KevSun commited on
Commit
6cf5666
1 Parent(s): ae20ea4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -16
app.py CHANGED
@@ -1,33 +1,110 @@
1
  import streamlit as st
2
- from sentence_transformers import SentenceTransformer
 
 
 
3
  from langdetect import detect, DetectorFactory
 
 
 
4
 
5
- st.set_page_config(page_title="Simple Text Analysis", layout="wide")
6
 
7
  @st.cache_resource
8
  def load_model():
9
  return SentenceTransformer('distiluse-base-multilingual-cased-v1')
10
 
11
  DetectorFactory.seed = 0
12
- model = load_model()
13
 
14
- st.title("Simple Text Analysis")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  user_input = st.text_area("Enter your text here:")
16
 
17
- if st.button("Analyze"):
18
  if user_input:
19
- try:
20
- lang = detect(user_input)
21
- st.write(f"Detected language: {lang}")
22
-
23
- embedding = model.encode(user_input)
24
- st.write(f"Text embedding shape: {embedding.shape}")
25
- st.write("First few values of the embedding:")
26
- st.write(embedding[:5])
27
- except Exception as e:
28
- st.error(f"An error occurred: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  else:
30
  st.warning("Please enter some text to analyze.")
31
 
32
  st.sidebar.title("About")
33
- st.sidebar.info("This is a simple text analysis app.")
 
1
  import streamlit as st
2
+ from sentence_transformers import SentenceTransformer, util
3
+ from sklearn.decomposition import LatentDirichletAllocation
4
+ from sklearn.feature_extraction.text import CountVectorizer
5
+ from sklearn.manifold import TSNE
6
  from langdetect import detect, DetectorFactory
7
+ import numpy as np
8
+ import matplotlib.pyplot as plt
9
+ import pandas as pd
10
 
11
+ st.set_page_config(page_title="Multilingual Text Analysis System", layout="wide")
12
 
13
  @st.cache_resource
14
  def load_model():
15
  return SentenceTransformer('distiluse-base-multilingual-cased-v1')
16
 
17
  DetectorFactory.seed = 0
18
+ multi_embedding_model = load_model()
19
 
20
+ class WordEmbeddingAgent:
21
+ def __init__(self, model):
22
+ self.model = model
23
+
24
+ def get_embeddings(self, words):
25
+ return self.model.encode(words)
26
+
27
+ class SimilarityAgent:
28
+ def __init__(self, model):
29
+ self.model = model
30
+
31
+ def compute_similarity(self, text1, text2):
32
+ embedding1 = self.model.encode(text1, convert_to_tensor=True)
33
+ embedding2 = self.model.encode(text2, convert_to_tensor=True)
34
+ return util.pytorch_cos_sim(embedding1, embedding2).item()
35
+
36
+ class TopicModelingAgent:
37
+ def __init__(self, n_components=5):
38
+ self.lda_model = LatentDirichletAllocation(n_components=n_components, random_state=42)
39
+
40
+ def fit_transform(self, texts, lang):
41
+ stop_words = 'english' if lang == 'en' else None
42
+ vectorizer = CountVectorizer(max_df=0.9, min_df=2, stop_words=stop_words)
43
+ dtm = vectorizer.fit_transform(texts)
44
+ self.lda_model.fit(dtm)
45
+ return self.lda_model.transform(dtm), vectorizer
46
+
47
+ def get_topics(self, vectorizer, num_words=5):
48
+ topics = {}
49
+ for idx, topic in enumerate(self.lda_model.components_):
50
+ topics[idx] = [vectorizer.get_feature_names_out()[i] for i in topic.argsort()[-num_words:]]
51
+ return topics
52
+
53
+ def detect_language(text):
54
+ try:
55
+ return detect(text)
56
+ except:
57
+ return "unknown"
58
+
59
+ @st.cache_data
60
+ def tsne_visualization(embeddings, words):
61
+ tsne = TSNE(n_components=2, random_state=42)
62
+ embeddings_2d = tsne.fit_transform(embeddings)
63
+ df = pd.DataFrame(embeddings_2d, columns=['x', 'y'])
64
+ df['word'] = words
65
+ return df
66
+
67
+ st.title("Multilingual Text Analysis System")
68
  user_input = st.text_area("Enter your text here:")
69
 
70
+ if st.button("Analyze") or user_input:
71
  if user_input:
72
+ lang = detect_language(user_input)
73
+ st.write(f"Detected language: {lang}")
74
+
75
+ embedding_agent = WordEmbeddingAgent(multi_embedding_model)
76
+ similarity_agent = SimilarityAgent(multi_embedding_model)
77
+ topic_modeling_agent = TopicModelingAgent()
78
+
79
+ words = user_input.split()
80
+
81
+ with st.spinner("Generating word embeddings..."):
82
+ embeddings = embedding_agent.get_embeddings(words)
83
+ st.success("Word Embeddings Generated.")
84
+
85
+ with st.spinner("Creating t-SNE visualization..."):
86
+ tsne_df = tsne_visualization(embeddings, words)
87
+ fig, ax = plt.subplots()
88
+ ax.scatter(tsne_df['x'], tsne_df['y'])
89
+ for i, word in enumerate(tsne_df['word']):
90
+ ax.annotate(word, (tsne_df['x'][i], tsne_df['y'][i]))
91
+ st.pyplot(fig)
92
+
93
+ with st.spinner("Extracting topics..."):
94
+ texts = [user_input, "Another text to improve topic modeling."]
95
+ topic_distr, vectorizer = topic_modeling_agent.fit_transform(texts, lang)
96
+ topics = topic_modeling_agent.get_topics(vectorizer)
97
+ st.subheader("Topics Extracted:")
98
+ for topic, words in topics.items():
99
+ st.write(f"Topic {topic}: {', '.join(words)}")
100
+
101
+ with st.spinner("Computing similarity..."):
102
+ text2 = "Otro texto de ejemplo para comparación de similitud." if lang != 'en' else "Another example text for similarity comparison."
103
+ similarity_score = similarity_agent.compute_similarity(user_input, text2)
104
+ st.write(f"Similarity Score with example text: {similarity_score:.4f}")
105
+
106
  else:
107
  st.warning("Please enter some text to analyze.")
108
 
109
  st.sidebar.title("About")
110
+ st.sidebar.info("This app performs multilingual text analysis using various NLP techniques.")