humy65 commited on
Commit
6812eef
·
1 Parent(s): 73ec345

Update demo with enhanced Hebrew intent model

Browse files
Files changed (2) hide show
  1. app.py +217 -40
  2. requirements.txt +4 -3
app.py CHANGED
@@ -1,49 +1,226 @@
 
 
 
 
 
1
  import gradio as gr
2
- from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoConfig
3
  import torch
4
 
5
- # Load model and tokenizer from Hugging Face Hub
6
- model_name = "humy65/hebrew-intent-classifier"
7
- tokenizer = AutoTokenizer.from_pretrained(model_name)
8
- model = AutoModelForSequenceClassification.from_pretrained(model_name)
9
-
10
- # Load config and extract label mapping
11
- config = AutoConfig.from_pretrained(model_name)
12
-
13
- # Try to get label names from config.id2label (if available)
14
- if hasattr(config, "id2label") and config.id2label:
15
- intent_labels = [config.id2label[i] for i in range(config.num_labels)]
16
- else:
17
- # Fallback: generate generic labels
18
- intent_labels = [f"כוונה {i}" for i in range(config.num_labels)]
19
-
20
- def classify_intent(text):
21
- inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
22
- with torch.no_grad():
23
- outputs = model(**inputs)
24
- probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
25
- top_prob, top_label = torch.max(probs, dim=1)
 
26
  try:
27
- intent = intent_labels[top_label.item()]
28
- except IndexError:
29
- intent = "כוונה לא מזוהה"
30
- confidence = top_prob.item()
31
- return f"כוונה: {intent}\nרמת ביטחון: {confidence:.2f}"
32
-
33
- # Build Gradio interface
34
- with gr.Blocks(theme="soft") as demo:
35
- gr.Markdown("## 🔍 מסווג כוונות של סקולי")
36
- gr.Markdown("מודל לזיהוי כוונות בשפה העברית. הקלד שאלה וראה את הכוונה המשוערת.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
- # Display supported intents
39
- gr.Markdown("### כוונות נתמכות:\n" + "\n".join(f"- {label}" for label in intent_labels))
 
 
 
40
 
41
  with gr.Row():
42
- input_text = gr.Textbox(label="הקלד שאלה בעברית", placeholder="לדוגמה: שכחתי את הסיסמה שלי")
43
-
44
- output_text = gr.Textbox(label="תוצאה")
45
- submit_btn = gr.Button("סווג")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
- submit_btn.click(fn=classify_intent, inputs=input_text, outputs=output_text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
- demo.launch()
 
 
 
 
 
 
 
1
+ """
2
+ Gradio Demo for Hebrew Intent Classification
3
+ Deploy this as a Hugging Face Space
4
+ """
5
+
6
  import gradio as gr
7
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
8
  import torch
9
 
10
+
11
+ class HebrewIntentClassifier:
12
+ def __init__(self):
13
+ # Use your deployed model
14
+ model_name = "Huggingm1r@n/hebrew-intent-classifier"
15
+
16
+ try:
17
+ print("Loading Hebrew Intent Classification model...")
18
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
19
+ self.model = AutoModelForSequenceClassification.from_pretrained(
20
+ model_name)
21
+ self.model.eval()
22
+ print("Model loaded successfully!")
23
+ except Exception as e:
24
+ print(f"Error loading model: {e}")
25
+ raise e
26
+
27
+ def predict(self, text):
28
+ """Predict intent for Hebrew text"""
29
+ if not text.strip():
30
+ return "Please enter some Hebrew text", {}, "אנא הכנס טקסט בעברית"
31
+
32
  try:
33
+ # Tokenize input
34
+ inputs = self.tokenizer(
35
+ text,
36
+ return_tensors="pt",
37
+ padding=True,
38
+ truncation=True,
39
+ max_length=128
40
+ )
41
+
42
+ # Get prediction
43
+ with torch.no_grad():
44
+ outputs = self.model(**inputs)
45
+ logits = outputs.logits
46
+ probabilities = torch.softmax(logits, dim=-1)
47
+
48
+ # Get all predictions
49
+ all_scores = {}
50
+ for i, prob in enumerate(probabilities[0]):
51
+ intent_name = self.model.config.id2label[i]
52
+ all_scores[intent_name] = float(prob)
53
+
54
+ # Get top prediction
55
+ predicted_id = torch.argmax(logits, dim=-1).item()
56
+ predicted_label = self.model.config.id2label[predicted_id]
57
+ confidence = probabilities[0][predicted_id].item()
58
+
59
+ # Format results in Hebrew and English
60
+ intent_translations = {
61
+ "ביטול מנוי": "Cancel Subscription",
62
+ "שאלה כללית": "General Question",
63
+ "שכחת סיסמה": "Password Reset",
64
+ "תמיכה טכנית": "Technical Support"
65
+ }
66
+
67
+ result_text = f"""
68
+ 🎯 **כוונה חזויה / Predicted Intent:** {predicted_label}
69
+ 🎲 **רמת ביטחון / Confidence:** {confidence:.1%}
70
+ 🔤 **תרגום / Translation:** {intent_translations.get(predicted_label, "Unknown")}
71
+
72
+ 📊 **כל התחזיות / All Predictions:**
73
+ """
74
+
75
+ # Sort by confidence and show all
76
+ sorted_scores = sorted(
77
+ all_scores.items(), key=lambda x: x[1], reverse=True)
78
+ for intent, score in sorted_scores:
79
+ bar = "█" * int(score * 20)
80
+ translation = intent_translations.get(intent, "Unknown")
81
+ result_text += f"\\n{intent} ({translation}): {score:.1%} {bar}"
82
+
83
+ return result_text, all_scores, predicted_label
84
+
85
+ except Exception as e:
86
+ return f"Error: {str(e)}", {}, "שגיאה"
87
+
88
+
89
+ # Initialize the classifier
90
+ try:
91
+ classifier = HebrewIntentClassifier()
92
+ except Exception as e:
93
+ print(f"Failed to initialize classifier: {e}")
94
+ classifier = None
95
+
96
+
97
+ def classify_text(text):
98
+ """Main classification function"""
99
+ if classifier is None:
100
+ return "Model not loaded properly", {}, "Model Error"
101
+
102
+ return classifier.predict(text)
103
+
104
+
105
+ def load_example(example_text):
106
+ """Load example text into the input"""
107
+ return example_text
108
+
109
+
110
+ # Create the Gradio interface
111
+ with gr.Blocks(
112
+ title="🇮🇱 Hebrew Intent Classification",
113
+ theme=gr.themes.Soft(),
114
+ css=".rtl { direction: rtl; text-align: right; }"
115
+ ) as demo:
116
+
117
+ gr.Markdown("""
118
+ # 🇮🇱 מסווג כוונות עברית / Hebrew Intent Classification
119
+
120
+ ## מה זה עושה? / What does this do?
121
+
122
+ מסווג טקסט עברית לפי כוונת הלקוח לאחת מ-4 קטגוריות:
123
+
124
+ **Classifies Hebrew customer service text into 4 categories:**
125
 
126
+ - 🔐 **שכחת סיסמה** (Password Reset) - בעיות התחברות וסיסמאות
127
+ - **ביטול מנוי** (Cancel Subscription) - בקשות לביטול שירות
128
+ - ❓ **שאלה כללית** (General Question) - שאלות על מחירים, שירותים, חשבון
129
+ - 🔧 **תמיכה טכנית** (Technical Support) - בעיות טכניות, תקלות, באגים
130
+ """)
131
 
132
  with gr.Row():
133
+ with gr.Column(scale=1):
134
+ gr.Markdown("### 📝 הכנס טקסט עברית / Enter Hebrew Text")
135
+
136
+ text_input = gr.Textbox(
137
+ label="טקסט / Text:",
138
+ placeholder="לדוגמה: שכחתי את הסיסמה שלי",
139
+ lines=4,
140
+ elem_classes=["rtl"],
141
+ info="הכנס טקסט בעברית הקשור לשירות לקוחות"
142
+ )
143
+
144
+ classify_btn = gr.Button(
145
+ "🔍 סווג כוונה / Classify Intent",
146
+ variant="primary",
147
+ size="lg"
148
+ )
149
+
150
+ gr.Markdown("### 📋 דוגמאות לניסוי / Try These Examples:")
151
+
152
+ examples = [
153
+ ("שכחתי את הסיסמה שלי", "🔐 שכחת סיסמה"),
154
+ ("רוצה לבטל את המנוי", "❌ ביטול מנוי"),
155
+ ("כמה עולה החבילה השנתית", "❓ שאלה כללית"),
156
+ ("האתר לא עובד לי", "🔧 תמיכה טכנית"),
157
+ ("איך אני משנה את האימייל", "❓ שאלה כללית"),
158
+ ("יש לי בעיה טכנית באפליקציה", "🔧 תמיכה טכנית"),
159
+ ("איך מבטלים את החשבון", "❌ ביטול מנוי"),
160
+ ("לא מצליח להיכנס למערכת", "🔐 שכחת סיסמה")
161
+ ]
162
 
163
+ for text, category in examples:
164
+ gr.Button(
165
+ f"{category}: {text}",
166
+ size="sm"
167
+ ).click(
168
+ lambda x=text: x,
169
+ outputs=text_input
170
+ )
171
+
172
+ with gr.Column(scale=1):
173
+ gr.Markdown("### 📊 תוצאות / Results")
174
+
175
+ result_output = gr.Markdown(
176
+ value="התוצאות יופיעו כאן / Results will appear here",
177
+ elem_classes=["rtl"]
178
+ )
179
+
180
+ confidence_plot = gr.Label(
181
+ label="ציוני ביטחון / Confidence Scores",
182
+ num_top_classes=4
183
+ )
184
+
185
+ predicted_intent = gr.Textbox(
186
+ label="כוונה חזויה / Predicted Intent",
187
+ interactive=False
188
+ )
189
+
190
+ # Connect the classification function
191
+ classify_btn.click(
192
+ classify_text,
193
+ inputs=[text_input],
194
+ outputs=[result_output, confidence_plot, predicted_intent]
195
+ )
196
+
197
+ # Allow Enter key to trigger classification
198
+ text_input.submit(
199
+ classify_text,
200
+ inputs=[text_input],
201
+ outputs=[result_output, confidence_plot, predicted_intent]
202
+ )
203
+
204
+ gr.Markdown("""
205
+ ---
206
+ ### 📈 מידע על המודל / Model Information
207
+
208
+ - **בסיס / Base Model:** BERT Multilingual
209
+ - **נתוני אימון / Training Data:** 135 דוגמאות עברית מתחום שירות לקוחות
210
+ - **ביצועים / Performance:** דיוק גבוה >90% על טקסט עברית
211
+ - **קוד מקור / Source:** [GitHub Repository](https://github.com/your-repo)
212
+
213
+ ### 🔗 קישורים / Links
214
+ - [Model on Hugging Face](https://huggingface.co/Huggingm1r@n/hebrew-intent-classifier)
215
+ - [Documentation](https://huggingface.co/Huggingm1r@n/hebrew-intent-classifier/blob/main/README.md)
216
+
217
+ Built with ❤️ using Hugging Face Transformers and Gradio
218
+ """)
219
 
220
+ # Launch the demo
221
+ if __name__ == "__main__":
222
+ demo.launch(
223
+ share=True,
224
+ server_name="0.0.0.0",
225
+ server_port=7860
226
+ )
requirements.txt CHANGED
@@ -1,3 +1,4 @@
1
- transformers
2
- torch
3
- gradio
 
 
1
+ gradio>=4.0.0
2
+ transformers>=4.20.0
3
+ torch>=1.9.0
4
+ numpy