Shirjannn commited on
Commit
885b6a0
·
verified ·
1 Parent(s): 64de7d9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -208
app.py CHANGED
@@ -5,220 +5,141 @@ matplotlib.use('Agg')
5
  import matplotlib.pyplot as plt
6
  from sklearn.metrics.pairwise import cosine_similarity
7
  from sentence_transformers import SentenceTransformer
8
- import tempfile
9
- from datetime import datetime
10
  import plotly.graph_objects as go
11
  from plotly.subplots import make_subplots
12
 
13
- # Load model
14
  model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
15
 
16
- # Dummy: Semantic Plot
17
- def create_semantic_plot(user_vec, best_match):
18
- fig, ax = plt.subplots()
19
- ax.set_title(f"Semantic Positioning: {best_match}")
20
- ax.scatter(user_vec[0][0], user_vec[0][1], color='blue')
21
- ax.text(user_vec[0][0], user_vec[0][1], f"{best_match}", fontsize=12)
22
- ax.set_xlim(-1, 1)
23
- ax.set_ylim(-1, 1)
24
- ax.grid(True)
25
- return fig
26
-
27
- # Dummy: Conceptual Graph
28
- def generate_concept_graph():
29
- fig, ax = plt.subplots()
30
- ax.set_title("Conceptual Map (Placeholder)")
31
- ax.text(0.5, 0.5, "Key concepts will be mapped here.", ha='center', va='center', fontsize=12)
32
- ax.axis('off')
33
- return fig
 
 
 
 
 
34
 
35
- # Smarter Reflection Response
36
- def philosophical_response(text, school=None):
37
- if school == "Existentialism":
38
- return f"Your sentence reflects existential freedom, perhaps inviting thought on authenticity and the burden of choice."
39
- elif school == "Stoicism":
40
- return f"This seems to align with Stoic resilience and inner control, possibly invoking the dichotomy of control."
41
- return f"This sentence echoes a philosophical sentiment. Possibly about meaning, freedom, or virtue: \"{text}\""
42
-
43
- # Knowledge Base (same as before)
44
- KNOWLEDGE_BASE = {
45
- "Existentialism": {
46
- "icon": "🌌",
47
- "color": "#4E79A7",
48
- "philosophers": ["Jean-Paul Sartre", "Albert Camus", "Friedrich Nietzsche"],
49
- "texts": [
50
- "Existence precedes essence",
51
- "Man is condemned to be free",
52
- "What does not kill me makes me stronger"
53
- ],
54
- "timeline": [1943, 1942, 1889],
55
- "psychology": {
56
- "positive": ["Deep self-awareness", "Radical responsibility", "Authenticity"],
57
- "negative": ["Existential anxiety", "Meaning crisis", "Freedom overwhelm"],
58
- "solution": ["Logotherapy", "Existential group therapy", "Creative expression"]
59
- },
60
- "key_concepts": ["Freedom", "Authenticity", "Absurd", "Angst"]
61
- },
62
- "Stoicism": {
63
- "icon": "🪨",
64
- "color": "#59A14F",
65
- "philosophers": ["Marcus Aurelius", "Epictetus", "Seneca"],
66
- "texts": [
67
- "The obstacle is the way",
68
- "You have power over your mind—not outside events",
69
- "We suffer more in imagination than in reality"
70
- ],
71
- "timeline": [180, 135, 65],
72
- "psychology": {
73
- "positive": ["Inner peace", "Resilience", "Emotional control"],
74
- "negative": ["Emotional suppression", "Detachment", "Fatalism"],
75
- "solution": ["Cognitive therapy", "Mindfulness meditation", "Negative visualization"]
76
- },
77
- "key_concepts": ["Virtue", "Dichotomy of Control", "Amor Fati", "Memento Mori"]
78
- }
79
  }
80
 
81
- # Precompute vectors
82
- for school in KNOWLEDGE_BASE:
83
- try:
84
- texts = KNOWLEDGE_BASE[school]["texts"]
85
- KNOWLEDGE_BASE[school]["vectors"] = np.array(model.encode(texts))
86
- except:
87
- KNOWLEDGE_BASE[school]["vectors"] = np.random.rand(len(texts), 384)
88
-
89
- # Timeline generator (no change)
90
- def generate_timeline():
91
- try:
92
- fig = make_subplots(rows=1, cols=1)
93
- entries = []
94
- for school, data in KNOWLEDGE_BASE.items():
95
- for name, year in zip(data["philosophers"], data["timeline"]):
96
- entries.append({
97
- "year": year,
98
- "name": name,
99
- "school": school,
100
- "color": data["color"],
101
- "icon": data["icon"]
102
- })
103
- entries.sort(key=lambda x: x["year"])
104
- for entry in entries:
105
- fig.add_trace(go.Scatter(
106
- x=[entry["year"]],
107
- y=[0],
108
- mode="markers+text",
109
- marker=dict(size=20, color=entry["color"]),
110
- name=f"{entry['icon']} {entry['name']}",
111
- text=f"{entry['icon']} {entry['name']}",
112
- hoverinfo="text",
113
- hovertext=f"<b>{entry['name']}</b><br>{entry['school']}<br>{entry['year']} CE",
114
- textposition="top center"
115
- ))
116
- fig.update_layout(
117
- title="🕰️ Philosophical Timeline",
118
- xaxis_title="Year",
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
- xaxis=dict(showgrid=True, gridcolor='lightgray'),
124
- yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)
125
- )
126
- return fig
127
- except:
128
- return go.Figure()
129
-
130
- # Text analysis (enhanced logic)
131
  def analyze_text(text):
132
- try:
133
- if not text.strip():
134
- return "**🚨 Please enter a valid philosophical text.**", None, generate_timeline(), generate_concept_graph(), ""
135
-
136
- user_vec = model.encode([text])
137
- best_match = None
138
- highest_score = -1
139
-
140
- for school, data in KNOWLEDGE_BASE.items():
141
- sims = cosine_similarity(user_vec, data["vectors"])
142
- score = np.max(sims)
143
- if score > highest_score:
144
- highest_score = score
145
- best_match = school
146
-
147
- school_data = KNOWLEDGE_BASE[best_match]
148
- psych = school_data["psychology"]
149
- semantic_plot = create_smarter_semantic_plot(user_vec, best_match, school_data)
150
- timeline = generate_timeline()
151
- concept_map = generate_concept_graph()
152
- reflect = philosophical_response(text, school=best_match)
153
-
154
- report = f"""
155
- <div>
156
- <h2>{school_data['icon']} Philosophical School: <span style="color:{school_data['color']};">{best_match}</span></h2>
157
- <p><strong>🧠 Confidence Score:</strong> {round(highest_score*100, 2)}%</p>
158
- <p><strong>🔑 Key Concepts:</strong> {', '.join(school_data.get('key_concepts', []))}</p>
159
- <h3>🧬 Psychological Effects</h3>
160
- <ul>
161
- <li><strong>Positive:</strong> {', '.join(psych["positive"])}</li>
162
- <li><strong>Negative:</strong> {', '.join(psych["negative"])}</li>
163
- <li><strong>Suggested Approaches:</strong> {', '.join(psych["solution"])}</li>
164
- </ul>
165
- <h3>🔍 Interpretation:</h3>
166
- <blockquote>{reflect}</blockquote>
167
- </div>
168
- """
169
-
170
- related = "### 🎓 Related Philosophers\n" + "\n".join([f"- {name}" for name in school_data["philosophers"]])
171
-
172
- return report, semantic_plot, timeline, concept_map, related
173
- except Exception as e:
174
- print("Error:", e)
175
- return "**⚠️ Unexpected error occurred. Try again.**", None, generate_timeline(), generate_concept_graph(), ""
176
-
177
- # UI (unchanged)
178
- def build_ui():
179
- with gr.Blocks() as demo:
180
- gr.Markdown("# 🌌 Philosophy Insight Engine")
181
- with gr.Row():
182
- with gr.Column(scale=2):
183
- text_input = gr.Textbox(
184
- label="📜 Enter Philosophical Text",
185
- lines=4,
186
- placeholder="e.g. 'Man is condemned to be free'"
187
- )
188
- analyze_btn = gr.Button("🔍 Analyze Text")
189
- clear_btn = gr.Button("🧹 Clear")
190
- gr.Examples(
191
- examples=[
192
- ["Man is condemned to be free."],
193
- ["The obstacle is the way."],
194
- ["We suffer more in imagination than in reality."]
195
- ],
196
- inputs=text_input
197
- )
198
- with gr.Column(scale=1):
199
- semantic_plot = gr.Plot(label="🗺️ Semantic Space")
200
- with gr.Tabs():
201
- with gr.TabItem("📝 Report"):
202
- analysis_output = gr.HTML()
203
- with gr.TabItem("🕰️ Timeline"):
204
- timeline_output = gr.Plot()
205
- with gr.TabItem("🧭 Concept Map"):
206
- concept_map_output = gr.Plot()
207
- with gr.TabItem("🎓 Philosophers"):
208
- related_philosophers = gr.Markdown()
209
-
210
- analyze_btn.click(
211
- analyze_text,
212
- inputs=text_input,
213
- outputs=[analysis_output, semantic_plot, timeline_output, concept_map_output, related_philosophers]
214
- )
215
- clear_btn.click(
216
- lambda: ["", None, None, None, ""],
217
- outputs=[text_input, semantic_plot, timeline_output, concept_map_output, related_philosophers]
218
- )
219
- return demo
220
-
221
- # Run
222
- if __name__ == "__main__":
223
- demo = build_ui()
224
- demo.launch(share=True)
 
 
 
 
 
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()