Shirjannn commited on
Commit
fd208b1
·
verified ·
1 Parent(s): a335695

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +189 -97
app.py CHANGED
@@ -8,21 +8,22 @@ from sentence_transformers import SentenceTransformer
8
  import tempfile
9
  from datetime import datetime
10
  import plotly.graph_objects as go
 
11
  import logging
12
 
13
  # تنظیمات لاگ‌گیری
14
  logging.basicConfig(level=logging.INFO)
15
  logger = logging.getLogger(__name__)
16
 
17
- # بارگیری مدل با مدیریت خطا
18
  try:
19
  model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
20
- logger.info("Model loaded successfully")
21
  except Exception as e:
22
- logger.error(f"Error loading model: {str(e)}")
23
  raise
24
 
25
- # پایگاه دانش به‌روزرسانی شده
26
  KNOWLEDGE_BASE = {
27
  "Existentialism": {
28
  "icon": "🌌",
@@ -60,25 +61,23 @@ KNOWLEDGE_BASE = {
60
  }
61
  }
62
 
63
- # پیش‌محاسبه بردارها با مدیریت خطا
64
  for school in KNOWLEDGE_BASE:
65
  try:
66
  texts = KNOWLEDGE_BASE[school]["texts"]
67
  KNOWLEDGE_BASE[school]["vectors"] = model.encode(texts)
68
- logger.info(f"Successfully encoded texts for {school}")
69
  except Exception as e:
70
- logger.error(f"Error encoding texts for {school}: {str(e)}")
71
- # مقدار پیش‌فرض برای حالت خطا
72
  KNOWLEDGE_BASE[school]["vectors"] = np.random.rand(len(texts), 384)
73
 
74
- # پاسخ فلسفی بهبودیافته
75
  def philosophical_response(text):
76
- if not text or not text.strip():
77
- return "🚨 لطفاً یک متن فلسفی برای تحلیل وارد کنید"
78
 
79
  text_lower = text.lower()
80
  responses = {
81
- "freedom": "🦋 سارتر می‌گوید: انسان محکوم به آزادی است",
82
  "choice": "⚖️ کییرکگور: زندگی در انتخاب‌های ما معنا می‌یابد",
83
  "existence": "🌫 هایدگر: بودن در جهان است",
84
  "control": "🧘 مارکوس اورلیوس: تنها افکارت را می‌توانی کنترل کنی",
@@ -91,29 +90,133 @@ def philosophical_response(text):
91
 
92
  for keyword, response in responses.items():
93
  if keyword in text_lower:
94
- current_time = datetime.now().strftime("%H:%M")
95
- return f"⏳ {current_time} - {response}"
96
 
97
  return "💭 فلسفه هنر پرسیدن سوال‌های درست است"
98
 
99
- # تحلیل متن با مدیریت خطای جامع
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  def analyze_text(text):
101
  try:
102
- # بررسی متن ورودی
103
- if not text or not text.strip():
104
  return {
105
- "report": "**🚨 لطفاً یک متن فلسفی معتبر وارد کنید**",
106
  "plot": None,
107
  "timeline": None,
108
  "concept_map": None,
109
  "philosophers": ""
110
  }
111
 
112
- # کدگذاری متن کاربر
113
  try:
114
  user_vec = model.encode([text])
115
  except Exception as e:
116
- logger.error(f"Encoding error: {str(e)}")
117
  return {
118
  "report": "**⚠️ خطا در پردازش متن. لطفاً متن دیگری امتحان کنید**",
119
  "plot": None,
@@ -122,22 +225,20 @@ def analyze_text(text):
122
  "philosophers": ""
123
  }
124
 
125
- # یافتن بهترین تطابق
126
  best_match = None
127
  highest_score = -1
128
 
129
  for school, data in KNOWLEDGE_BASE.items():
130
  try:
131
  sims = cosine_similarity(user_vec, data["vectors"])
132
- current_score = np.max(sims)
133
- if current_score > highest_score:
134
- highest_score = current_score
135
  best_match = school
136
  except Exception as e:
137
- logger.warning(f"Comparison error with {school}: {str(e)}")
138
  continue
139
 
140
- # آماده‌سازی نتایج
141
  school_data = KNOWLEDGE_BASE.get(best_match, {})
142
  psych = school_data.get("psychology", {
143
  "positive": ["بینش جدید"],
@@ -145,7 +246,6 @@ def analyze_text(text):
145
  "solution": ["مطالعه بیشتر"]
146
  })
147
 
148
- # تولید گزارش
149
  report = f"""
150
  <div style="font-family: 'B Nazanin', Arial, sans-serif; direction: rtl; text-align: right;">
151
  <div style="background: {school_data.get('color', '#6c757d')}20; padding: 20px; border-radius: 10px; border-right: 5px solid {school_data.get('color', '#6c757d')};">
@@ -194,7 +294,6 @@ def analyze_text(text):
194
  </div>
195
  """
196
 
197
- # فیلسوفان مرتبط
198
  philosophers = ""
199
  if best_match:
200
  philosophers = "### 🎓 فیلسوفان مرتبط\n" + "\n".join(
@@ -203,14 +302,14 @@ def analyze_text(text):
203
 
204
  return {
205
  "report": report,
206
- "plot": create_semantic_plot(user_vec, best_match) if best_match else None,
207
  "timeline": generate_timeline(),
208
- "concept_map": generate_concept_graph(),
209
  "philosophers": philosophers
210
  }
211
 
212
  except Exception as e:
213
- logger.error(f"Unexpected error in analysis: {str(e)}")
214
  return {
215
  "report": "**⚠️ خطای غیرمنتظره رخ داد. لطفاً دوباره تلاش کنید**",
216
  "plot": None,
@@ -219,82 +318,75 @@ def analyze_text(text):
219
  "philosophers": ""
220
  }
221
 
222
- # رابط کاربری با مدیریت خطا
223
  def build_ui():
224
- try:
225
- with gr.Blocks(title="تحلیلگر فلسفی", theme=gr.themes.Soft()) as app:
226
- with gr.Row():
227
- gr.Markdown("""
228
- <div style="text-align: center;">
229
- <h1>🌌 تحلیلگر فلسفی</h1>
230
- <p>کشف معانی پنهان در اندیشه‌های شما</p>
231
- </div>
232
- """)
233
-
234
- with gr.Row():
235
- with gr.Column():
236
- input_text = gr.Textbox(
237
- label="📜 متن فلسفی خود را وارد کنید",
238
- placeholder="مثال: انسان محکوم به آزادی است...",
239
- lines=3
240
- )
241
- examples = gr.Examples(
242
- examples=[
243
- ["انسان محکوم به آزادی است"],
244
- ["مانع همان راه است"],
245
- ["آنچه مرا نکشد، قوی‌ترم می‌کند"]
246
- ],
247
- inputs=[input_text],
248
- label="نمونه‌های فلسفی"
249
- )
250
-
251
- with gr.Column():
252
- plot_output = gr.Plot(label="نمودار معنایی")
253
-
254
- with gr.Tabs():
255
- with gr.TabItem("گزارش تحلیل"):
256
- report_output = gr.HTML()
257
 
258
- with gr.TabItem("فیلسوفان"):
259
- philosophers_output = gr.Markdown()
 
 
 
 
260
 
261
- analyze_btn = gr.Button("تحلیل متن", variant="primary")
262
- clear_btn = gr.Button("پاک کردن")
263
 
264
- # مدیریت رویدادها
265
- analyze_btn.click(
266
- lambda text: analyze_text(text),
267
- inputs=[input_text],
268
- outputs=[
269
- report_output,
270
- plot_output,
271
- philosophers_output
272
- ]
273
- )
274
 
275
- clear_btn.click(
276
- lambda: ["", None, ""],
277
- outputs=[input_text, plot_output, philosophers_output]
278
- )
279
 
280
- return app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
 
282
- except Exception as e:
283
- logger.error(f"UI build error: {str(e)}")
284
- with gr.Blocks() as fallback_app:
285
- gr.Markdown("# تحلیلگر فلسفی (حالت ساده)")
286
- text_input = gr.Textbox(label="متن خود را وارد کنید")
287
- output = gr.Markdown()
288
- gr.Button("تحلیل").click(
289
- lambda x: f"نتیجه: {x[:100]}..." if x else "لطفاً متن وارد کنید",
290
- inputs=text_input,
291
- outputs=output
292
- )
293
- return fallback_app
294
 
295
  if __name__ == "__main__":
296
  try:
297
  app = build_ui()
298
  app.launch(share=True)
299
  except Exception as e:
300
- logger.critical(f"Application failed: {str(e)}")
 
8
  import tempfile
9
  from datetime import datetime
10
  import plotly.graph_objects as go
11
+ from plotly.subplots import make_subplots
12
  import logging
13
 
14
  # تنظیمات لاگ‌گیری
15
  logging.basicConfig(level=logging.INFO)
16
  logger = logging.getLogger(__name__)
17
 
18
+ # بارگیری مدل
19
  try:
20
  model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
21
+ logger.info("مدل با موفقیت بارگذاری شد")
22
  except Exception as e:
23
+ logger.error(f"خطا در بارگذاری مدل: {str(e)}")
24
  raise
25
 
26
+ # پایگاه دانش بهبود یافته
27
  KNOWLEDGE_BASE = {
28
  "Existentialism": {
29
  "icon": "🌌",
 
61
  }
62
  }
63
 
64
+ # پیش‌محاسبه بردارها
65
  for school in KNOWLEDGE_BASE:
66
  try:
67
  texts = KNOWLEDGE_BASE[school]["texts"]
68
  KNOWLEDGE_BASE[school]["vectors"] = model.encode(texts)
 
69
  except Exception as e:
70
+ logger.error(f"خطا در کدگذاری متون برای {school}: {str(e)}")
 
71
  KNOWLEDGE_BASE[school]["vectors"] = np.random.rand(len(texts), 384)
72
 
73
+ # پاسخ‌های فلسفی
74
  def philosophical_response(text):
75
+ if not text.strip():
76
+ return "لطفاً یک متن فلسفی وارد کنید"
77
 
78
  text_lower = text.lower()
79
  responses = {
80
+ "freedom": "🦋 سارتر: انسان محکوم به آزادی است",
81
  "choice": "⚖️ کییرکگور: زندگی در انتخاب‌های ما معنا می‌یابد",
82
  "existence": "🌫 هایدگر: بودن در جهان است",
83
  "control": "🧘 مارکوس اورلیوس: تنها افکارت را می‌توانی کنترل کنی",
 
90
 
91
  for keyword, response in responses.items():
92
  if keyword in text_lower:
93
+ return response
 
94
 
95
  return "💭 فلسفه هنر پرسیدن سوال‌های درست است"
96
 
97
+ # ایجاد نمودار زمانی
98
+ def generate_timeline():
99
+ try:
100
+ fig = go.Figure()
101
+
102
+ for school, data in KNOWLEDGE_BASE.items():
103
+ for name, year in zip(data["philosophers"], data["timeline"]):
104
+ fig.add_trace(go.Scatter(
105
+ x=[year],
106
+ y=[0],
107
+ mode="markers+text",
108
+ marker=dict(size=20, color=data["color"]),
109
+ name=f"{data['icon']} {name}",
110
+ text=f"{data['icon']} {name}",
111
+ hoverinfo="text",
112
+ hovertext=f"<b>{name}</b><br>{school}<br>{year} CE",
113
+ textposition="top center"
114
+ ))
115
+
116
+ fig.update_layout(
117
+ title="🕰️ Timeline فلسفی",
118
+ xaxis_title="سال",
119
+ showlegend=False,
120
+ height=300,
121
+ margin=dict(l=20, r=20, t=40, b=20),
122
+ plot_bgcolor='rgba(0,0,0,0)'
123
+ )
124
+
125
+ return fig
126
+ except Exception as e:
127
+ logger.error(f"خطا در تولید timeline: {str(e)}")
128
+ return go.Figure()
129
+
130
+ # ایجاد نقشه مفهومی
131
+ def generate_concept_map():
132
+ try:
133
+ fig = go.Figure()
134
+
135
+ for school, data in KNOWLEDGE_BASE.items():
136
+ fig.add_trace(go.Scatter(
137
+ x=[1],
138
+ y=[1],
139
+ mode="markers+text",
140
+ marker=dict(size=20, color=data["color"]),
141
+ name=school,
142
+ text=data["icon"],
143
+ hovertext="<br>".join(data["key_concepts"])
144
+ ))
145
+
146
+ fig.update_layout(
147
+ title="🧭 نقشه مفهومی",
148
+ height=300,
149
+ showlegend=True
150
+ )
151
+
152
+ return fig
153
+ except Exception as e:
154
+ logger.error(f"خطا در تولید نقشه مفهومی: {str(e)}")
155
+ return go.Figure()
156
+
157
+ # ایجاد نمودار فضای معنایی
158
+ def create_semantic_plot(user_vec, best_match):
159
+ try:
160
+ fig = go.Figure()
161
+
162
+ # نقاط مربوط به مکاتب فلسفی
163
+ for school, data in KNOWLEDGE_BASE.items():
164
+ reduced = data["vectors"][:,:2]
165
+ fig.add_trace(go.Scatter(
166
+ x=reduced[:,0],
167
+ y=reduced[:,1],
168
+ mode="markers",
169
+ name=school,
170
+ marker=dict(
171
+ color=data["color"],
172
+ size=10,
173
+ symbol=data["icon"][0]
174
+ ),
175
+ text=data["texts"],
176
+ hoverinfo="text"
177
+ ))
178
+
179
+ # نقطه مربوط به متن کاربر
180
+ if user_vec is not None:
181
+ reduced = user_vec[0][:2]
182
+ fig.add_trace(go.Scatter(
183
+ x=[reduced[0]],
184
+ y=[reduced[1]],
185
+ mode="markers",
186
+ name="متن شما",
187
+ marker=dict(
188
+ color="#FF6B6B",
189
+ size=15,
190
+ symbol="star"
191
+ )
192
+ ))
193
+
194
+ fig.update_layout(
195
+ title="🗺️ فضای معنایی",
196
+ height=400
197
+ )
198
+
199
+ return fig
200
+ except Exception as e:
201
+ logger.error(f"خطا در تولید نمودار معنایی: {str(e)}")
202
+ return go.Figure()
203
+
204
+ # تحلیل متن اصلی
205
  def analyze_text(text):
206
  try:
207
+ if not text.strip():
 
208
  return {
209
+ "report": "**🚨 لطفاً یک متن فلسفی وارد کنید**",
210
  "plot": None,
211
  "timeline": None,
212
  "concept_map": None,
213
  "philosophers": ""
214
  }
215
 
 
216
  try:
217
  user_vec = model.encode([text])
218
  except Exception as e:
219
+ logger.error(f"خطا در پردازش متن: {str(e)}")
220
  return {
221
  "report": "**⚠️ خطا در پردازش متن. لطفاً متن دیگری امتحان کنید**",
222
  "plot": None,
 
225
  "philosophers": ""
226
  }
227
 
 
228
  best_match = None
229
  highest_score = -1
230
 
231
  for school, data in KNOWLEDGE_BASE.items():
232
  try:
233
  sims = cosine_similarity(user_vec, data["vectors"])
234
+ score = np.max(sims)
235
+ if score > highest_score:
236
+ highest_score = score
237
  best_match = school
238
  except Exception as e:
239
+ logger.warning(f"خطا در مقایسه با {school}: {str(e)}")
240
  continue
241
 
 
242
  school_data = KNOWLEDGE_BASE.get(best_match, {})
243
  psych = school_data.get("psychology", {
244
  "positive": ["بینش جدید"],
 
246
  "solution": ["مطالعه بیشتر"]
247
  })
248
 
 
249
  report = f"""
250
  <div style="font-family: 'B Nazanin', Arial, sans-serif; direction: rtl; text-align: right;">
251
  <div style="background: {school_data.get('color', '#6c757d')}20; padding: 20px; border-radius: 10px; border-right: 5px solid {school_data.get('color', '#6c757d')};">
 
294
  </div>
295
  """
296
 
 
297
  philosophers = ""
298
  if best_match:
299
  philosophers = "### 🎓 فیلسوفان مرتبط\n" + "\n".join(
 
302
 
303
  return {
304
  "report": report,
305
+ "plot": create_semantic_plot(user_vec, best_match),
306
  "timeline": generate_timeline(),
307
+ "concept_map": generate_concept_map(),
308
  "philosophers": philosophers
309
  }
310
 
311
  except Exception as e:
312
+ logger.error(f"خطای غیرمنتظره در تحلیل: {str(e)}")
313
  return {
314
  "report": "**⚠️ خطای غیرمنتظره رخ داد. لطفاً دوباره تلاش کنید**",
315
  "plot": None,
 
318
  "philosophers": ""
319
  }
320
 
321
+ # رابط کاربری
322
  def build_ui():
323
+ with gr.Blocks(title="تحلیلگر فلسفی", theme=gr.themes.Soft()) as app:
324
+ with gr.Row():
325
+ gr.Markdown("""
326
+ <div style="text-align: center;">
327
+ <h1>🌌 تحلیلگر فلسفی</h1>
328
+ <p>کشف معانی پنهان در اندیشه‌های شما</p>
329
+ </div>
330
+ """)
331
+
332
+ with gr.Row():
333
+ with gr.Column():
334
+ input_text = gr.Textbox(
335
+ label="📜 متن فلسفی خود را وارد کنید",
336
+ placeholder="مثال: انسان محکوم به آزادی است...",
337
+ lines=3
338
+ )
339
+ examples = gr.Examples(
340
+ examples=[
341
+ ["انسان محکوم به آزادی است"],
342
+ ["مانع همان راه است"],
343
+ ["آنچه مرا نکشد، قوی‌ترم می‌کند"]
344
+ ],
345
+ inputs=[input_text],
346
+ label="نمونه‌های فلسفی"
347
+ )
 
 
 
 
 
 
 
 
348
 
349
+ with gr.Column():
350
+ plot_output = gr.Plot(label="نمودار معنایی")
351
+
352
+ with gr.Tabs():
353
+ with gr.TabItem("گزارش تحلیل"):
354
+ report_output = gr.HTML()
355
 
356
+ with gr.TabItem("تایم‌لاین"):
357
+ timeline_output = gr.Plot()
358
 
359
+ with gr.TabItem("نقشه مفهومی"):
360
+ concept_map_output = gr.Plot()
 
 
 
 
 
 
 
 
361
 
362
+ with gr.TabItem("فیلسوفان"):
363
+ philosophers_output = gr.Markdown()
 
 
364
 
365
+ analyze_btn = gr.Button("تحلیل متن", variant="primary")
366
+ clear_btn = gr.Button("پاک کردن")
367
+
368
+ analyze_btn.click(
369
+ lambda text: analyze_text(text),
370
+ inputs=[input_text],
371
+ outputs=[
372
+ report_output,
373
+ plot_output,
374
+ timeline_output,
375
+ concept_map_output,
376
+ philosophers_output
377
+ ]
378
+ )
379
+
380
+ clear_btn.click(
381
+ lambda: ["", None, None, None, ""],
382
+ outputs=[input_text, plot_output, timeline_output, concept_map_output, philosophers_output]
383
+ )
384
 
385
+ return app
 
 
 
 
 
 
 
 
 
 
 
386
 
387
  if __name__ == "__main__":
388
  try:
389
  app = build_ui()
390
  app.launch(share=True)
391
  except Exception as e:
392
+ logger.critical(f"خطا در اجرای برنامه: {str(e)}")