<jupyter_start><jupyter_text>Import data<jupyter_code>ruta =  os.getcwd()+"\\data\\"
dfs = []
for file in os.listdir(ruta):
    print(f"Abriendo {file}")
    dfs.append(pd.read_csv(ruta+file,encoding='utf-8'))
print([len(x) for x in dfs])
print(sum([len(x) for x in dfs]))
df = pd.concat(dfs,ignore_index = True)

#df.columns
df.drop('Unnamed: 0',axis=1,inplace=True)
#df.Last_Name.notnull()
df.loc[df['extended_tweet.full_text'].notnull(), 'text'] = df['extended_tweet.full_text']


pd.set_option('display.max_colwidth', -1)
#borrar extended.tweet.full_text, ya no sirve
df.drop('extended_tweet.full_text',axis=1,inplace=True)
#prueba

df = df.sample(1000)<jupyter_output><empty_output><jupyter_text>Remover links<jupyter_code>df['text'].replace({"http\\S+": '<linkremoved>'}, inplace=True, regex=True)
for texto in df['text']:
    print(texto)<jupyter_output>a quien puta le importa que estén saqueando cosas MATERIALES a cadenas MILLONARIAS mientras los carabineros y militares nos están M A T A N D O !!! enfermos culiaos compartan información útil.
@meganoticiascl @TVN @T13 @chilevision #ChileResiste #ChileDesperto #ChileSeCanso
Ya No nos hacen weones #ChileDesperto 🇨🇱 💪 #fuerzachile <linkremoved>
Policia conteniendo a DELINCUENTES que saquean Sodimac en Coquimbo

"#ChileResiste" "#ChileDesperto" <linkremoved>
Sí, si es necesario. La ley de donaciones para las universidades lo demuestra. Para que sea equitativo, sí, si es necesario. Después del impuesto, pueda hacer lo que quiera con su dinero.
Supermercados cerrados!
Sin embargo lider de carrera esta abierto pero atendiendo por turnos.
#Copiapo #supermercadoscopiapo
#regiondeatacama #Atacama #supermercado #super #Copiapó #ToquedeQuedaChile #toquedequeda #ChileProtests #domingo20 #20Octubre  #Chile #ChileDesperto
Nuestro  futuro
Estas imágenes se repiten, Piñera eres un idiota más y eres el[...]<jupyter_text>remove usernames<jupyter_code>df['text'].replace({"@[^\\s]+": '<usernameremoved>'}, inplace=True, regex=True)<jupyter_output><empty_output><jupyter_text>remove duplicates - Quizas esto debieramos no hacerlo. Deben haber bots que publican lo mismo<jupyter_code>df.drop_duplicates(['text'],keep='first', inplace=True)
# numero de usuarios
tweets_by_user_data = df.groupby('user.screen_name').agg('size').sort_values(ascending=False).reset_index()
len(tweets_by_user_data)<jupyter_output><empty_output><jupyter_text>remove digits, puntuaactions, symbols<jupyter_code>punctuation
punctuation+='¡¿'
punctuation
#Remove digits and puntuaction
remove_digits = str.maketrans(digits, ' '*len(digits))#remove_digits = str.maketrans('', '', digits)
remove_punctuation = str.maketrans(punctuation, ' '*len(punctuation))#remove_punctuation = str.maketrans('', '', punctuation)
remove_hashtags_caracter = str.maketrans('#', ' '*len('#'))
#las palabras de los hashtag se mantiene, pero no el simbolo. 
import unidecode

data = []
for tweet in df['text']:
    tweet = tweet.translate(remove_digits)
    #tweet = tweet.lower() it wasn't a good idea,, we lost a lot of
    tweet = tweet.translate(remove_punctuation)
    tweet = tweet.translate(remove_hashtags_caracter)
    tweet = tweet.lower()
    tweet = unidecode.unidecode(tweet)
    #tweet = tweet.strip().split()
    #filtered_words = [word for word in tweet if word not in stopWords]
    #corpus[id_tweet]= filtered_words
    #id_tweet+=1
    data.append(tweet)<jupyter_output><empty_output><jupyter_text>Twitter tokenizer<jupyter_code>from nltk.tokenize import TweetTokenizer
tknzr = TweetTokenizer()
def sent_to_words(sentences):
    for sentence in sentences:
        yield(tknzr.tokenize(sentence))

data_words = list(sent_to_words(data))<jupyter_output><empty_output><jupyter_text>Create bigram and trigram models<jupyter_code># Build the bigram and trigram models
#quizas el min count es muy bajo
#documentaicon de bigramas 
#https://www.machinelearningplus.com/nlp/topic-modeling-gensim-python/#3importpackages
min_count = int(len(df)*0.02)
bigram = gensim.models.Phrases(data_words, min_count=min_count, threshold=1) # higher threshold fewer phrases.
trigram = gensim.models.Phrases(bigram[data_words], min_count =min_count, threshold=1)  

# Faster way to get a sentence clubbed as a trigram/bigram
bigram_mod = gensim.models.phrases.Phraser(bigram)
trigram_mod = gensim.models.phrases.Phraser(trigram)

# See trigram example
print(trigram_mod[bigram_mod[data_words[1]]])
# See trigram example
#print(trigram_mod[bigram_mod[data_words[1]]])
for i in range(0,5):
    print(trigram_mod[bigram_mod[data_words[i]]])<jupyter_output>['a', 'quien', 'puta', 'le', 'importa', 'que', 'esten', 'saqueando', 'cosas', 'materiales', 'a', 'cadenas', 'millonarias', 'mientras', 'los', 'carabineros', 'y', 'militares', 'nos', 'estan', 'm', 'a', 't', 'a', 'n', 'd', 'o', 'enfermos', 'culiaos', 'compartan', 'informacion', 'util', 'usernameremoved_usernameremoved_usernameremoved_usernameremoved', 'chileresiste', 'chiledesperto', 'chilesecanso']
['ya', 'no', 'nos', 'hacen', 'weones', 'chiledesperto', 'fuerzachile', 'linkremoved']
['policia', 'conteniendo', 'a', 'delincuentes', 'que', 'saquean', 'sodimac', 'en', 'coquimbo', 'chileresiste', 'chiledesperto_linkremoved']
['si', 'si', 'es', 'necesario', 'la', 'ley', 'de', 'donaciones', 'para', 'las', 'universidades', 'lo', 'demuestra', 'para', 'que', 'sea', 'equitativo', 'si', 'si', 'es', 'necesario', 'despues', 'del', 'impuesto', 'pueda', 'hacer', 'lo_que', 'quiera', 'con', 'su', 'dinero']
['supermercados', 'cerrados', 'sin', 'embargo', 'lider', 'de', 'carrera', 'esta', 'abierto', 'pero'[...]<jupyter_text>Remove stopwords, make bigrams and lemmatize<jupyter_code>def remove_stopwords(texts):
    return [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]

def make_bigrams(texts):
    return [bigram_mod[doc] for doc in texts]

def make_trigrams(texts):
    return [trigram_mod[bigram_mod[doc]] for doc in texts]

def lemmatization(texts, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']):
    """https://spacy.io/api/annotation"""
    texts_out = []
    for sent in texts:
        doc = nlp(" ".join(sent)) 
        texts_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags])
    return texts_out
# Remove Stop Words
data_words_nostops = remove_stopwords(data_words)

# Form Bigrams
data_words_bigrams = make_bigrams(data_words_nostops)


# Initialize spacy 'en' model, keeping only tagger component (for efficiency)
!python -m spacy download es

nlp = spacy.load('es', disable=['parser', 'ner'])

#sera mejor ocupar wordnetlemattizer?
# Do lemmatization keeping only noun, adj, vb, adv
data_lemmatized = lemmatization(data_words_bigrams, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV'])

print(data_lemmatized[:1])<jupyter_output>[['importar', 'saquear', 'coser', 'material', 'cadena', 'millonario', 'carabinero', 'militar', 'estan', 'enfermo', 'compartir', 'util', 'chiledesperto', 'chilesecanso']]<jupyter_text>Create dictionary and corpus for topic modeling<jupyter_code>#The two main inputs to the LDA topic model are the dictionary(id2word) and the corpus
# Create Dictionary
id2word = corpora.Dictionary(data_lemmatized)

# Create Corpus
texts = data_lemmatized

# Term Document Frequency
corpus = [id2word.doc2bow(text) for text in texts]

# View
print(corpus[:1])
[[(id2word[id], freq) for id, freq in cp] for cp in corpus[:1]]<jupyter_output><empty_output><jupyter_text>Calcular mejor numero de topicos<jupyter_code>from gensim.test.utils import common_corpus, common_dictionary
from gensim.models.wrappers import LdaMallet
import os
os.environ.update({'MALLET_HOME':r'C:\mallet'}) #OJO!, por alguna razon mallet solo puede estar disponible en esa carpeta

path_to_mallet_binary = "C:\\mallet\\bin\\mallet"<jupyter_output><empty_output><jupyter_text>Build LDA Mallet Model<jupyter_code>num_topic = 2
start = time.time()


ldamallet = LdaMallet(path_to_mallet_binary, corpus=corpus, num_topics=num_topic, id2word=id2word)

end = time.time()
hours, rem = divmod(end-start, 3600)
minutes, seconds = divmod(rem, 60)
print("{:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))
# Show Topics
#pprint(ldamallet.show_topics(formatted=False, num_topics=num_topics))
pprint(ldamallet.show_topics(num_topics=num_topic, num_words=10, log=False, formatted=True))

# Compute Coherence Score
coherence_model_ldamallet = CoherenceModel(model=ldamallet, texts=data_lemmatized, dictionary=id2word, coherence='c_v')
coherence_ldamallet = coherence_model_ldamallet.get_coherence()
print('\nCoherence Score: ', coherence_ldamallet)<jupyter_output>Coherence Score:  0.3190677353406149<jupyter_text>Mapear text con clean text<jupyter_code>df.head(1)
data[0]
df["clean_text"] = data

df.head()<jupyter_output><empty_output><jupyter_text>Highest topic per tweet<jupyter_code>def format_topics_sentences(ldamodel=ldamallet, corpus=corpus, texts=data):
    # Init output
    sent_topics_df = pd.DataFrame()

    # Get main topic in each document
    for i, row in enumerate(ldamodel[corpus]):
        row = sorted(row, key=lambda x: (x[1]), reverse=True)
        # Get the Dominant topic, Perc Contribution and Keywords for each document
        for j, (topic_num, prop_topic) in enumerate(row):
            if j == 0:  # => dominant topic
                wp = ldamodel.show_topic(topic_num)
                topic_keywords = ", ".join([word for word, prop in wp])
                sent_topics_df = sent_topics_df.append(pd.Series([int(topic_num), round(prop_topic,4), topic_keywords]), ignore_index=True)
            else:
                break
    sent_topics_df.columns = ['Dominant_Topic', 'Perc_Contribution', 'Topic_Keywords']

    # Add original text to the end of the output
    contents = pd.Series(texts)
    sent_topics_df = pd.concat([sent_topics_df, contents], axis=1)
    return(sent_topics_df)


df_topic_sents_keywords = format_topics_sentences(ldamodel=ldamallet, corpus=corpus, texts=data)

# Format
df_dominant_topic = df_topic_sents_keywords.reset_index()
df_dominant_topic.columns = ['Document_No', 'Dominant_Topic', 'Topic_Perc_Contrib', 'Keywords', 'Text']

# Show
df_dominant_topic.head(20)<jupyter_output><empty_output><jupyter_text>Find the most representative tweets for each topic<jupyter_code># Group top 5 sentences under each topic
numero_de_tweets_por_topico = 10


sent_topics_sorteddf_mallet = pd.DataFrame()
sent_topics_outdf_grpd = df_topic_sents_keywords.groupby('Dominant_Topic') # esta matriz contiene todos los tweets con el porcentaje de contribucion y max topico. se agrupa y se obtiene lo q queremos

for i, grp in sent_topics_outdf_grpd:
    sent_topics_sorteddf_mallet = pd.concat([sent_topics_sorteddf_mallet, 
                                             grp.sort_values(['Perc_Contribution'], ascending=False).head(numero_de_tweets_por_topico)], 
                                            axis=0)


# Reset Index    
sent_topics_sorteddf_mallet.reset_index(drop=True, inplace=True)

# Format
sent_topics_sorteddf_mallet.columns = ['Topic_Num', "Topic_Perc_Contrib", "Keywords", "Text"]

# Show
# sent_topics_sorteddf_mallet

sent_topics_sorteddf_mallet.head()
sent_topics_sorteddf_mallet.rename(columns={"Text": "clean_text"},inplace=True)<jupyter_output><empty_output><jupyter_text>find original text - username- created at<jupyter_code>sent_topics_sorteddf_mallet = pd.merge(sent_topics_sorteddf_mallet, df, on='clean_text', how='left')

from datetime import datetime
sent_topics_sorteddf_mallet.to_csv("Topic_Modeling_num_topics_"+str(num_topic)+"_"+datetime.now().strftime("%Y_%m_%d_%H_%M")+".csv")
sent_topics_sorteddf_mallet.Topic_Num = sent_topics_sorteddf_mallet.Topic_Num.astype(int)
json_tweets = sent_topics_sorteddf_mallet.to_json(orient="records")<jupyter_output><empty_output><jupyter_text>Topic distribution across documents<jupyter_code># Number of Documents for Each Topic
topic_counts = df_topic_sents_keywords['Dominant_Topic'].value_counts()

# Percentage of Documents for Each Topic
topic_contribution = round(topic_counts/topic_counts.sum(), 4)

# Topic Number and Keywords
topic_num_keywords = df_topic_sents_keywords[['Dominant_Topic', 'Topic_Keywords']]

# Concatenate Column wise
df_dominant_topics = pd.concat([topic_num_keywords.drop_duplicates(subset='Dominant_Topic', keep='first').sort_values(by=['Dominant_Topic']).reset_index(drop=True), topic_counts.sort_index(), topic_contribution.sort_index()], axis=1)

# Change Column names
df_dominant_topics.columns = ['Dominant_Topic', 'Topic_Keywords', 'Num_Documents', 'Perc_Documents']


#funciona perfecto
df_dominant_topics
df_dominant_topics.Dominant_Topic = df_dominant_topics.Dominant_Topic.astype(int)
json_tweets<jupyter_output><empty_output><jupyter_text>Visualize topics with Mallet<jupyter_code>prueba = gensim.models.wrappers.ldamallet.malletmodel2ldamodel(ldamallet)

pyLDAvis.enable_notebook(local=True)

data = pyLDAvis.gensim.prepare(prueba, corpus,id2word, mds='pcoa')

#data.to_
pyLDAvis.save_html(data, json_tweets, "Topic_Modeling_num_topics_test"+".html")

data<jupyter_output><empty_output><jupyter_text>Obtener tweets<jupyter_code>#df[df['texto_completo'].str.contains("carpathy")]['texto_completo']<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1308694335049985, 'fraction_numerical': 0.006513177824901545, 'mean_word_length': 6.781378903948144, 'pattern_counts': {'":': 3, '<': 73, '<?xml version=': 0, '>': 76, 'https://': 2, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 5, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '18', 'dir': 'jupyter-structured-clean-dedup', 'id': '662312', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 5045, 'n_tokens_neox': 4880, 'n_words': 965, 'path': 'notebooks/Topic-Modeling-EstoPasaEnChile-Obtener-tweets-mas-relevantes-Informacion-agregada.ipynb', 'repo_name': 'gonzalezf/pyLDAvis', 'size': '13204'}