-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathteco_main.py
137 lines (116 loc) · 6.56 KB
/
teco_main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import time
import cProfile
from gensim.models import KeyedVectors
from sklearn.feature_extraction.text import TfidfVectorizer
from teco_config.load_config import *
from proverb_selector.sel_utils.file_manager import read_write_obj_file
from teco_twitterbot.twitter_bot import run_twitter_bot
from teco_twitterbot.twitter_bot import call_teco
from teco_twitterbot.twitter_bot import load_twitter_confs
def test_twitter_bot(all_expressions, model, dict_forms_labels, dict_lemmas_labels, configs, gen_method, twitter_conf_file, post=True):
twitter_conf = load_twitter_confs(twitter_conf_file)
#print(twitter_conf)
while True:
print("Run Twitter bot...")
run_twitter_bot(all_expressions=all_expressions, model=model, dict_forms_labels=dict_forms_labels,
dict_lemmas_labels=dict_lemmas_labels, configs=configs, gen_method=gen_method, twitter_conf=twitter_conf, post=post)
sleep = twitter_conf[0]
print("Sleep for", sleep)
time.sleep(sleep)
def test_headline_gen(all_expressions, model, dict_forms_labels, dict_lemmas_labels, configs, method_order):
noticias_teste = [
# um que não tem keywords
# "BADABADA PA PA PIM",
# um que so' da' com Subs
# "Mourinho culpa-me por ter sido demitido do Chelsea. Esteve sempre contra mim",
# "VÍDEO: erro de Otamendi e Rodrigo Pinho dá vantagem ao Marítimo",
"existências",
"A educação deve falar com a ciência",
"Agência europeia confirma pedidos de vacinas e responde dentro de semanas",
"Cristina Ferreira levou os amigos e tentou mudar tudo na TVI mas as derrotas sucessivas ameaçam o futuro",
"Coronavírus: Profissionais de saúde sofreram estigma por parte de vizinhos",
"Pareceu que o adversário queria passar mais do que nós à próxima eliminatória",
"Covid-19: Proibição de circulação entre concelhos tem 10 exceções",
"Liga dos Campeões: Noite de Champions com arte, fortuna e altruísmo de Bruno Fernandes",
# "Alentejo: No Verão de 2021, o Redondo volta à alegria das Ruas Floridas",
#"MotoGP: Miguel Oliveira voa para a vitória no GP de Portugal",
"Orçamento do Estado 2021: Finanças culpam PSD por coligações negativas que terão custado já mais de 20 milhões",
#"Coronavírus: Estado de emergência: contactos limitados ao “mínimo indispensável” e celebrações até seis pessoas",
# "Natal? É difícil antecipar. Privados prontos a libertar camas.",
# "MotoGP: pilotos escolheram os melhores do ano e Miguel Oliveira destacou-se",
# "Em 19 dias houve mais mortes por Covid do que nos últimos cinco meses"
]
for n in noticias_teste:
headline, generated = call_teco(n, all_expressions, model, dict_forms_labels, dict_lemmas_labels, configs, method_order)
if generated:
print(headline, "->", generated[1])
def test_console_gen(all_expressions, model, dict_forms_labels, dict_lemmas_labels, configs, method_order):
while True:
text = input("> ")
if text:
headline, generated = call_teco(text, all_expressions, model, dict_forms_labels, dict_lemmas_labels, configs,
method_order)
print("> "+generated[1] if generated else "...")
else:
print("> Adeus.")
break
def dict_forms_to_lemmas_label(dict_forms_labels):
dict_lemmas_labels = {}
for form in dict_forms_labels:
for entry in dict_forms_labels[form]:
if entry[1] not in dict_lemmas_labels:
dict_lemmas_labels[entry[1]] = []
dict_lemmas_labels[entry[1]].append(entry)
return dict_lemmas_labels
if __name__ == '__main__':
# ----- CONFIGURATION -----
# ----- expressions; output_db; we_model; lexicon; tfidf_words; tfidf_occur; 1st_sel_amount; sel_method; sleep_time
file_paths = load_config()
print("Expressions", file_paths[EXPRESSIONS])
all_expressions = read_write_obj_file(1, None, file_paths[EXPRESSIONS])
print("Model", file_paths[EMBEDDINGS])
model = KeyedVectors.load(file_paths[EMBEDDINGS])
print("Lexicon", file_paths[LEXICON])
dict_forms_labels = read_write_obj_file(1, None, file_paths[LEXICON])
#print("Frequencies", file_paths[FREQUENCIES])
#freqs = read_write_obj_file(1, None, file_paths[FREQUENCIES])
configs = [file_paths[FIRST_SEL], int(file_paths[N_FIRST_SEL]), file_paths[FINAL_SEL]]
gen_method = file_paths[GEN_METHOD]
print("Gen method", gen_method)
#sleep_time = int(file_paths[TWEET_INTERVAL])
#print("Sleep time", sleep_time)
twitter_conf_file = file_paths[TWITTER_CONFS]
print("Twitter confs", twitter_conf_file)
dict_lemmas_labels = dict_forms_to_lemmas_label(dict_forms_labels)
#test_console_gen(all_expressions, model, dict_forms_labels, dict_lemmas_labels, configs, gen_method)
#test_headline_gen(all_expressions, model, dict_forms_labels, dict_lemmas_labels, configs, gen_method)
test_twitter_bot(all_expressions, model, dict_forms_labels, dict_lemmas_labels, configs, gen_method, twitter_conf_file, post=True)
#cProfile.run('test_headline_gen(all_expressions, model, dict_forms_labels, dict_lemmas_labels, configs, gen_method)')
# vectorizer = TfidfVectorizer(max_df=0.75, min_df=2)
# vectors = vectorizer.fit_transform(all_expressions)
# print(vectors.shape)
# features = vectorizer.get_feature_names()
# #print(len(features))
#
# new_exp = ["eu não gosto de brincar contigo", "as armas e os barões assinalados", "no caminho do bem",
# "esta vida são dois dias e um é para acordar", "as vidas não têm prazo de validade", "piloto obrigado a mudar de número",
# "tudo na vida tem uma consequência", "como um vício que liberta todo o bom e mau em mim"]
# vectors_new = vectorizer.transform(new_exp)
# features = vectorizer.get_feature_names()
# print(vectors_new.shape)
#
# a_vectors = vectors.toarray()
# a_vectors_new = vectors_new.toarray()
#
# for c1, v in enumerate(a_vectors_new):
# #print(v)
# max_id = -1
# max_sim = -1
# for c2, vn in enumerate(a_vectors):
# sim = cosine_similarity([v], [vn])[0][0]
# if sim > max_sim:
# max_sim = sim
# max_id = c2
# print(sim, "*", new_exp[c1], "*", all_expressions[max_id])
#selection = init_prov_selector_standard(0, ["Pareceu que o adversário queria passar mais do que nós à próxima eliminatória"], all_expressions, 10)
#print(selection)