Shirjannn commited on
Commit
da0bc53
·
verified ·
1 Parent(s): 37a06d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -112
app.py CHANGED
@@ -14,26 +14,50 @@ import warnings
14
  warnings.filterwarnings('ignore')
15
 
16
  # ------------------------
17
- # تنظیمات Hugging Face Spaces
18
  # ------------------------
19
- # مسیرهای فایل در Spaces
20
  csv_path = "stoic_quotes_full.csv"
21
  zip_path = "archive.zip"
22
 
23
- # ایجاد داده‌های نمونه اگر فایلی وجود نداشته باشد
24
- if not os.path.exists(csv_path) and not os.path.exists(zip_path):
25
- sample_data = {
26
- "philosopher": ["Seneca", "Marcus Aurelius", "Epictetus"],
27
- "quote": [
28
- "We suffer more often in imagination than in reality.",
29
- "You have power over your mind - not outside events.",
30
- "It's not what happens to you, but how you react that matters."
31
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  }
33
- pd.DataFrame(sample_data).to_csv(csv_path, index=False)
34
 
35
  # ------------------------
36
- # بارگذاری مدل با کش Hugging Face
37
  # ------------------------
38
  try:
39
  model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2', device='cpu')
@@ -42,7 +66,7 @@ except Exception as e:
42
  model = None
43
 
44
  # ------------------------
45
- # بارگذاری داده‌ها (بهینه‌شده برای Spaces)
46
  # ------------------------
47
  def build_school_data():
48
  school_data_dynamic = {}
@@ -61,7 +85,7 @@ def build_school_data():
61
  except Exception as e:
62
  print(f"Error loading CSV: {e}")
63
 
64
- # حالت ZIP (برای Spaces بهتر از git-lfs استفاده کنید)
65
  elif os.path.exists(zip_path):
66
  try:
67
  with zipfile.ZipFile(zip_path, 'r') as z:
@@ -100,7 +124,7 @@ def build_school_data():
100
  school_data = build_school_data()
101
 
102
  # ------------------------
103
- # پروفایل مکاتب (بهینه‌شده برای نمایش در Spaces)
104
  # ------------------------
105
  school_profiles = {
106
  "Stoicism": {
@@ -113,7 +137,7 @@ school_profiles = {
113
  }
114
  }
115
 
116
- # Complete profiles for any detected schools
117
  for name in school_data.keys():
118
  if name not in school_profiles:
119
  school_profiles[name] = {
@@ -122,86 +146,33 @@ for name in school_data.keys():
122
  }
123
 
124
  # ------------------------
125
- # رابط Gradio (بهینه‌شده برای Spaces)
126
  # ------------------------
127
- with gr.Blocks(title="Philosophical Analyzer", theme=gr.themes.Soft()) as demo:
128
- gr.Markdown("""
129
- # 🏛️ Philosophical Text Analyzer
130
- *Discover which philosophical school your text aligns with*
131
- """)
132
-
133
- with gr.Row():
134
- with gr.Column():
135
- input_text = gr.Textbox(
136
- label="📝 Enter your text",
137
- placeholder="Type or paste philosophical text here...",
138
- lines=5
139
- )
140
- with gr.Row():
141
- submit_btn = gr.Button("Analyze", variant="primary")
142
- clear_btn = gr.Button("Clear")
143
-
144
- with gr.Column():
145
- school = gr.Textbox(label="🏫 Closest School")
146
- score = gr.Textbox(label="🔍 Similarity Score")
147
- timeline = gr.Textbox(label="⏳ Historical Period")
148
-
149
- with gr.Accordion("Detailed Analysis", open=False):
150
- with gr.Row():
151
- with gr.Column():
152
- profile_box = gr.Textbox(label="📖 School Profile", lines=3)
153
- best_quote = gr.Textbox(label="💬 Most Similar Quote", lines=3)
154
- with gr.Column():
155
- psych_box = gr.Textbox(label="🧠 Psychological Profile", lines=4)
156
-
157
- conceptual_map = gr.Plot(label="🧭 Semantic Map")
158
 
159
- def analyze_text(text):
160
- if not text.strip():
161
- return "", "", "", "", "", None, ""
162
-
163
- if model is None:
164
- return "Model not loaded", "", "", "", "", None, ""
165
-
166
- try:
167
- user_vec = model.encode([text])[0]
168
- best_school, best_score, best_match = None, -1, ""
169
-
170
- for school, data in school_data.items():
171
- for quote in data["quotes"]:
172
- quote_vec = model.encode([quote])[0]
173
- score = cosine_similarity([user_vec], [quote_vec])[0][0]
174
- if score > best_score:
175
- best_score, best_school, best_match = score, school, quote
176
-
177
- if best_school is None:
178
- return "No match found", "", "", "", "", None, ""
179
-
180
- semantic_plot = create_semantic_plot(user_vec, best_school)
181
- school_profile = school_profiles[best_school]["profile"]
182
- timeline = school_profiles[best_school]["timeline"]
183
- psych_output = psychological_analysis(text)
184
 
185
- return best_school, f"{best_score:.2f}", timeline, school_profile, best_match, semantic_plot, psych_output
186
-
187
- except Exception as e:
188
- print(f"Error: {e}")
189
- return f"Error: {str(e)}", "", "", "", "", None, ""
190
-
191
- submit_btn.click(
192
- analyze_text,
193
- inputs=input_text,
194
- outputs=[school, score, timeline, profile_box, best_quote, conceptual_map, psych_box]
195
- )
196
-
197
- clear_btn.click(
198
- lambda: ("", "", "", "", "", None, ""),
199
- outputs=[school, score, timeline, profile_box, best_quote, conceptual_map, psych_box]
200
- )
201
 
202
- # تابع create_semantic_plot و psychological_analysis مانند قبل باقی می‌مانند
203
- # (همان توابعی که در کد قبلی تعریف شده بودند)
 
 
 
 
204
 
 
 
 
205
  def create_semantic_plot(user_vec, best_school):
206
  if best_school not in school_data:
207
  return None
@@ -238,33 +209,98 @@ def create_semantic_plot(user_vec, best_school):
238
 
239
  fig.update_layout(
240
  title=f"Semantic Map: Your Text vs {best_school}",
241
- showlegend=True
 
 
242
  )
243
  return fig
244
 
245
- def psychological_analysis(text):
 
 
 
246
  if not text.strip():
247
- return "No text provided"
248
 
249
- text_lower = text.lower()
250
- results = []
251
- for category in psychological_categories:
252
- for keyword in category["keywords"]:
253
- if re.search(rf"\b{re.escape(keyword.lower())}\b", text_lower):
254
- results.append(category)
255
- break
256
 
257
- if not results:
258
- return "No specific psychological patterns detected"
 
259
 
260
- output = "## Psychological Analysis:\n\n"
261
- for item in results:
262
- output += f"### {item['name']}\n"
263
- output += f"- ✅ **Positive:** {item['followed']}\n"
264
- output += f"- ❌ **Negative:** {item['ignored']}\n\n"
265
- return output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
 
267
  # ------------------------
268
- # اجرا در Hugging Face Spaces
269
  # ------------------------
270
- demo.launch()
 
 
14
  warnings.filterwarnings('ignore')
15
 
16
  # ------------------------
17
+ # تنظیمات مسیر فایل‌ها
18
  # ------------------------
 
19
  csv_path = "stoic_quotes_full.csv"
20
  zip_path = "archive.zip"
21
 
22
+ # ------------------------
23
+ # دسته‌بندی روانشناختی
24
+ # ------------------------
25
+ psychological_categories = [
26
+ {
27
+ "name": "Moral guilt",
28
+ "keywords": ["guilt", "remorse", "regret", "پشیمانی", "عذاب وجدان", "ندامت"],
29
+ "followed": "Helps in personal growth, emotional release, and reconciliation.",
30
+ "ignored": "Can lead to chronic anxiety, regret, or depression."
31
+ },
32
+ {
33
+ "name": "Freedom & Will",
34
+ "keywords": ["freedom", "free will", "liberty", "independence", "آزادی", "اراده", "خودمختاری"],
35
+ "followed": "Encourages autonomy and a sense of responsibility.",
36
+ "ignored": "May result in feelings of helplessness or existential crisis."
37
+ },
38
+ {
39
+ "name": "Altruism",
40
+ "keywords": ["altruism", "help", "helping", "helped", "assist", "support", "others",
41
+ "نوع‌دوستی", "کمک", "یاری", "حمایت"],
42
+ "followed": "Improves social bonding and personal satisfaction.",
43
+ "ignored": "May cause loneliness or self-centered thinking."
44
+ },
45
+ {
46
+ "name": "Anxiety & Fear",
47
+ "keywords": ["anxiety", "fear", "worry", "stress", "ترس", "اضطراب", "استرس", "نگرانی"],
48
+ "followed": "Leads to caution and preparedness.",
49
+ "ignored": "Might cause mental blocks, phobia, or stress disorders."
50
+ },
51
+ {
52
+ "name": "Rationality",
53
+ "keywords": ["reason", "logic", "rational", "عقل", "منطق", "استدلال", "عقلانی"],
54
+ "followed": "Supports wise decision-making and clarity.",
55
+ "ignored": "Can result in poor judgments and emotional impulses."
56
  }
57
+ ]
58
 
59
  # ------------------------
60
+ # بارگذاری مدل
61
  # ------------------------
62
  try:
63
  model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2', device='cpu')
 
66
  model = None
67
 
68
  # ------------------------
69
+ # بارگذاری داده‌ها
70
  # ------------------------
71
  def build_school_data():
72
  school_data_dynamic = {}
 
85
  except Exception as e:
86
  print(f"Error loading CSV: {e}")
87
 
88
+ # حالت ZIP
89
  elif os.path.exists(zip_path):
90
  try:
91
  with zipfile.ZipFile(zip_path, 'r') as z:
 
124
  school_data = build_school_data()
125
 
126
  # ------------------------
127
+ # پروفایل مکاتب
128
  # ------------------------
129
  school_profiles = {
130
  "Stoicism": {
 
137
  }
138
  }
139
 
140
+ # Complete profiles
141
  for name in school_data.keys():
142
  if name not in school_profiles:
143
  school_profiles[name] = {
 
146
  }
147
 
148
  # ------------------------
149
+ # تحلیل روانشناختی
150
  # ------------------------
151
+ def psychological_analysis(text):
152
+ if not text.strip():
153
+ return "No text provided for analysis."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
 
155
+ text_lower = text.lower()
156
+ results = []
157
+ for category in psychological_categories:
158
+ for keyword in category["keywords"]:
159
+ if re.search(rf"\b{re.escape(keyword.lower())}\b", text_lower):
160
+ results.append(category)
161
+ break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
 
163
+ if not results:
164
+ return "No clear psychological indicators found."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
 
166
+ output = "## Psychological Analysis:\n\n"
167
+ for item in results:
168
+ output += f"### {item['name']}\n"
169
+ output += f"- ✅ **Positive:** {item['followed']}\n"
170
+ output += f"- ❌ **Negative:** {item['ignored']}\n\n"
171
+ return output.strip()
172
 
173
+ # ------------------------
174
+ # رسم نقشه مفهومی
175
+ # ------------------------
176
  def create_semantic_plot(user_vec, best_school):
177
  if best_school not in school_data:
178
  return None
 
209
 
210
  fig.update_layout(
211
  title=f"Semantic Map: Your Text vs {best_school}",
212
+ showlegend=True,
213
+ xaxis_title="PCA Dimension 1",
214
+ yaxis_title="PCA Dimension 2"
215
  )
216
  return fig
217
 
218
+ # ------------------------
219
+ # تحلیل متن
220
+ # ------------------------
221
+ def analyze_text(text):
222
  if not text.strip():
223
+ return "", "", "", "", "", None, ""
224
 
225
+ if model is None:
226
+ return "Model not loaded", "", "", "", "", None, ""
 
 
 
 
 
227
 
228
+ try:
229
+ user_vec = model.encode([text])[0]
230
+ best_school, best_score, best_match = None, -1, ""
231
 
232
+ for school, data in school_data.items():
233
+ for quote in data["quotes"]:
234
+ quote_vec = model.encode([quote])[0]
235
+ score = cosine_similarity([user_vec], [quote_vec])[0][0]
236
+ if score > best_score:
237
+ best_score, best_school, best_match = score, school, quote
238
+
239
+ if best_school is None:
240
+ return "No match found", "", "", "", "", None, ""
241
+
242
+ semantic_plot = create_semantic_plot(user_vec, best_school)
243
+ school_profile = school_profiles[best_school]["profile"]
244
+ timeline = school_profiles[best_school]["timeline"]
245
+ psych_output = psychological_analysis(text)
246
+
247
+ return best_school, f"{best_score:.2f}", timeline, school_profile, best_match, semantic_plot, psych_output
248
+
249
+ except Exception as e:
250
+ print(f"Error in analysis: {e}")
251
+ return f"Error: {str(e)}", "", "", "", "", None, ""
252
+
253
+ def clear_fields():
254
+ return "", "", "", "", "", None, ""
255
+
256
+ # ------------------------
257
+ # رابط Gradio
258
+ # ------------------------
259
+ with gr.Blocks(title="Philosophical Analyzer", theme=gr.themes.Soft()) as demo:
260
+ gr.Markdown("""
261
+ # �️ Philosophical Text Analyzer
262
+ *Discover which philosophical school your text aligns with*
263
+ """)
264
+
265
+ with gr.Row():
266
+ with gr.Column():
267
+ input_text = gr.Textbox(
268
+ label="📝 Enter your text",
269
+ placeholder="Type or paste philosophical text here...",
270
+ lines=5
271
+ )
272
+ with gr.Row():
273
+ submit_btn = gr.Button("Analyze", variant="primary")
274
+ clear_btn = gr.Button("Clear")
275
+
276
+ with gr.Column():
277
+ school = gr.Textbox(label="🏫 Closest School")
278
+ score = gr.Textbox(label="🔍 Similarity Score")
279
+ timeline = gr.Textbox(label="⏳ Historical Period")
280
+
281
+ with gr.Accordion("Detailed Analysis", open=False):
282
+ with gr.Row():
283
+ with gr.Column():
284
+ profile_box = gr.Textbox(label="📖 School Profile", lines=3)
285
+ best_quote = gr.Textbox(label="💬 Most Similar Quote", lines=3)
286
+ with gr.Column():
287
+ psych_box = gr.Textbox(label="🧠 Psychological Profile", lines=4)
288
+
289
+ conceptual_map = gr.Plot(label="🧭 Semantic Map")
290
+
291
+ submit_btn.click(
292
+ analyze_text,
293
+ inputs=input_text,
294
+ outputs=[school, score, timeline, profile_box, best_quote, conceptual_map, psych_box]
295
+ )
296
+
297
+ clear_btn.click(
298
+ clear_fields,
299
+ outputs=[school, score, timeline, profile_box, best_quote, conceptual_map, psych_box]
300
+ )
301
 
302
  # ------------------------
303
+ # اجرای برنامه
304
  # ------------------------
305
+ if __name__ == "__main__":
306
+ demo.launch()