tahamueed23 commited on
Commit
b60b60e
·
verified ·
1 Parent(s): 8d690f5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -65
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
- # Setup shared CSV for user submissions
30
- # ------------------------
31
- USER_LOG_FILE = "user_feedback.csv"
32
 
33
- # Create file if missing
34
- if not os.path.exists(USER_LOG_FILE):
35
- pd.DataFrame(columns=["Sentence", "Predicted_Sentiment"]).to_csv(USER_LOG_FILE, index=False)
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
- sentiment = clf.predict(query_emb)[0]
58
- if hasattr(clf, "predict_proba"):
59
- confidence = clf.predict_proba(query_emb).max() * 100
60
- confidence = round(confidence, 2)
61
- else:
62
- confidence = "N/A"
63
- except Exception as e:
64
- return f"❌ Model prediction error: {str(e)}"
65
-
66
- examples = "\n".join([f"{i+1}. {s}" for i, s in enumerate(retrieved['Sentence'].tolist())])
67
- print("✅ Prediction done")
68
-
69
- return (
70
- f"**Predicted Sentiment:** {sentiment}\n"
71
- f"**Confidence:** {confidence}%\n\n"
72
- f"**Similar Feedbacks:**\n{examples}"
73
- )
74
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
- # ------------------------
77
- # Save user input to log
78
- # ------------------------
79
- log_entry = pd.DataFrame([[text, sentiment]], columns=["Sentence", "Predicted_Sentiment"])
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 UI
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(label="🧾 All User Feedback", headers=["Sentence", "Predicted_Sentiment"])
98
  ],
99
  title="🎓 Student Feedback RAG System",
100
  description=(
101
- "Classifies Roman Urdu/English student feedback with context and reasoning.\n\n"
102
  "All submissions are saved and visible to everyone below 👇"
103
  ),
104
  )
105
 
106
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
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()