Aadhavan12344 commited on
Commit
dbe77fe
·
verified ·
1 Parent(s): 52ac49e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -0
app.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from sentence_transformers import SentenceTransformer, util
3
+ import torch
4
+ import json
5
+
6
+ model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
7
+
8
+ # In-memory label store (can be replaced by DB)
9
+ LABEL_STORE = {
10
+ "chat": ["say hello", "casual talk", "how are you"],
11
+ "image_generation": ["generate an image", "draw a picture", "create artwork"],
12
+ "action": ["set a timer", "create a reminder"]
13
+ }
14
+
15
+ def classify(text, label_json):
16
+ if not text.strip():
17
+ return {"error": "Empty input"}
18
+
19
+ try:
20
+ labels = json.loads(label_json)
21
+ except Exception as e:
22
+ return {"error": "Invalid label JSON"}
23
+
24
+ label_embeddings = {}
25
+ for label, examples in labels.items():
26
+ if not examples:
27
+ continue
28
+ emb = model.encode(examples, convert_to_tensor=True)
29
+ label_embeddings[label] = emb.mean(dim=0)
30
+
31
+ if not label_embeddings:
32
+ return {"error": "No valid labels"}
33
+
34
+ text_emb = model.encode(text, convert_to_tensor=True)
35
+
36
+ scores = {}
37
+ for label, emb in label_embeddings.items():
38
+ scores[label] = float(util.cos_sim(text_emb, emb))
39
+
40
+ top_intent = max(scores, key=scores.get)
41
+
42
+ return {
43
+ "text": text,
44
+ "top_intent": top_intent,
45
+ "scores": scores
46
+ }
47
+
48
+ with gr.Blocks() as demo:
49
+ gr.Markdown("## ⚡ Semantic Intent Router Builder")
50
+
51
+ user_input = gr.Textbox(label="User Input")
52
+
53
+ label_editor = gr.JSON(
54
+ value=LABEL_STORE,
55
+ label="Labels & Examples (edit freely, add/remove)"
56
+ )
57
+
58
+ output = gr.JSON(label="Routing Result")
59
+
60
+ classify_btn = gr.Button("Classify")
61
+
62
+ classify_btn.click(
63
+ classify,
64
+ inputs=[user_input, label_editor],
65
+ outputs=output
66
+ )
67
+
68
+ demo.launch(
69
+ share=True,
70
+ show_api=True,
71
+ enable_queue=False
72
+ )