tahamueed23 commited on
Commit
efe8f87
Β·
verified Β·
1 Parent(s): 5e37ff6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -36
app.py CHANGED
@@ -5,63 +5,59 @@ import faiss
5
  from sentence_transformers import SentenceTransformer
6
  import joblib
7
 
8
- # ===============================
9
- # πŸ”Ή Load all assets
10
- # ===============================
11
  df = pd.read_csv("clean_feedback.csv")
12
- embeddings = np.load("embeddings.npy") # βœ… matches your file spelling
13
- index = faiss.read_index("feedback.index") # βœ… matches the visible file
14
- clf = joblib.load("feedback_model.pkl") # βœ… your classifier model
 
 
 
 
 
 
 
15
 
16
- # βœ… Use CPU to avoid Hugging Face GPU issues
17
  model = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2", device="cpu")
 
18
 
19
- # ===============================
20
- # πŸ”Ή Define feedback classifier
21
- # ===============================
22
  def classify_feedback(text, top_k=5):
 
 
23
  if not text.strip():
24
- return "**Please enter some feedback text.**"
25
 
26
- # Create embedding for user input
27
  query_emb = model.encode([text])
 
28
 
29
- # Retrieve top-k similar feedbacks from FAISS index
30
  distances, indices = index.search(query_emb, top_k)
 
31
 
32
- # Get similar sentences
33
  retrieved = df.iloc[indices[0]]
 
 
34
 
35
- # Combine context (optional, for RAG explainability)
36
- context = "\n".join(retrieved['Sentence'].astype(str).tolist())
37
-
38
- # Predict sentiment from classifier
39
- sentiment = clf.predict(query_emb)[0]
40
 
41
- # Prepare explanation list
42
- examples = "\n".join(
43
- [f"{i+1}. {s}" for i, s in enumerate(retrieved['Sentence'].astype(str).tolist())]
44
- )
45
 
46
  return f"**Predicted Sentiment:** {sentiment}\n\n**Similar Feedbacks:**\n{examples}"
47
 
48
- # ===============================
49
- # πŸ”Ή Gradio UI
50
- # ===============================
51
  demo = gr.Interface(
52
  fn=classify_feedback,
53
- inputs=[
54
- gr.Textbox(
55
- label="Enter Student Feedback",
56
- placeholder="Type a Roman Urdu or English feedback sentence here..."
57
- )
58
- ],
59
  outputs=[gr.Markdown(label="Prediction & Explanation")],
60
  title="πŸŽ“ Student Feedback RAG System",
61
- description="Analyzes student feedback (Roman Urdu or English) using Retrieval-Augmented Generation with contextual examples."
62
  )
63
 
64
- # ===============================
65
- # πŸ”Ή Launch app
66
- # ===============================
67
  demo.launch()
 
5
  from sentence_transformers import SentenceTransformer
6
  import joblib
7
 
8
+ # Load assets
9
+ print("πŸ”„ Loading data and models...")
 
10
  df = pd.read_csv("clean_feedback.csv")
11
+ print("βœ… CSV loaded with columns:", df.columns.tolist())
12
+
13
+ embeddings = np.load("embedings.npy")
14
+ print("βœ… Embeddings loaded with shape:", embeddings.shape)
15
+
16
+ index = faiss.read_index("feedback.index")
17
+ print("βœ… FAISS index loaded")
18
+
19
+ clf = joblib.load("feedback_model.pkl")
20
+ print("βœ… Sentiment model loaded")
21
 
 
22
  model = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2", device="cpu")
23
+ print("βœ… SentenceTransformer ready")
24
 
 
 
 
25
  def classify_feedback(text, top_k=5):
26
+ print(f"\n🧠 New query: {text}")
27
+
28
  if not text.strip():
29
+ return "⚠️ Please enter a feedback text."
30
 
31
+ # Embed query
32
  query_emb = model.encode([text])
33
+ print("Embedding shape:", query_emb.shape)
34
 
35
+ # Search similar samples
36
  distances, indices = index.search(query_emb, top_k)
37
+ print("Retrieved indices:", indices)
38
 
 
39
  retrieved = df.iloc[indices[0]]
40
+ if "Sentence" not in df.columns:
41
+ return "❌ Column 'Sentence' not found in CSV. Columns are: " + ", ".join(df.columns)
42
 
43
+ # Predict sentiment
44
+ try:
45
+ sentiment = clf.predict(query_emb)[0]
46
+ except Exception as e:
47
+ return f"❌ Model prediction error: {str(e)}"
48
 
49
+ examples = "\n".join([f"{i+1}. {s}" for i, s in enumerate(retrieved['Sentence'].tolist())])
50
+ print("βœ… Prediction done")
 
 
51
 
52
  return f"**Predicted Sentiment:** {sentiment}\n\n**Similar Feedbacks:**\n{examples}"
53
 
54
+ # Gradio UI
 
 
55
  demo = gr.Interface(
56
  fn=classify_feedback,
57
+ inputs=[gr.Textbox(label="Enter Student Feedback")],
 
 
 
 
 
58
  outputs=[gr.Markdown(label="Prediction & Explanation")],
59
  title="πŸŽ“ Student Feedback RAG System",
60
+ description="Classifies Roman Urdu/English student feedback with context and reasoning."
61
  )
62
 
 
 
 
63
  demo.launch()