Shirjannn commited on
Commit
7b95dad
·
verified ·
1 Parent(s): 885b6a0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +267 -118
app.py CHANGED
@@ -5,141 +5,290 @@ matplotlib.use('Agg')
5
  import matplotlib.pyplot as plt
6
  from sklearn.metrics.pairwise import cosine_similarity
7
  from sentence_transformers import SentenceTransformer
8
- from sklearn.decomposition import PCA
9
  import plotly.graph_objects as go
10
  from plotly.subplots import make_subplots
11
 
12
- # مدل زبانی برای تحلیل معنایی جملات
13
  model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
14
 
15
- # داده‌های مربوط به مکاتب فلسفی
16
- school_data = {
17
- "Stoicism": [
18
- "The key to happiness is accepting things we cannot control.",
19
- "Virtue is the only good.",
20
- "Live according to nature."
21
- ],
22
- "Existentialism": [
23
- "Existence precedes essence.",
24
- "Man is nothing else but what he makes of himself.",
25
- "Life has no inherent meaning; we create our own meaning."
26
- ],
27
- "Rationalism": [
28
- "Reason is the chief source of knowledge.",
29
- "I think, therefore I am.",
30
- "Innate ideas exist prior to experience."
31
- ],
32
- "Empiricism": [
33
- "Knowledge comes only from sensory experience.",
34
- "The mind is a blank slate at birth.",
35
- "All ideas originate in experience."
 
 
 
 
 
 
 
 
 
 
 
 
36
  ]
37
- }
38
 
39
- # داده‌های زمانی و پروفایل روانشناختی
40
- school_profiles = {
41
- "Stoicism": {"timeline": "3rd century BCE – 3rd century CE", "profile": "Calm, Resilient, Virtue-centered"},
42
- "Existentialism": {"timeline": "19th – 20th century", "profile": "Individualistic, Authentic, Anxious"},
43
- "Rationalism": {"timeline": "17th – 18th century", "profile": "Logical, Abstract, Confident"},
44
- "Empiricism": {"timeline": "17th – 18th century", "profile": "Practical, Observational, Experimental"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  }
46
 
47
- # تابع تحلیل و یافتن مکتب فلسفی
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  def analyze_text(text):
49
- if not text.strip():
50
- return "Please enter a philosophical text.", None, None, None, None, None
51
-
52
- user_vec = model.encode([text])[0]
53
-
54
- best_school = None
55
- best_score = -1
56
- best_match = ""
57
-
58
- for school, quotes in school_data.items():
59
- for quote in quotes:
60
- quote_vec = model.encode([quote])[0]
61
- score = cosine_similarity([user_vec], [quote_vec])[0][0]
62
- if score > best_score:
63
- best_score = score
64
- best_school = school
65
- best_match = quote
66
-
67
- # گراف مفهومی (Conceptual Map)
68
- semantic_plot = create_semantic_plot(user_vec, best_match, best_school)
69
-
70
- # بازگشت خروجی‌ها
71
- return (
72
- best_school,
73
- f"{best_score:.2f}",
74
- school_profiles[best_school]["profile"],
75
- school_profiles[best_school]["timeline"],
76
- best_match,
77
- semantic_plot
78
- )
79
-
80
- # تابع رسم گراف مفهومی
81
- def create_semantic_plot(user_vec, best_quote, best_school):
82
- ref_quotes = school_data[best_school]
83
- quote_vecs = model.encode(ref_quotes)
84
- labels = [f"Ref {i+1}" for i in range(len(ref_quotes))]
85
-
86
- all_vecs = np.vstack([user_vec, quote_vecs])
87
- pca = PCA(n_components=2)
88
- reduced_vecs = pca.fit_transform(all_vecs)
89
-
90
- fig = go.Figure()
91
- fig.add_trace(go.Scatter(
92
- x=[reduced_vecs[0][0]],
93
- y=[reduced_vecs[0][1]],
94
- mode='markers+text',
95
- text=["User Input"],
96
- name="User Input",
97
- textposition="top center",
98
- marker=dict(size=14, symbol='circle', color='blue')
99
- ))
100
-
101
- fig.add_trace(go.Scatter(
102
- x=reduced_vecs[1:, 0],
103
- y=reduced_vecs[1:, 1],
104
- mode='markers+text',
105
- text=labels,
106
- name="Reference Quotes",
107
- textposition="top center",
108
- marker=dict(size=12, symbol='square', color='orange')
109
- ))
110
-
111
- fig.update_layout(title="🧭 Conceptual Map", showlegend=False)
112
- return fig
113
 
114
- # رابط کاربری با Gradio
115
- with gr.Blocks(title="Philosophical Analyzer") as demo:
116
- gr.Markdown("## 📝 Enter Philosophical Text")
117
- input_text = gr.Textbox(lines=4, placeholder="Type or paste a philosophical text...")
 
 
 
 
118
 
119
- submit_btn = gr.Button("Analyze")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
- with gr.Row():
122
- with gr.Column():
123
- gr.Markdown("### 🕰️ Philosophy Timeline")
124
- timeline = gr.Textbox(label="Timeline")
125
 
126
- gr.Markdown("### 🧠 Philosophical School Detected:")
127
- school = gr.Textbox(label="School")
128
 
129
- gr.Markdown("### 📈 Similarity Score:")
130
- score = gr.Textbox(label="Similarity")
 
131
 
132
- gr.Markdown("### 🧬 Psychological Profile:")
133
- profile = gr.Textbox(label="Profile")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
- with gr.Column():
136
- conceptual_map = gr.Plot(label="🧭 Conceptual Map")
 
 
 
 
 
 
 
137
 
138
- with gr.Accordion("🧾 Most Similar Reference Quote", open=False):
139
- best_quote = gr.Textbox(label="Closest Match")
 
 
 
 
140
 
141
- submit_btn.click(fn=analyze_text, inputs=input_text,
142
- outputs=[school, score, profile, timeline, best_quote, conceptual_map])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
- # اجرا
145
- demo.launch()
 
 
 
5
  import matplotlib.pyplot as plt
6
  from sklearn.metrics.pairwise import cosine_similarity
7
  from sentence_transformers import SentenceTransformer
 
8
  import plotly.graph_objects as go
9
  from plotly.subplots import make_subplots
10
 
11
+ # Load model
12
  model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
13
 
14
+ # Psychological analysis function
15
+ def psychological_analysis(text):
16
+ rules = [
17
+ {
18
+ "keywords": ["guilt", "remorse"],
19
+ "aspect": "Moral guilt",
20
+ "followed": "Helps in personal growth, emotional release, and reconciliation.",
21
+ "ignored": "Can lead to chronic anxiety, regret, or depression."
22
+ },
23
+ {
24
+ "keywords": ["freedom", "free will"],
25
+ "aspect": "Freedom & Will",
26
+ "followed": "Encourages autonomy and a sense of responsibility.",
27
+ "ignored": "May result in feelings of helplessness or existential crisis."
28
+ },
29
+ {
30
+ "keywords": ["altruism", "help", "others"],
31
+ "aspect": "Altruism",
32
+ "followed": "Improves social bonding and personal satisfaction.",
33
+ "ignored": "May cause loneliness or self-centered thinking."
34
+ },
35
+ {
36
+ "keywords": ["anxiety", "fear"],
37
+ "aspect": "Anxiety & Fear",
38
+ "followed": "Leads to caution and preparedness.",
39
+ "ignored": "Might cause mental blocks, phobia, or stress disorders."
40
+ },
41
+ {
42
+ "keywords": ["reason", "logic"],
43
+ "aspect": "Rationality",
44
+ "followed": "Supports wise decision-making and clarity.",
45
+ "ignored": "Can result in poor judgments and emotional impulses."
46
+ }
47
  ]
 
48
 
49
+ results = []
50
+ lower_text = text.lower()
51
+
52
+ for rule in rules:
53
+ if any(keyword in lower_text for keyword in rule["keywords"]):
54
+ results.append({
55
+ "aspect": rule["aspect"],
56
+ "followed": rule["followed"],
57
+ "ignored": rule["ignored"]
58
+ })
59
+
60
+ return results
61
+
62
+ # Dummy: Semantic Plot
63
+ def create_semantic_plot(user_vec, best_match):
64
+ fig, ax = plt.subplots()
65
+ ax.set_title(f"Semantic Positioning: {best_match}")
66
+ ax.scatter(user_vec[0][0], user_vec[0][1], color='blue')
67
+ ax.text(user_vec[0][0], user_vec[0][1], f"{best_match}", fontsize=12)
68
+ ax.set_xlim(-1, 1)
69
+ ax.set_ylim(-1, 1)
70
+ ax.grid(True)
71
+ return fig
72
+
73
+ # Dummy: Conceptual Graph
74
+ def generate_concept_graph():
75
+ fig, ax = plt.subplots()
76
+ ax.set_title("Conceptual Map (Placeholder)")
77
+ ax.text(0.5, 0.5, "Key concepts will be mapped here.", ha='center', va='center', fontsize=12)
78
+ ax.axis('off')
79
+ return fig
80
+
81
+ # Smarter Reflection Response
82
+ def philosophical_response(text, school=None):
83
+ if school == "Existentialism":
84
+ return f"Your sentence reflects existential freedom, perhaps inviting thought on authenticity and the burden of choice."
85
+ elif school == "Stoicism":
86
+ return f"This seems to align with Stoic resilience and inner control, possibly invoking the dichotomy of control."
87
+ return f"This sentence echoes a philosophical sentiment. Possibly about meaning, freedom, or virtue: \"{text}\""
88
+
89
+ # Knowledge Base
90
+ KNOWLEDGE_BASE = {
91
+ "Existentialism": {
92
+ "icon": "🌌",
93
+ "color": "#4E79A7",
94
+ "philosophers": ["Jean-Paul Sartre", "Albert Camus", "Friedrich Nietzsche"],
95
+ "texts": [
96
+ "Existence precedes essence",
97
+ "Man is condemned to be free",
98
+ "What does not kill me makes me stronger"
99
+ ],
100
+ "timeline": [1943, 1942, 1889],
101
+ "psychology": {
102
+ "positive": ["Deep self-awareness", "Radical responsibility", "Authenticity"],
103
+ "negative": ["Existential anxiety", "Meaning crisis", "Freedom overwhelm"],
104
+ "solution": ["Logotherapy", "Existential group therapy", "Creative expression"]
105
+ },
106
+ "key_concepts": ["Freedom", "Authenticity", "Absurd", "Angst"]
107
+ },
108
+ "Stoicism": {
109
+ "icon": "🪨",
110
+ "color": "#59A14F",
111
+ "philosophers": ["Marcus Aurelius", "Epictetus", "Seneca"],
112
+ "texts": [
113
+ "The obstacle is the way",
114
+ "You have power over your mind—not outside events",
115
+ "We suffer more in imagination than in reality"
116
+ ],
117
+ "timeline": [180, 135, 65],
118
+ "psychology": {
119
+ "positive": ["Inner peace", "Resilience", "Emotional control"],
120
+ "negative": ["Emotional suppression", "Detachment", "Fatalism"],
121
+ "solution": ["Cognitive therapy", "Mindfulness meditation", "Negative visualization"]
122
+ },
123
+ "key_concepts": ["Virtue", "Dichotomy of Control", "Amor Fati", "Memento Mori"]
124
+ }
125
  }
126
 
127
+ # Precompute vectors
128
+ for school in KNOWLEDGE_BASE:
129
+ try:
130
+ texts = KNOWLEDGE_BASE[school]["texts"]
131
+ KNOWLEDGE_BASE[school]["vectors"] = np.array(model.encode(texts))
132
+ except:
133
+ KNOWLEDGE_BASE[school]["vectors"] = np.random.rand(len(texts), 384)
134
+
135
+ # Timeline generator
136
+ def generate_timeline():
137
+ try:
138
+ fig = make_subplots(rows=1, cols=1)
139
+ entries = []
140
+ for school, data in KNOWLEDGE_BASE.items():
141
+ for name, year in zip(data["philosophers"], data["timeline"]):
142
+ entries.append({
143
+ "year": year,
144
+ "name": name,
145
+ "school": school,
146
+ "color": data["color"],
147
+ "icon": data["icon"]
148
+ })
149
+ entries.sort(key=lambda x: x["year"])
150
+ for entry in entries:
151
+ fig.add_trace(go.Scatter(
152
+ x=[entry["year"]],
153
+ y=[0],
154
+ mode="markers+text",
155
+ marker=dict(size=20, color=entry["color"]),
156
+ name=f"{entry['icon']} {entry['name']}",
157
+ text=f"{entry['icon']} {entry['name']}",
158
+ hoverinfo="text",
159
+ hovertext=f"<b>{entry['name']}</b><br>{entry['school']}<br>{entry['year']} CE",
160
+ textposition="top center"
161
+ ))
162
+ fig.update_layout(
163
+ title="🕰️ Philosophical Timeline",
164
+ xaxis_title="Year",
165
+ showlegend=False,
166
+ height=300,
167
+ margin=dict(l=20, r=20, t=40, b=20),
168
+ plot_bgcolor='rgba(0,0,0,0)',
169
+ xaxis=dict(showgrid=True, gridcolor='lightgray'),
170
+ yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)
171
+ )
172
+ return fig
173
+ except:
174
+ return go.Figure()
175
+
176
+ # Text analysis
177
  def analyze_text(text):
178
+ try:
179
+ if not text.strip():
180
+ return "**🚨 Please enter a valid philosophical text.**", None, generate_timeline(), generate_concept_graph(), "", "", ""
181
+
182
+ user_vec = model.encode([text])
183
+ best_match = None
184
+ highest_score = -1
185
+
186
+ for school, data in KNOWLEDGE_BASE.items():
187
+ sims = cosine_similarity(user_vec, data["vectors"])
188
+ score = np.max(sims)
189
+ if score > highest_score:
190
+ highest_score = score
191
+ best_match = school
192
+
193
+ school_data = KNOWLEDGE_BASE[best_match]
194
+ psych = school_data["psychology"]
195
+ semantic_plot = create_semantic_plot(user_vec, best_match)
196
+ timeline = generate_timeline()
197
+ concept_map = generate_concept_graph()
198
+ reflect = philosophical_response(text, school=best_match)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
 
200
+ # Psychological profile (new)
201
+ psych_profile = psychological_analysis(text)
202
+ psych_output = ""
203
+ if psych_profile:
204
+ for item in psych_profile:
205
+ psych_output += f"- **{item['aspect']}**\n • If followed: {item['followed']}\n • If ignored: {item['ignored']}\n\n"
206
+ else:
207
+ psych_output = "No clear psychological indicators found."
208
 
209
+ report = f"""
210
+ <div>
211
+ <h2>{school_data['icon']} Philosophical School: <span style="color:{school_data['color']};">{best_match}</span></h2>
212
+ <p><strong>🧠 Confidence Score:</strong> {round(highest_score*100, 2)}%</p>
213
+ <p><strong>🔑 Key Concepts:</strong> {', '.join(school_data.get('key_concepts', []))}</p>
214
+ <h3>🧬 Psychological Effects</h3>
215
+ <ul>
216
+ <li><strong>Positive:</strong> {', '.join(psych["positive"])}</li>
217
+ <li><strong>Negative:</strong> {', '.join(psych["negative"])}</li>
218
+ <li><strong>Suggested Approaches:</strong> {', '.join(psych["solution"])}</li>
219
+ </ul>
220
+ <h3>🔍 Interpretation:</h3>
221
+ <blockquote>{reflect}</blockquote>
222
+ </div>
223
+ """
224
 
225
+ related = "### 🎓 Related Philosophers\n" + "\n".join([f"- {name}" for name in school_data["philosophers"]])
 
 
 
226
 
227
+ return report, semantic_plot, timeline, concept_map, related, best_match, round(highest_score*100, 2), psych_output
 
228
 
229
+ except Exception as e:
230
+ print("Error:", e)
231
+ return "**⚠️ Unexpected error occurred. Try again.**", None, generate_timeline(), generate_concept_graph(), "", "", "", ""
232
 
233
+ # UI
234
+ def build_ui():
235
+ with gr.Blocks() as demo:
236
+ gr.Markdown("# 🌌 Philosophy Insight Engine")
237
+ with gr.Row():
238
+ with gr.Column(scale=2):
239
+ text_input = gr.Textbox(
240
+ label="📜 Enter Philosophical Text",
241
+ lines=4,
242
+ placeholder="e.g. 'Man is condemned to be free'"
243
+ )
244
+ analyze_btn = gr.Button("🔍 Analyze Text")
245
+ clear_btn = gr.Button("🧹 Clear")
246
+ gr.Examples(
247
+ examples=[
248
+ ["Man is condemned to be free."],
249
+ ["The obstacle is the way."],
250
+ ["We suffer more in imagination than in reality."]
251
+ ],
252
+ inputs=text_input
253
+ )
254
+ with gr.Column(scale=1):
255
+ semantic_plot = gr.Plot(label="🗺️ Semantic Space")
256
 
257
+ with gr.Tabs():
258
+ with gr.TabItem("📝 Report"):
259
+ analysis_output = gr.HTML()
260
+ with gr.TabItem("🕰️ Timeline"):
261
+ timeline_output = gr.Plot()
262
+ with gr.TabItem("🧭 Concept Map"):
263
+ concept_map_output = gr.Plot()
264
+ with gr.TabItem("🎓 Philosophers"):
265
+ related_philosophers = gr.Markdown()
266
 
267
+ # پایین سمت چپ (با اضافه کردن سه خروجی جدید برای روانشناسی و ...) یک ردیف جدید:
268
+ with gr.Row():
269
+ with gr.Column():
270
+ school_output = gr.Markdown(label="🧠 Philosophical School Detected:")
271
+ similarity_output = gr.Markdown(label="Similarity Score:")
272
+ psychological_output = gr.Markdown(label="Psychological Profile:")
273
 
274
+ analyze_btn.click(
275
+ analyze_text,
276
+ inputs=text_input,
277
+ outputs=[
278
+ analysis_output, semantic_plot, timeline_output, concept_map_output, related_philosophers,
279
+ school_output, similarity_output, psychological_output
280
+ ]
281
+ )
282
+ clear_btn.click(
283
+ lambda: ["", None, None, None, "", "", "", ""],
284
+ outputs=[
285
+ text_input, semantic_plot, timeline_output, concept_map_output, related_philosophers,
286
+ school_output, similarity_output, psychological_output
287
+ ]
288
+ )
289
+ return demo
290
 
291
+ # Run
292
+ if __name__ == "__main__":
293
+ demo = build_ui()
294
+ demo.launch(share=True)