Shirjannn commited on
Commit
09cef87
Β·
verified Β·
1 Parent(s): d9888c6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +205 -85
app.py CHANGED
@@ -13,92 +13,212 @@ from plotly.subplots import make_subplots
13
  # Load model
14
  model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
15
 
16
- # Sample philosophical schools and concepts
17
- schools = {
18
- "Existentialism": ["absurdity", "freedom", "authenticity", "existence", "meaning", "alienation"],
19
- "Stoicism": ["virtue", "nature", "reason", "emotion", "control", "detachment"],
20
- "Nihilism": ["meaninglessness", "nothingness", "rejection", "morality", "truth"],
21
- "Idealism": ["ideas", "mind", "perception", "reality", "consciousness"],
22
- "Rationalism": ["reason", "logic", "truth", "knowledge", "a priori"],
23
- }
 
 
 
 
 
 
 
 
 
 
24
 
25
- # Sample philosophical timeline
26
- philosophers = {
27
- "Socrates": -470,
28
- "Plato": -428,
29
- "Aristotle": -384,
30
- "Descartes": 1596,
31
- "Spinoza": 1632,
32
- "Kant": 1724,
33
- "Nietzsche": 1844,
34
- "Heidegger": 1889,
35
- "Sartre": 1905,
36
- "Camus": 1913,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  }
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  def analyze_text(text):
40
- embedding = model.encode([text])[0]
41
-
42
- # Match to philosophical school
43
- school_scores = {}
44
- for school, concepts in schools.items():
45
- concept_embeddings = model.encode(concepts)
46
- similarities = cosine_similarity([embedding], concept_embeddings)[0]
47
- score = float(np.mean(similarities))
48
- school_scores[school] = score
49
-
50
- best_school = max(school_scores, key=school_scores.get)
51
- best_score = school_scores[best_school]
52
-
53
- # Create concept map (bar chart)
54
- fig1 = go.Figure()
55
- fig1.add_trace(go.Bar(x=list(school_scores.keys()), y=list(school_scores.values())))
56
- fig1.update_layout(title="Similarity to Philosophical Schools", height=300)
57
-
58
- # Timeline (scatter plot)
59
- years = list(philosophers.values())
60
- names = list(philosophers.keys())
61
- fig2 = go.Figure()
62
- fig2.add_trace(go.Scatter(x=years, y=[1]*len(years), mode='markers+text', text=names, textposition="top center"))
63
- fig2.update_layout(title="Philosopher Timeline", height=300, xaxis_title="Year", yaxis=dict(visible=False))
64
-
65
- # Psychological profile (simple heuristic)
66
- profile = ""
67
- if "freedom" in text or "choice" in text:
68
- profile += "High autonomy. "
69
- if "suffering" in text or "absurd" in text:
70
- profile += "Potential existential anxiety. "
71
- if "virtue" in text or "reason" in text:
72
- profile += "Rational and ethical mindset. "
73
-
74
- return (
75
- fig1,
76
- fig2,
77
- best_school,
78
- f"{best_score:.2f}",
79
- profile.strip() if profile else "Neutral / Undefined"
80
- )
81
-
82
- # Interface
83
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
84
- gr.Markdown("## 🧠 Philosophical Insight Tool")
85
-
86
- with gr.Row():
87
- with gr.Column():
88
- input_text = gr.Textbox(lines=6, label="πŸ“ Enter Philosophical Text")
89
- with gr.Column():
90
- concept_map = gr.Plot(label="πŸ“Š Concept Map")
91
-
92
- with gr.Row():
93
- with gr.Column():
94
- timeline = gr.Plot(label="πŸ•°οΈ Philosophy Timeline")
95
- with gr.Column():
96
- school_output = gr.Textbox(label="🏫 Philosophical School Detected:")
97
- similarity_output = gr.Textbox(label="πŸ“ˆ Similarity Score:")
98
- profile_output = gr.Textbox(label="🧬 Psychological Profile:")
99
-
100
- input_text.change(fn=analyze_text, inputs=[input_text], outputs=[
101
- concept_map, timeline, school_output, similarity_output, profile_output
102
- ])
103
-
104
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_semantic_plot(user_vec, best_match)
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)