Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,175 +1,3 @@
|
|
| 1 |
-
# import gradio as gr
|
| 2 |
-
# import torch
|
| 3 |
-
# from sentence_transformers import SentenceTransformer
|
| 4 |
-
# from sklearn.metrics.pairwise import cosine_similarity
|
| 5 |
-
# import pickle
|
| 6 |
-
# import os
|
| 7 |
-
# import numpy as np
|
| 8 |
-
|
| 9 |
-
# class UrduOptimizedPredictor:
|
| 10 |
-
# def __init__(self, model_path=None):
|
| 11 |
-
# self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 12 |
-
# print(f"Using device: {self.device}")
|
| 13 |
-
|
| 14 |
-
# # Load the multilingual model
|
| 15 |
-
# self.text_model = SentenceTransformer('sentence-transformers/paraphrase-multilingual-mpnet-base-v2')
|
| 16 |
-
# self.text_model.to(self.device)
|
| 17 |
-
|
| 18 |
-
# # Load YOUR model
|
| 19 |
-
# model_file = "models/urdu_optimized_model/urdu_optimized_model.pkl"
|
| 20 |
-
# print(f"📁 Loading YOUR model from: {model_file}")
|
| 21 |
-
|
| 22 |
-
# try:
|
| 23 |
-
# with open(model_file, 'rb') as f:
|
| 24 |
-
# model_data = pickle.load(f)
|
| 25 |
-
|
| 26 |
-
# self.emoji_embeddings = {k: v[0] for k, v in model_data['emoji_embeddings'].items()}
|
| 27 |
-
# self.emoji_list = model_data['emoji_list']
|
| 28 |
-
|
| 29 |
-
# print(f"✅ SUCCESS: Loaded YOUR Urdu-optimized model with {len(self.emoji_list)} emojis")
|
| 30 |
-
# print(f"📊 Your emojis: {self.emoji_list[:20]}...") # Show first 20 emojis
|
| 31 |
-
|
| 32 |
-
# except Exception as e:
|
| 33 |
-
# print(f"❌ ERROR loading your model: {e}")
|
| 34 |
-
# raise e
|
| 35 |
-
|
| 36 |
-
# def predict_smart(self, text, top_k=3, min_confidence=0.3):
|
| 37 |
-
# """Use YOUR model for prediction"""
|
| 38 |
-
# print(f"\n🔍 PREDICTING for: '{text}'")
|
| 39 |
-
|
| 40 |
-
# # Get text embedding
|
| 41 |
-
# text_embedding = self.text_model.encode([text], convert_to_tensor=True)
|
| 42 |
-
# text_embedding_np = text_embedding.cpu().numpy()
|
| 43 |
-
|
| 44 |
-
# # Calculate similarities with YOUR emoji embeddings
|
| 45 |
-
# similarities = {}
|
| 46 |
-
# for emoji, emoji_embedding in self.emoji_embeddings.items():
|
| 47 |
-
# similarity = cosine_similarity(text_embedding_np, emoji_embedding.reshape(1, -1))[0][0]
|
| 48 |
-
# similarities[emoji] = similarity
|
| 49 |
-
|
| 50 |
-
# print(f"📈 Similarities calculated for {len(similarities)} emojis")
|
| 51 |
-
|
| 52 |
-
# # Filter by confidence and return top K
|
| 53 |
-
# filtered = [(emoji, score) for emoji, score in similarities.items() if score >= min_confidence]
|
| 54 |
-
# sorted_emojis = sorted(filtered, key=lambda x: x[1], reverse=True)
|
| 55 |
-
|
| 56 |
-
# print(f"🎯 Top predictions: {sorted_emojis[:top_k]}")
|
| 57 |
-
|
| 58 |
-
# # If no confident predictions, return top overall
|
| 59 |
-
# if not sorted_emojis:
|
| 60 |
-
# top_overall = sorted(similarities.items(), key=lambda x: x[1], reverse=True)[:top_k]
|
| 61 |
-
# print(f"⚠️ No confident predictions, using top overall: {top_overall}")
|
| 62 |
-
# return top_overall
|
| 63 |
-
|
| 64 |
-
# return sorted_emojis[:top_k]
|
| 65 |
-
|
| 66 |
-
# # Initialize predictor
|
| 67 |
-
# print("🚀 Loading YOUR Urdu Emoji Prediction Model...")
|
| 68 |
-
# predictor = UrduOptimizedPredictor()
|
| 69 |
-
|
| 70 |
-
# def predict_emoji(urdu_text):
|
| 71 |
-
# """Main prediction function using YOUR model"""
|
| 72 |
-
# if not urdu_text.strip():
|
| 73 |
-
# return "⬅️ اردو متن لکھیں"
|
| 74 |
-
|
| 75 |
-
# try:
|
| 76 |
-
# # Get predictions from YOUR model
|
| 77 |
-
# predictions = predictor.predict_smart(urdu_text, top_k=3, min_confidence=0.3)
|
| 78 |
-
|
| 79 |
-
# # Format output
|
| 80 |
-
# if predictions:
|
| 81 |
-
# result = "🎯 **آپ کے ماڈل کی پیشنگو:**\n\n"
|
| 82 |
-
# for i, (emoji, score) in enumerate(predictions, 1):
|
| 83 |
-
# confidence_level = "اعلیٰ" if score > 0.6 else "درمیانی" if score > 0.4 else "کم"
|
| 84 |
-
# result += f"{i}. {emoji} - {confidence_level} درستگی ({score:.3f})\n"
|
| 85 |
-
# return result
|
| 86 |
-
# else:
|
| 87 |
-
# return "❌ آپ کے ماڈل سے کوئی مناسب ایموجی نہیں مل سکی"
|
| 88 |
-
|
| 89 |
-
# except Exception as e:
|
| 90 |
-
# print(f"Error in prediction: {e}")
|
| 91 |
-
# return f"⚠️ نظام میں خرابی: {e}"
|
| 92 |
-
|
| 93 |
-
# # Test your model with some examples before starting the interface
|
| 94 |
-
# print("\n" + "="*60)
|
| 95 |
-
# print("🧪 TESTING YOUR MODEL WITH SAMPLE TEXTS")
|
| 96 |
-
# print("="*60)
|
| 97 |
-
|
| 98 |
-
# test_texts = [
|
| 99 |
-
# "میں بہت خوش ہوں",
|
| 100 |
-
# "دل ٹوٹ گیا ہے",
|
| 101 |
-
# "دوستوں کے ساتھ پارٹی کا مزہ آیا",
|
| 102 |
-
# "امی نے میری پسندیدہ ڈش بنائی ہے",
|
| 103 |
-
# "غصہ سے دماغ پھٹ رہا ہے"
|
| 104 |
-
# ]
|
| 105 |
-
|
| 106 |
-
# for text in test_texts:
|
| 107 |
-
# print(f"\n📝 Testing: '{text}'")
|
| 108 |
-
# predictions = predictor.predict_smart(text, top_k=3, min_confidence=0.3)
|
| 109 |
-
# print(f" → {[emoji for emoji, score in predictions]}")
|
| 110 |
-
|
| 111 |
-
# print("\n" + "="*60)
|
| 112 |
-
# print("🚀 STARTING GRADIO INTERFACE")
|
| 113 |
-
# print("="*60)
|
| 114 |
-
|
| 115 |
-
# # Create Gradio interface
|
| 116 |
-
# demo = gr.Blocks(title="آپ کا اردو ایموجی پیشنگو ماڈل")
|
| 117 |
-
|
| 118 |
-
# with demo:
|
| 119 |
-
# gr.Markdown(
|
| 120 |
-
# """
|
| 121 |
-
# # 🎯 **آپ کا تربیت یافتہ اردو ایموجی ماڈل**
|
| 122 |
-
|
| 123 |
-
# یہ انٹرفیس **آپ کے ہی تربیت یافتہ ماڈل** کا استعمال کر رہا ہے!
|
| 124 |
-
# - **80+ Urdu emojis** آپ کے ڈیٹا سے تربیت یافتہ
|
| 125 |
-
# - **10 لاکھ+ Urdu tweets** پر مبنی
|
| 126 |
-
# - **Top-3 درستگی: 30.4%**
|
| 127 |
-
# """
|
| 128 |
-
# )
|
| 129 |
-
|
| 130 |
-
# with gr.Row():
|
| 131 |
-
# with gr.Column():
|
| 132 |
-
# input_text = gr.Textbox(
|
| 133 |
-
# label="اردو متن درج کریں",
|
| 134 |
-
# placeholder="اپنا Urdu متن یہاں لکھیں...",
|
| 135 |
-
# lines=3
|
| 136 |
-
# )
|
| 137 |
-
|
| 138 |
-
# predict_btn = gr.Button("🎯 ماڈل سے ایموجیز حاصل کریں", variant="primary")
|
| 139 |
-
|
| 140 |
-
# with gr.Column():
|
| 141 |
-
# output_text = gr.Textbox(
|
| 142 |
-
# label="آپ کے ماڈل کی پیشنگو",
|
| 143 |
-
# placeholder="یہاں آپ کے ماڈل کی پیشنگو ایموجیز ظاہر ہوں گی...",
|
| 144 |
-
# lines=5
|
| 145 |
-
# )
|
| 146 |
-
|
| 147 |
-
# gr.Markdown("### 💡 آپ کے ماڈل کی جانچ کے لیے مثالیں")
|
| 148 |
-
# examples = gr.Examples(
|
| 149 |
-
# examples=[
|
| 150 |
-
# ["میں آج بہت خوش ہوں اور مسکرا رہا ہوں"],
|
| 151 |
-
# ["دل ٹوٹ گیا ہے، بہت دکھ ہو رہا ہے"],
|
| 152 |
-
# ["دوستوں کے ساتھ پارٹی کا بہت مزہ آیا"],
|
| 153 |
-
# ["نیند آ رہی ہے، بہت تھک گیا ہوں"],
|
| 154 |
-
# ["امی نے میری پسندیدہ کھانا بنایا ہے"],
|
| 155 |
-
# ["محبت میں پڑ گیا ہوں، دل دھڑک رہا ہے"],
|
| 156 |
-
# ["غصہ سے دماغ پھٹ رہا ہے"],
|
| 157 |
-
# ["بارش ہو رہی ہے، موسم بہت اچھا ہے"]
|
| 158 |
-
# ],
|
| 159 |
-
# inputs=input_text,
|
| 160 |
-
# outputs=output_text,
|
| 161 |
-
# fn=predict_emoji,
|
| 162 |
-
# cache_examples=False
|
| 163 |
-
# )
|
| 164 |
-
|
| 165 |
-
# if __name__ == "__main__":
|
| 166 |
-
# demo.launch(
|
| 167 |
-
# server_name="0.0.0.0",
|
| 168 |
-
# server_port=7860,
|
| 169 |
-
# share=True
|
| 170 |
-
# )
|
| 171 |
-
|
| 172 |
-
|
| 173 |
import gradio as gr
|
| 174 |
import torch
|
| 175 |
from sentence_transformers import SentenceTransformer
|
|
@@ -188,7 +16,7 @@ class UrduOptimizedPredictor:
|
|
| 188 |
self.text_model.to(self.device)
|
| 189 |
|
| 190 |
# Load YOUR model
|
| 191 |
-
model_file = "urdu_optimized_model.pkl"
|
| 192 |
print(f"📁 Loading YOUR model from: {model_file}")
|
| 193 |
|
| 194 |
try:
|
|
@@ -248,19 +76,19 @@ def predict_emoji(urdu_text):
|
|
| 248 |
# Get predictions from YOUR model
|
| 249 |
predictions = predictor.predict_smart(urdu_text, top_k=3, min_confidence=0.3)
|
| 250 |
|
| 251 |
-
# Format output
|
| 252 |
if predictions:
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
return result
|
| 258 |
else:
|
| 259 |
-
return "❌
|
| 260 |
|
| 261 |
except Exception as e:
|
| 262 |
print(f"Error in prediction: {e}")
|
| 263 |
-
return
|
| 264 |
|
| 265 |
# Test your model with some examples before starting the interface
|
| 266 |
print("\n" + "="*60)
|
|
@@ -285,17 +113,17 @@ print("🚀 STARTING GRADIO INTERFACE")
|
|
| 285 |
print("="*60)
|
| 286 |
|
| 287 |
# Create Gradio interface
|
| 288 |
-
demo = gr.Blocks(title="
|
| 289 |
|
| 290 |
with demo:
|
| 291 |
gr.Markdown(
|
| 292 |
"""
|
| 293 |
-
# 🎯
|
| 294 |
|
| 295 |
-
|
| 296 |
-
- **80+
|
| 297 |
-
- **10 لاکھ+
|
| 298 |
-
- **
|
| 299 |
"""
|
| 300 |
)
|
| 301 |
|
|
@@ -303,30 +131,30 @@ with demo:
|
|
| 303 |
with gr.Column():
|
| 304 |
input_text = gr.Textbox(
|
| 305 |
label="اردو متن درج کریں",
|
| 306 |
-
placeholder="اپنا
|
| 307 |
lines=3
|
| 308 |
)
|
| 309 |
|
| 310 |
-
predict_btn = gr.Button("🎯
|
| 311 |
|
| 312 |
with gr.Column():
|
| 313 |
output_text = gr.Textbox(
|
| 314 |
-
label="
|
| 315 |
-
placeholder="یہاں
|
| 316 |
-
lines=
|
| 317 |
)
|
| 318 |
|
| 319 |
-
gr.Markdown("### 💡
|
| 320 |
examples = gr.Examples(
|
| 321 |
examples=[
|
| 322 |
-
["میں آج بہت خوش ہوں
|
| 323 |
-
["دل ٹوٹ گیا ہے
|
| 324 |
-
["دوستوں کے ساتھ پارٹی کا
|
| 325 |
-
["نیند آ رہی ہے
|
| 326 |
["امی نے میری پسندیدہ کھانا بنایا ہے"],
|
| 327 |
-
["محبت میں پڑ گیا ہوں
|
| 328 |
["غصہ سے دماغ پھٹ رہا ہے"],
|
| 329 |
-
["بارش ہو رہی ہے
|
| 330 |
],
|
| 331 |
inputs=input_text,
|
| 332 |
outputs=output_text,
|
|
@@ -334,7 +162,7 @@ with demo:
|
|
| 334 |
cache_examples=False
|
| 335 |
)
|
| 336 |
|
| 337 |
-
#
|
| 338 |
predict_btn.click(fn=predict_emoji, inputs=input_text, outputs=output_text)
|
| 339 |
|
| 340 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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.device)
|
| 17 |
|
| 18 |
# Load YOUR model
|
| 19 |
+
model_file = "models/urdu_optimized_model/urdu_optimized_model.pkl"
|
| 20 |
print(f"📁 Loading YOUR model from: {model_file}")
|
| 21 |
|
| 22 |
try:
|
|
|
|
| 76 |
# Get predictions from YOUR model
|
| 77 |
predictions = predictor.predict_smart(urdu_text, top_k=3, min_confidence=0.3)
|
| 78 |
|
| 79 |
+
# Format output - ONLY EMOJIS, no scores or text
|
| 80 |
if predictions:
|
| 81 |
+
# Extract just the emojis from predictions
|
| 82 |
+
emojis_only = [emoji for emoji, score in predictions]
|
| 83 |
+
# Join them with spaces for clean display
|
| 84 |
+
result = " ".join(emojis_only)
|
| 85 |
return result
|
| 86 |
else:
|
| 87 |
+
return "❌"
|
| 88 |
|
| 89 |
except Exception as e:
|
| 90 |
print(f"Error in prediction: {e}")
|
| 91 |
+
return "⚠️"
|
| 92 |
|
| 93 |
# Test your model with some examples before starting the interface
|
| 94 |
print("\n" + "="*60)
|
|
|
|
| 113 |
print("="*60)
|
| 114 |
|
| 115 |
# Create Gradio interface
|
| 116 |
+
demo = gr.Blocks(title="اردو ایموجی پیشنگو")
|
| 117 |
|
| 118 |
with demo:
|
| 119 |
gr.Markdown(
|
| 120 |
"""
|
| 121 |
+
# 🎯 اردو ایموجی پیشنگو
|
| 122 |
|
| 123 |
+
اپنے اردو متن کے لیے موزوں ترین ایموجیز دریافت کریں
|
| 124 |
+
- **80+ اردو ایموجیز**
|
| 125 |
+
- **10 لاکھ+ اردو ٹویٹس** پر تربیت یافتہ
|
| 126 |
+
- **تین بہترین ایموجیز** کی پیشنگو
|
| 127 |
"""
|
| 128 |
)
|
| 129 |
|
|
|
|
| 131 |
with gr.Column():
|
| 132 |
input_text = gr.Textbox(
|
| 133 |
label="اردو متن درج کریں",
|
| 134 |
+
placeholder="اپنا اردو متن یہاں لکھیں... مثلاً: آج میں بہت خوش ہوں",
|
| 135 |
lines=3
|
| 136 |
)
|
| 137 |
|
| 138 |
+
predict_btn = gr.Button("🎯 ایموجیز حاصل کریں", variant="primary")
|
| 139 |
|
| 140 |
with gr.Column():
|
| 141 |
output_text = gr.Textbox(
|
| 142 |
+
label="پیشنگو شدہ ایموجیز",
|
| 143 |
+
placeholder="یہاں ایموجیز ظاہر ہوں گی...",
|
| 144 |
+
lines=2
|
| 145 |
)
|
| 146 |
|
| 147 |
+
gr.Markdown("### 💡 مثالیں")
|
| 148 |
examples = gr.Examples(
|
| 149 |
examples=[
|
| 150 |
+
["میں آج بہت خوش ہوں"],
|
| 151 |
+
["دل ٹوٹ گیا ہے"],
|
| 152 |
+
["دوستوں کے ساتھ پارٹی کا مزہ آیا"],
|
| 153 |
+
["نیند آ رہی ہے"],
|
| 154 |
["امی نے میری پسندیدہ کھانا بنایا ہے"],
|
| 155 |
+
["محبت میں پڑ گیا ہوں"],
|
| 156 |
["غصہ سے دماغ پھٹ رہا ہے"],
|
| 157 |
+
["بارش ہو رہی ہے"]
|
| 158 |
],
|
| 159 |
inputs=input_text,
|
| 160 |
outputs=output_text,
|
|
|
|
| 162 |
cache_examples=False
|
| 163 |
)
|
| 164 |
|
| 165 |
+
# Connect button to function
|
| 166 |
predict_btn.click(fn=predict_emoji, inputs=input_text, outputs=output_text)
|
| 167 |
|
| 168 |
if __name__ == "__main__":
|