Update app.py
Browse files
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 |
-
#
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
"
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
#
|
| 26 |
-
|
| 27 |
-
"
|
| 28 |
-
|
| 29 |
-
"
|
| 30 |
-
|
| 31 |
-
"
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
"
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
}
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
def analyze_text(text):
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
f"{
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
with gr.
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|