tahamueed23 commited on
Commit
1d5af67
·
verified ·
1 Parent(s): a8c40e9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -0
app.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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())
15
+
16
+ embeddings = np.load("embeddings.npy")
17
+ print("✅ Embeddings loaded with shape:", embeddings.shape)
18
+
19
+ index = faiss.read_index("feedback.index")
20
+ print("✅ FAISS index loaded")
21
+
22
+ clf = joblib.load("feedback_model.pkl")
23
+ print("✅ Sentiment model loaded")
24
+
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.", pd.read_csv(USER_LOG_FILE)
46
+
47
+ # Embed query
48
+ query_emb = model.encode([text])
49
+ print("Embedding shape:", query_emb.shape)
50
+
51
+ # Search similar samples
52
+ distances, indices = index.search(query_emb, top_k)
53
+ print("Retrieved indices:", indices)
54
+
55
+ retrieved = df.iloc[indices[0]]
56
+
57
+ # Predict sentiment
58
+ try:
59
+ sentiment = clf.predict(query_emb)[0]
60
+ except Exception as e:
61
+ return f"❌ Model prediction error: {str(e)}", pd.read_csv(USER_LOG_FILE)
62
+
63
+ examples = "\n".join(
64
+ [f"{i+1}. {s}" for i, s in enumerate(retrieved['Sentence'].tolist())]
65
+ )
66
+ print("✅ Prediction done")
67
+
68
+ # ------------------------
69
+ # Save user input to log
70
+ # ------------------------
71
+ log_entry = pd.DataFrame([[text, sentiment]], columns=["Sentence", "Predicted_Sentiment"])
72
+ log_entry.to_csv(USER_LOG_FILE, mode="a", header=False, index=False)
73
+ print("📝 Saved to user_feedback.csv")
74
+
75
+ # Read updated log to show
76
+ user_log = pd.read_csv(USER_LOG_FILE)
77
+
78
+ output_text = f"**Predicted Sentiment:** {sentiment}\n\n**Similar Feedbacks:**\n{examples}"
79
+ return output_text, user_log
80
+
81
+ # ------------------------
82
+ # Gradio UI
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(label="🧾 All User Feedback", headers=["Sentence", "Predicted_Sentiment"])
90
+ ],
91
+ title="🎓 Student Feedback RAG System",
92
+ description=(
93
+ "Classifies Roman Urdu/English student feedback with context and reasoning.\n\n"
94
+ "All submissions are saved and visible to everyone below 👇"
95
+ ),
96
+ )
97
+
98
+ demo.launch()