Spaces:
Running
Running
File size: 16,924 Bytes
a7397b2 9969f5f 132d418 b981086 6bbd705 b981086 c1701e9 fd26154 132d418 a7397b2 6bbd705 b981086 6bbd705 b981086 c1701e9 a7397b2 fd26154 62b62ba 6bbd705 c1701e9 6bbd705 132d418 a7397b2 132d418 b981086 a7397b2 b981086 8c53e95 c1701e9 a7397b2 132d418 b981086 c1701e9 5a4965a b981086 5a4965a c1701e9 a7397b2 6bbd705 c1701e9 6bbd705 132d418 5a4965a 132d418 b981086 132d418 9969f5f b981086 132d418 b981086 bf6c1ce 132d418 b981086 132d418 c1701e9 132d418 6bbd705 c1701e9 6bbd705 9022d7b b981086 5a4965a c1701e9 5a4965a 0a31d3f 6bbd705 5a4965a c1701e9 6bbd705 b981086 5a4965a b981086 0a31d3f c1701e9 b981086 0a31d3f c1701e9 0a31d3f 5a4965a c1701e9 a7397b2 2f4c802 67510b3 2f4c802 67510b3 2f4c802 c1701e9 67510b3 c1701e9 5a4965a c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 67510b3 c1701e9 6bbd705 b981086 6bbd705 c1701e9 b981086 c1701e9 03d1cf7 67510b3 c1701e9 b981086 c1701e9 dd9c134 c1701e9 dd9c134 c1701e9 dd9c134 c1701e9 dd9c134 c1701e9 dd9c134 c1701e9 dd9c134 c1701e9 dd9c134 c1701e9 b981086 9022d7b dd9c134 9022d7b bf6c1ce c1701e9 9022d7b c1701e9 dd9c134 c1701e9 6bbd705 b981086 6bbd705 b981086 6bbd705 c1701e9 6bbd705 c1701e9 6bbd705 b981086 6bbd705 9022d7b c1701e9 6bbd705 2f4c802 c1701e9 6bbd705 a7397b2 9969f5f 6bbd705 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 | import gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
import logging
from huggingface_hub import login
from datetime import datetime
import pandas as pd
from datasets import Dataset, load_dataset, Features, Value
import os
logging.basicConfig(level=logging.INFO)
# ==============================================
# CONFIGURATION
# ==============================================
HF_DATASET_NAME = "AdhamAshraf/slanggpt-feedback-dataset"
MODEL_NAME = "AdhamAshraf/SlangGPT"
HF_TOKEN = os.getenv("HF_TOKEN")
if not HF_TOKEN:
raise RuntimeError(
"HF_TOKEN environment variable not set. "
"Please add a secret named 'HF_TOKEN' with your Hugging Face write token."
)
login(token=HF_TOKEN)
print("โ
Logged in to Hugging Face Hub")
# ==============================================
# EXPLICIT SCHEMA โ prevents column-mismatch errors
# ==============================================
FEEDBACK_FEATURES = Features({
"egyptian_arabic": Value("string"),
"generated_msa": Value("string"),
"user_label": Value("string"),
"user_rating": Value("int64"),
"corrected_msa": Value("string"),
"timestamp": Value("string"),
})
# ==============================================
# LOAD GENERATION MODEL
# ==============================================
print("Loading tokenizer...")
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
tokenizer.padding_side = "left"
print("Loading model...")
dtype = torch.float16 if torch.cuda.is_available() else torch.float32
model = AutoModelForCausalLM.from_pretrained(
MODEL_NAME,
torch_dtype=dtype,
device_map="auto",
low_cpu_mem_usage=True,
)
model.eval()
print("โ
Model loaded successfully")
# ==============================================
# CACHE FEEDBACK DATASET AT STARTUP
# ==============================================
print("Loading feedback dataset...")
try:
_feedback_df = load_dataset(HF_DATASET_NAME, split="train").to_pandas()
if "corrected_msa" not in _feedback_df.columns:
_feedback_df["corrected_msa"] = ""
for col in ["egyptian_arabic", "generated_msa", "user_label", "corrected_msa", "timestamp"]:
_feedback_df[col] = _feedback_df[col].fillna("").astype(str)
_feedback_df["user_rating"] = _feedback_df["user_rating"].fillna(-1).astype("int64")
print(f"โ
Feedback dataset loaded ({len(_feedback_df)} existing rows)")
except Exception as e:
print(f"โ ๏ธ No existing feedback dataset โ starting fresh ({e})")
_feedback_df = pd.DataFrame(columns=list(FEEDBACK_FEATURES.keys()))
# ==============================================
# TRANSLATION
# ==============================================
def translate_to_msa(egyptian_text):
if not egyptian_text or not egyptian_text.strip():
return "Please enter an Egyptian Arabic phrase."
prompt = f"dialect: {egyptian_text.strip()} โ msa:"
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=64)
inputs = {k: v.to(model.device) for k, v in inputs.items()}
with torch.inference_mode():
outputs = model.generate(
**inputs,
max_new_tokens=48,
do_sample=False,
repetition_penalty=1.3,
pad_token_id=tokenizer.pad_token_id,
eos_token_id=tokenizer.eos_token_id,
)
full_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
result = full_output.split("msa:")[-1].strip() if "msa:" in full_output else full_output
result = result.split("โ")[0].strip()
return result if result else "[No translation generated.]"
# ==============================================
# FEEDBACK SAVING
# ==============================================
def save_feedback(egyptian_input, generated_output, correct_incorrect, rating, corrected_translation):
global _feedback_df
if not generated_output or not generated_output.strip() or generated_output.startswith("["):
return "โ ๏ธ No valid translation to rate. Please translate something first."
if rating is None:
return "โ ๏ธ Please provide a quality rating before submitting."
rating = int(rating)
is_incorrect = correct_incorrect == "โ Incorrect"
low_rating = rating <= 2
needs_correction = is_incorrect or low_rating
has_correction = bool(corrected_translation and corrected_translation.strip())
if needs_correction and not has_correction:
if is_incorrect:
return "โ ๏ธ Please provide the correct MSA translation before submitting."
else:
return f"โ ๏ธ Rating of {rating}/5 is low โ please provide a better translation before submitting."
new_row = {
"egyptian_arabic": egyptian_input.strip(),
"generated_msa": generated_output.strip(),
"user_label": "incorrect" if is_incorrect else "correct",
"user_rating": rating,
"corrected_msa": corrected_translation.strip() if needs_correction and has_correction else "",
"timestamp": datetime.utcnow().isoformat() + "Z",
}
_feedback_df = pd.concat([_feedback_df, pd.DataFrame([new_row])], ignore_index=True)
_feedback_df["user_rating"] = _feedback_df["user_rating"].fillna(-1).astype("int64")
try:
Dataset.from_pandas(_feedback_df, features=FEEDBACK_FEATURES).push_to_hub(
HF_DATASET_NAME, split="train", private=False
)
return "โ
Feedback recorded โ ุดูุฑุงู!"
except Exception as e:
_feedback_df = _feedback_df.iloc[:-1].reset_index(drop=True)
return f"โ ๏ธ Could not save feedback: {str(e)}"
# ==============================================
# RESET UI
# ==============================================
def reset_feedback_ui():
return (
gr.update(visible=False),
gr.update(value=""),
gr.update(value="โ
Correct"),
gr.update(value=None),
gr.update(value=""),
)
# ==============================================
# MOBILE-RESPONSIVE CSS
# ==============================================
CSS = """
@import url('https://fonts.googleapis.com/css2?family=Noto+Naskh+Arabic:wght@400;600&family=DM+Mono:wght@400;500&family=DM+Sans:wght@300;400;500;600&display=swap');
:root {
--bg: #0f1117;
--surface: #181c27;
--border: #2a2f3d;
--accent: #4f8ef7;
--accent2: #a78bfa;
--text: #e8eaf0;
--muted: #6b7280;
--success: #34d399;
--warn: #f87171;
--radius: 12px;
--mono: 'DM Mono', monospace;
--sans: 'DM Sans', sans-serif;
--arabic: 'Noto Naskh Arabic', serif;
}
/* โโ Base โโ */
body, .gradio-container {
background: var(--bg) !important;
font-family: var(--sans) !important;
color: var(--text) !important;
/* prevent horizontal overflow on mobile */
overflow-x: hidden !important;
}
/* โโ Header โโ */
#header {
text-align: center;
padding: 2rem 1rem 1rem;
border-bottom: 1px solid var(--border);
margin-bottom: 1.5rem;
}
#header h1 {
font-family: var(--mono);
font-size: clamp(1.4rem, 5vw, 2rem);
letter-spacing: -0.02em;
background: linear-gradient(135deg, var(--accent), var(--accent2));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
margin: 0 0 0.25rem;
}
#header p {
color: var(--muted);
font-size: clamp(0.75rem, 2.5vw, 0.9rem);
margin: 0;
line-height: 1.5;
}
/* โโ Inputs โโ */
textarea, input[type=text] {
background: #0f1117 !important;
border: 1px solid var(--border) !important;
border-radius: 8px !important;
color: var(--text) !important;
font-family: var(--arabic) !important;
font-size: clamp(1rem, 3.5vw, 1.1rem) !important;
line-height: 1.7 !important;
direction: rtl;
transition: border-color 0.2s;
/* Prevent zoom on focus in iOS (font-size must be >= 16px equivalent) */
touch-action: manipulation;
}
textarea:focus, input[type=text]:focus {
border-color: var(--accent) !important;
outline: none !important;
box-shadow: 0 0 0 3px rgba(79,142,247,0.15) !important;
}
#output-box textarea {
background: #13161f !important;
color: #a5f3c0 !important;
font-size: clamp(1rem, 3.5vw, 1.15rem) !important;
}
/* โโ Buttons โโ */
button.primary, #translate-btn {
background: linear-gradient(135deg, var(--accent), var(--accent2)) !important;
border: none !important;
border-radius: 8px !important;
color: #fff !important;
font-family: var(--sans) !important;
font-weight: 600 !important;
font-size: clamp(0.85rem, 3vw, 0.95rem) !important;
/* taller tap target on mobile */
padding: 0.75rem 1.4rem !important;
min-height: 48px !important;
width: 100% !important;
cursor: pointer !important;
transition: opacity 0.15s, transform 0.1s !important;
touch-action: manipulation;
}
button.primary:hover, #translate-btn:hover {
opacity: 0.88 !important;
transform: translateY(-1px) !important;
}
#submit-btn {
background: var(--surface) !important;
border: 1px solid var(--accent) !important;
border-radius: 8px !important;
color: var(--accent) !important;
font-family: var(--sans) !important;
font-weight: 500 !important;
min-height: 48px !important;
width: 100% !important;
transition: background 0.15s !important;
touch-action: manipulation;
}
#submit-btn:hover {
background: rgba(79,142,247,0.1) !important;
}
/* โโ Radio & Slider โโ */
.gr-radio-item label {
color: var(--text) !important;
font-family: var(--sans) !important;
/* larger touch target */
padding: 0.4rem 0 !important;
min-height: 44px !important;
display: flex !important;
align-items: center !important;
}
.gr-radio-item input[type=radio] {
width: 20px !important;
height: 20px !important;
}
input[type=range] {
accent-color: var(--accent) !important;
height: 6px !important;
/* taller hit area */
padding: 12px 0 !important;
cursor: pointer;
touch-action: manipulation;
}
/* โโ Labels โโ */
label span, .gr-form label {
color: var(--muted) !important;
font-family: var(--sans) !important;
font-size: clamp(0.72rem, 2vw, 0.82rem) !important;
text-transform: uppercase !important;
letter-spacing: 0.06em !important;
}
/* โโ Status โโ */
#status-box textarea {
background: transparent !important;
border: none !important;
color: var(--success) !important;
font-family: var(--mono) !important;
font-size: clamp(0.8rem, 2.5vw, 0.9rem) !important;
text-align: center;
}
/* โโ Examples table โโ */
.gr-samples-table td {
font-family: var(--arabic) !important;
font-size: clamp(0.9rem, 3vw, 1rem) !important;
direction: rtl;
color: var(--text) !important;
/* comfortable row height on mobile */
padding: 0.6rem 0.75rem !important;
}
.gr-samples-table tr:hover td {
background: rgba(79,142,247,0.07) !important;
cursor: pointer;
}
/* โโ Section labels โโ */
.section-label {
font-family: var(--mono);
font-size: clamp(0.68rem, 2vw, 0.75rem);
letter-spacing: 0.1em;
color: var(--muted);
text-transform: uppercase;
margin: 1.2rem 0 0.5rem;
display: flex;
align-items: center;
gap: 0.6rem;
}
.section-label::after {
content: '';
flex: 1;
height: 1px;
background: var(--border);
}
/* โโ Feedback panel โโ */
#feedback-panel {
border: 1px solid var(--border) !important;
border-radius: var(--radius) !important;
padding: 1rem !important;
margin-top: 1rem !important;
}
/* โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
RESPONSIVE BREAKPOINTS
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
/* Tablet / large phone โ stack the two columns */
@media (max-width: 768px) {
/* Gradio Row becomes a single column */
.gr-row {
flex-direction: column !important;
gap: 0 !important;
}
.gr-column {
width: 100% !important;
min-width: 0 !important;
flex: none !important;
}
/* Give textareas a comfortable height on phone */
textarea {
min-height: 100px !important;
}
/* Feedback radio stack vertically */
.gr-radio-group {
flex-direction: column !important;
}
}
/* Small phones */
@media (max-width: 480px) {
.gradio-container {
padding: 0 0.5rem !important;
}
#header {
padding: 1.25rem 0.5rem 0.75rem;
}
textarea {
min-height: 90px !important;
font-size: 1rem !important; /* prevents iOS zoom */
}
/* Make slider label wrap gracefully */
.gr-form label span {
white-space: normal !important;
}
}
"""
# ==============================================
# GRADIO INTERFACE
# ==============================================
with gr.Blocks(title="SlangGPT", css=CSS, theme=gr.themes.Base()) as demo:
gr.HTML("""
<div id="header">
<h1>SlangGPT</h1>
<p>Egyptian Arabic dialect โ Modern Standard Arabic (MSA)<br>ุงูููุฌุฉ ุงูู
ุตุฑูุฉ โ ุงููุตุญู</p>
</div>
""")
with gr.Row(equal_height=True):
with gr.Column(scale=1):
gr.HTML('<div class="section-label">Egyptian Arabic Input ยท ุงูุชุจ ุจุงูู
ุตุฑู</div>')
egyptian_input = gr.Textbox(
show_label=False,
placeholder="ุงูุชุจ ููุง ุจุงูููุฌุฉ ุงูู
ุตุฑูุฉโฆ",
lines=4,
rtl=True,
)
translate_btn = gr.Button(
"Translate ยท ุชุฑุฌู
โ",
variant="primary",
elem_id="translate-btn",
)
with gr.Column(scale=1):
gr.HTML('<div class="section-label">MSA Translation ยท ุงูุชุฑุฌู
ุฉ ุจุงููุตุญู</div>')
msa_output = gr.Textbox(
show_label=False,
lines=4,
interactive=False,
placeholder="ุณุชุธูุฑ ุงูุชุฑุฌู
ุฉ ููุงโฆ",
rtl=True,
elem_id="output-box",
)
gr.HTML('<div class="section-label">Try an example ยท ุฌุฑูุจ ู
ุซุงู</div>')
gr.Examples(
examples=[
["ุฅูุช ุฑุงูุญ ูููุ"],
["ุนุงูุฒ ุงูู ุญุงุฌุฉ ุญููุฉ"],
["ุงูุง ุชุนุจุงู ููู ุงูููุงุฑุฏู"],
["ุงูุฃูู ุฏู ูุงู ุชุญูุฉ"],
["ู
ู
ูู ุชุณุงุนุฏููุ"],
],
inputs=egyptian_input,
label="",
)
with gr.Group(visible=False, elem_id="feedback-panel") as feedback_group:
gr.HTML('<div class="section-label">Rate this translation ยท ูููู
ุงูุชุฑุฌู
ุฉ</div>')
with gr.Row():
correct_radio = gr.Radio(
choices=["โ
Correct", "โ Incorrect"],
value="โ
Correct",
label="Is the translation correct? ยท ูู ุงูุชุฑุฌู
ุฉ ุตุญูุญุฉุ",
scale=1,
)
rating_slider = gr.Slider(
minimum=0, maximum=5, step=1,
value=None,
label="Quality ยท ุงูุฌูุฏุฉ (0 = ุบูุฑ ู
ููุฏุฉ ยท 5 = ู
ู
ุชุงุฒุฉ) โ required ยท ู
ุทููุจ",
scale=2,
)
correction_textbox = gr.Textbox(
label="Better MSA translation ยท ุชุฑุฌู
ุฉ ุฃูุถู โ required if incorrect or rating โค 2 ยท ู
ุทููุจ ุฅุฐุง ูุงูุช ุฎุงุทุฆุฉ ุฃู ุงูุชูููู
โค 2",
lines=2,
visible=True,
placeholder="ุงูุชุฑุฌู
ุฉ ุงูุตุญูุญุฉ ููุงโฆ",
rtl=True,
)
submit_feedback = gr.Button("Submit Feedback ยท ุฃุฑุณู ุงูุชูููู
", elem_id="submit-btn")
feedback_status = gr.Textbox(
show_label=False,
interactive=False,
elem_id="status-box",
lines=1,
)
latest_translation = gr.State("")
translate_btn.click(
fn=translate_to_msa,
inputs=egyptian_input,
outputs=msa_output,
).then(
lambda out: (gr.update(visible=True), out),
inputs=msa_output,
outputs=[feedback_group, latest_translation],
)
submit_feedback.click(
fn=save_feedback,
inputs=[egyptian_input, latest_translation, correct_radio, rating_slider, correction_textbox],
outputs=feedback_status,
).then(
fn=reset_feedback_ui,
outputs=[feedback_group, correction_textbox, correct_radio, rating_slider, feedback_status],
)
if __name__ == "__main__":
demo.launch() |