Update app.py
Browse files
app.py
CHANGED
|
@@ -2,13 +2,14 @@ import gradio as gr
|
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
| 4 |
import faiss
|
| 5 |
-
import os
|
| 6 |
from sentence_transformers import SentenceTransformer
|
| 7 |
import joblib
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
#
|
| 10 |
# Load assets
|
| 11 |
-
#
|
| 12 |
print("🔄 Loading data and models...")
|
| 13 |
df = pd.read_csv("clean_feedback.csv")
|
| 14 |
print("✅ CSV loaded with columns:", df.columns.tolist())
|
|
@@ -25,82 +26,73 @@ print("✅ Sentiment model loaded")
|
|
| 25 |
model = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2", device="cpu")
|
| 26 |
print("✅ SentenceTransformer ready")
|
| 27 |
|
| 28 |
-
#
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
print("✅ Created user_feedback.csv")
|
| 37 |
-
|
| 38 |
-
# ------------------------
|
| 39 |
-
# Define classification + logging function
|
| 40 |
-
# ------------------------
|
| 41 |
def classify_feedback(text, top_k=5):
|
| 42 |
-
print(f"\n🧠 New query: {text}")
|
| 43 |
-
|
| 44 |
-
if not text.strip():
|
| 45 |
-
return "⚠️ Please enter a feedback text."
|
| 46 |
-
|
| 47 |
-
# Embed the input
|
| 48 |
-
query_emb = model.encode([text])
|
| 49 |
-
print("Embedding shape:", query_emb.shape)
|
| 50 |
-
|
| 51 |
-
# Retrieve top similar examples
|
| 52 |
-
distances, indices = index.search(query_emb, top_k)
|
| 53 |
-
retrieved = df.iloc[indices[0]]
|
| 54 |
-
|
| 55 |
-
# Predict sentiment and probability
|
| 56 |
try:
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
log_entry.to_csv(USER_LOG_FILE, mode="a", header=False, index=False)
|
| 81 |
-
print("📝 Saved to user_feedback.csv")
|
| 82 |
-
|
| 83 |
-
# Read updated log to show
|
| 84 |
-
user_log = pd.read_csv(USER_LOG_FILE)
|
| 85 |
-
|
| 86 |
-
output_text = f"**Predicted Sentiment:** {sentiment}\n\n**Similar Feedbacks:**\n{examples}"
|
| 87 |
-
return output_text, user_log
|
| 88 |
|
| 89 |
-
#
|
| 90 |
-
# Gradio
|
| 91 |
-
#
|
| 92 |
demo = gr.Interface(
|
| 93 |
fn=classify_feedback,
|
| 94 |
inputs=[gr.Textbox(label="Enter Student Feedback")],
|
| 95 |
outputs=[
|
| 96 |
gr.Markdown(label="Prediction & Explanation"),
|
| 97 |
-
gr.Dataframe(
|
| 98 |
],
|
| 99 |
title="🎓 Student Feedback RAG System",
|
| 100 |
description=(
|
| 101 |
-
"Classifies Roman Urdu/English student feedback with context and reasoning
|
| 102 |
"All submissions are saved and visible to everyone below 👇"
|
| 103 |
),
|
| 104 |
)
|
| 105 |
|
| 106 |
-
demo.launch(
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
| 4 |
import faiss
|
|
|
|
| 5 |
from sentence_transformers import SentenceTransformer
|
| 6 |
import joblib
|
| 7 |
+
import os
|
| 8 |
+
import traceback
|
| 9 |
|
| 10 |
+
# ===============================
|
| 11 |
# Load assets
|
| 12 |
+
# ===============================
|
| 13 |
print("🔄 Loading data and models...")
|
| 14 |
df = pd.read_csv("clean_feedback.csv")
|
| 15 |
print("✅ CSV loaded with columns:", df.columns.tolist())
|
|
|
|
| 26 |
model = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2", device="cpu")
|
| 27 |
print("✅ SentenceTransformer ready")
|
| 28 |
|
| 29 |
+
# File to store user submissions
|
| 30 |
+
USER_FEEDBACK_FILE = "user_feedback.csv"
|
| 31 |
+
if not os.path.exists(USER_FEEDBACK_FILE):
|
| 32 |
+
pd.DataFrame(columns=["Sentence", "Predicted_Sentiment", "Confidence"]).to_csv(USER_FEEDBACK_FILE, index=False)
|
| 33 |
|
| 34 |
+
# ===============================
|
| 35 |
+
# Core classification function
|
| 36 |
+
# ===============================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
def classify_feedback(text, top_k=5):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
try:
|
| 39 |
+
if not text.strip():
|
| 40 |
+
return "⚠️ Please enter a feedback text.", pd.read_csv(USER_FEEDBACK_FILE)
|
| 41 |
+
|
| 42 |
+
# Embed query
|
| 43 |
+
query_emb = model.encode([text])
|
| 44 |
+
|
| 45 |
+
# Retrieve similar sentences
|
| 46 |
+
distances, indices = index.search(query_emb, top_k)
|
| 47 |
+
retrieved = df.iloc[indices[0]]
|
| 48 |
+
|
| 49 |
+
# Predict sentiment & probability
|
| 50 |
+
probs_all = clf.predict_proba(query_emb)[0]
|
| 51 |
+
sentiment = clf.classes_[np.argmax(probs_all)]
|
| 52 |
+
confidence = np.max(probs_all)
|
| 53 |
+
|
| 54 |
+
examples = "\n".join(
|
| 55 |
+
[f"{i+1}. {s}" for i, s in enumerate(retrieved['Sentence'].tolist())]
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
# Save user submission to shared file
|
| 59 |
+
new_row = pd.DataFrame(
|
| 60 |
+
[{"Sentence": text, "Predicted_Sentiment": sentiment, "Confidence": round(confidence, 2)}]
|
| 61 |
+
)
|
| 62 |
+
existing = pd.read_csv(USER_FEEDBACK_FILE)
|
| 63 |
+
updated = pd.concat([existing, new_row], ignore_index=True)
|
| 64 |
+
updated.to_csv(USER_FEEDBACK_FILE, index=False)
|
| 65 |
+
|
| 66 |
+
print(f"✅ Prediction: {sentiment} ({confidence:.2f})")
|
| 67 |
+
|
| 68 |
+
# Return both text output + table
|
| 69 |
+
explanation = (
|
| 70 |
+
f"**Predicted Sentiment:** {sentiment}\n"
|
| 71 |
+
f"**Confidence:** {confidence:.2f}\n\n"
|
| 72 |
+
f"**Similar Feedbacks:**\n{examples}"
|
| 73 |
+
)
|
| 74 |
+
return explanation, updated
|
| 75 |
|
| 76 |
+
except Exception as e:
|
| 77 |
+
tb = traceback.format_exc()
|
| 78 |
+
print("❌ Error:", tb)
|
| 79 |
+
return f"❌ Error occurred:\n```\n{tb}\n```", pd.read_csv(USER_FEEDBACK_FILE)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
+
# ===============================
|
| 82 |
+
# Gradio Interface
|
| 83 |
+
# ===============================
|
| 84 |
demo = gr.Interface(
|
| 85 |
fn=classify_feedback,
|
| 86 |
inputs=[gr.Textbox(label="Enter Student Feedback")],
|
| 87 |
outputs=[
|
| 88 |
gr.Markdown(label="Prediction & Explanation"),
|
| 89 |
+
gr.Dataframe(headers=["Sentence", "Predicted_Sentiment", "Confidence"], label="🗂️ All User Feedback")
|
| 90 |
],
|
| 91 |
title="🎓 Student Feedback RAG System",
|
| 92 |
description=(
|
| 93 |
+
"Classifies Roman Urdu/English student feedback with context and reasoning.<br>"
|
| 94 |
"All submissions are saved and visible to everyone below 👇"
|
| 95 |
),
|
| 96 |
)
|
| 97 |
|
| 98 |
+
demo.launch()
|