JamesKingsley commited on
Commit
76d2426
·
1 Parent(s): 99ba1d7

deploy app to space

Browse files
Files changed (4) hide show
  1. App.py +193 -0
  2. lda_model.joblib +3 -0
  3. topic_labels.joblib +3 -0
  4. vectorizer.joblib +3 -0
App.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ import gradio as gr
3
+ import re
4
+ import pandas as pd
5
+ import joblib
6
+ import datetime
7
+ import matplotlib.pyplot as plt
8
+ from io import BytesIO
9
+ from nltk.tokenize import TreebankWordTokenizer
10
+ from nltk.stem import WordNetLemmatizer
11
+ from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
12
+ import os
13
+ import time
14
+ import zipfile
15
+
16
+ # Load models and label mapping
17
+ lda = joblib.load("lda_model.joblib")
18
+ vectorizer = joblib.load("vectorizer.joblib")
19
+ auto_labels = joblib.load("topic_labels.joblib")
20
+
21
+ #Optional topic summaries
22
+ topic_summaries = {
23
+ "Politics & Gun Rights": "Discussions about government policies, laws, gun control, and rights.",
24
+ "Computing & Hardware": "Technical issues and terms related to computer hardware and drivers.",
25
+ "Programming & Software": "Programming terms, file handling, software output.",
26
+ "Sports & Games": "Topics related to teams, players, seasons, and matches.",
27
+ "Health & Medicine": "Diseases, treatment, healthcare, and medical facilities.",
28
+ "Religion & Philosophy": "Talks involving faith, belief systems, philosophical views.",
29
+ "Space & NASA": "Space exploration, NASA missions, satellites, and astronomy.",
30
+ "Cryptography & Security": "Discussions on encryption, digital security, and data protection.",
31
+ "Internet & Networking": "Terms around internet use, FTP, web versions, and networks.",
32
+ "Middle East Politics & Conflicts": "Topics involving Israel, Armenia, conflict regions."
33
+ }
34
+
35
+ #Tokenizer and lemmatizer
36
+ tokenizer = TreebankWordTokenizer()
37
+ lemmatizer = WordNetLemmatizer()
38
+
39
+ # --- Utility Functions ---
40
+
41
+ def preprocess(text):
42
+ text = re.sub(r'\W+', ' ', text.lower())
43
+ tokens = tokenizer.tokenize(text)
44
+ tokens = [lemmatizer.lemmatize(w) for w in tokens if w not in ENGLISH_STOP_WORDS and len(w) > 2 and w.isalpha()]
45
+ return ' '.join(tokens)
46
+
47
+ def get_topic_keywords(model, vectorizer, topic_idx, top_n=10):
48
+ feature_names = vectorizer.get_feature_names_out()
49
+ topic = model.components_[topic_idx]
50
+ top_indices = topic.argsort()[:-top_n - 1:-1]
51
+ return [feature_names[i] for i in top_indices]
52
+
53
+ def plot_topic_distribution(distribution, labels):
54
+ plt.figure(figsize=(8, 4))
55
+ plt.bar(range(len(distribution)), distribution, tick_label=labels)
56
+ plt.xticks(rotation=45, ha="right")
57
+ plt.ylabel("Probability")
58
+ plt.title("Topic Distribution")
59
+ plt.tight_layout()
60
+ buf = BytesIO()
61
+ plt.savefig(buf, format="png")
62
+ plt.close()
63
+ buf.seek(0)
64
+ return Image.open(buf)
65
+
66
+ def save_prediction_file(text):
67
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
68
+ filename = f"lda_prediction_{timestamp}.txt"
69
+ with open(filename, "w", encoding="utf-8") as f:
70
+ f.write(text)
71
+ return filename
72
+
73
+ def cleanup_old_predictions(directory=".", extension=".txt", max_age_minutes=10):
74
+ now = time.time()
75
+ max_age = max_age_minutes * 60
76
+ for fname in os.listdir(directory):
77
+ if fname.endswith(extension) and fname.startswith("lda_prediction_"):
78
+ full_path = os.path.join(directory, fname)
79
+ if os.path.isfile(full_path) and (now - os.path.getmtime(full_path)) > max_age:
80
+ try:
81
+ os.remove(full_path)
82
+ except Exception as e:
83
+ print(f"Failed to delete {fname}: {e}")
84
+
85
+ def download_log():
86
+ zip_filename = "lda_predictions_log.zip"
87
+ with zipfile.ZipFile(zip_filename, "w", zipfile.ZIP_DEFLATED) as zipf:
88
+ zipf.write("lda_predictions_log.csv")
89
+ return zip_filename
90
+
91
+ def save_feedback(text, feedback):
92
+ timestamp = datetime.datetime.now().isoformat()
93
+ log_entry = pd.DataFrame([{
94
+ "timestamp": timestamp,
95
+ "feedback": feedback,
96
+ "text_excerpt": text[:300].replace('\n', ' ') + "..."
97
+ }])
98
+ feedback_log = "lda_feedback_log.csv"
99
+ log_entry.to_csv(feedback_log, mode='a', header=not os.path.exists(feedback_log), index=False)
100
+ return " Feedback recorded. Thank you!"
101
+
102
+ # --- Main Prediction Function ---
103
+
104
+ def predict_topic(text_input, file_input):
105
+ cleanup_old_predictions()
106
+
107
+ if file_input is not None:
108
+ text = file_input.read().decode("utf-8")
109
+ elif text_input.strip():
110
+ text = text_input
111
+ else:
112
+ return "Please provide input", None, None
113
+
114
+ cleaned = preprocess(text)
115
+ bow = vectorizer.transform([cleaned])
116
+ topic_distribution = lda.transform(bow)[0]
117
+ dominant_topic = topic_distribution.argmax()
118
+ label = auto_labels.get(dominant_topic, f"Topic {dominant_topic+1}")
119
+ top_words = get_topic_keywords(lda, vectorizer, dominant_topic)
120
+ summary = topic_summaries.get(label, "No summary available.")
121
+
122
+ # Confidence threshold warning
123
+ confidence_threshold = 0.4
124
+ if topic_distribution[dominant_topic] < confidence_threshold:
125
+ label += " ( Low confidence)"
126
+ summary = " The model is uncertain. Try providing more context or a longer input."
127
+
128
+ # Log entry
129
+ timestamp = datetime.datetime.now().isoformat()
130
+ log_entry = pd.DataFrame([{
131
+ "timestamp": timestamp,
132
+ "predicted_topic": label,
133
+ "dominant_topic_index": dominant_topic,
134
+ "top_words": ", ".join(top_words),
135
+ "text_excerpt": text[:300].replace('\n', ' ') + "..."
136
+ }])
137
+ log_path = "lda_predictions_log.csv"
138
+ log_entry.to_csv(log_path, mode='a', header=not os.path.exists(log_path), index=False)
139
+
140
+ chart = plot_topic_distribution(topic_distribution, [auto_labels.get(i, f"Topic {i+1}") for i in range(len(topic_distribution))])
141
+
142
+ result = f" **Predicted Topic:** {label}\n\n"
143
+ result += f" **Summary:** {summary}\n\n"
144
+ result += f" **Top Words:** {', '.join(top_words)}\n\n"
145
+ result += " **Topic Distribution:**\n"
146
+ for idx, prob in enumerate(topic_distribution):
147
+ tlabel = auto_labels.get(idx, f"Topic {idx+1}")
148
+ result += f"{tlabel}: {prob:.3f}\n"
149
+
150
+ prediction_file = save_prediction_file(result)
151
+ return result, chart, prediction_file
152
+
153
+ # --- Gradio Interface ---
154
+
155
+ with gr.Blocks() as demo:
156
+ gr.Markdown("## Topic Modeling with LDA")
157
+ gr.Markdown("Upload a `.txt` file or paste in text. See predicted topic, keywords, and a chart.")
158
+
159
+ with gr.Row():
160
+ with gr.Column():
161
+ text_input = gr.Textbox(lines=10, label=" Paste Text")
162
+ file_input = gr.File(label=" Or Upload a .txt File", file_types=[".txt"])
163
+ predict_btn = gr.Button(" Predict Topic")
164
+ download_btn = gr.Button("⬇ Download All Logs")
165
+
166
+ feedback_input = gr.Radio(
167
+ choices=["Accurate", " Inaccurate", "Unclear"],
168
+ label=" Was this prediction useful?",
169
+ interactive=True
170
+ )
171
+ feedback_btn = gr.Button("Submit Feedback")
172
+ feedback_output = gr.Textbox(visible=False)
173
+
174
+ with gr.Column():
175
+ output_text = gr.Textbox(label=" Prediction Result")
176
+ output_chart = gr.Image(type="pil", label=" Topic Distribution")
177
+ download_prediction = gr.File(label="⬇ Download This Prediction")
178
+
179
+ predict_btn.click(
180
+ fn=predict_topic,
181
+ inputs=[text_input, file_input],
182
+ outputs=[output_text, output_chart, download_prediction]
183
+ )
184
+
185
+ download_btn.click(fn=download_log, outputs=[gr.File()])
186
+
187
+ feedback_btn.click(
188
+ fn=save_feedback,
189
+ inputs=[text_input, feedback_input],
190
+ outputs=[feedback_output]
191
+ )
192
+
193
+ demo.launch()
lda_model.joblib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3371484707c0ca3a35348aab1134eb9fbb2376ec30808fc65916c5852419758b
3
+ size 4572069
topic_labels.joblib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5d73a67d3020a72d2b6a70491eaabc006f46ed077d4fedecb5d33d3a63d01792
3
+ size 146
vectorizer.joblib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9b71e13c424eaef2f0aa60ebb99805e0909f3b28db74d22e2e2f764d63a414d2
3
+ size 371927