File size: 29,228 Bytes
388a122 83eae80 388a122 83eae80 388a122 198257d 83eae80 a43818a 388a122 a43818a 388a122 a43818a 388a122 a43818a 388a122 a43818a 388a122 a43818a 388a122 a43818a 388a122 a43818a 388a122 a43818a 388a122 a43818a 388a122 a43818a 388a122 67e0ba1 9a08dab 388a122 67e0ba1 388a122 67e0ba1 388a122 67e0ba1 388a122 83eae80 388a122 e67ff88 fd7d4ce e67ff88 83eae80 388a122 83eae80 388a122 83eae80 388a122 67e0ba1 388a122 67e0ba1 66941bd 9a08dab feea326 9a08dab feea326 9a08dab feea326 9a08dab 388a122 9a08dab 388a122 9a08dab 66941bd 9a08dab aa11727 388a122 308327e 8b0ddaa 388a122 7b385b7 388a122 1b3b774 388a122 7b385b7 388a122 66941bd 711bd88 388a122 aa11727 711bd88 8b0ddaa 388a122 8b0ddaa 9a08dab 388a122 aa11727 388a122 9a08dab 388a122 aa11727 388a122 aa11727 388a122 aa11727 9a08dab 711bd88 388a122 66941bd 388a122 aa11727 388a122 aa11727 711bd88 388a122 aa11727 388a122 711bd88 388a122 e67ff88 388a122 e67ff88 388a122 e67ff88 c2473dc 388a122 67e0ba1 388a122 711bd88 388a122 711bd88 388a122 e67ff88 711bd88 e67ff88 711bd88 388a122 711bd88 e67ff88 388a122 711bd88 e67ff88 711bd88 388a122 5d3f55d 388a122 e67ff88 711bd88 5d3f55d 711bd88 e67ff88 711bd88 388a122 711bd88 388a122 870c866 388a122 711bd88 388a122 711bd88 e67ff88 711bd88 388a122 870c866 388a122 e67ff88 711bd88 388a122 711bd88 e67ff88 711bd88 388a122 aa11727 e67ff88 711bd88 388a122 711bd88 e67ff88 711bd88 aa11727 388a122 e67ff88 711bd88 388a122 e67ff88 aa11727 388a122 870c866 388a122 e67ff88 c2473dc 870c866 388a122 e67ff88 c2473dc 388a122 e67ff88 53a6c92 198257d 0e5f439 198257d e67ff88 198257d e67ff88 198257d e67ff88 198257d 870c866 e67ff88 870c866 e67ff88 870c866 e67ff88 870c866 53a6c92 388a122 e67ff88 53a6c92 711bd88 aa11727 198257d 870c866 53a6c92 83eae80 67e0ba1 388a122 83eae80 388a122 53a6c92 388a122 83eae80 53a6c92 83eae80 388a122 67e0ba1 388a122 83eae80 67e0ba1 388a122 67e0ba1 388a122 67e0ba1 388a122 67e0ba1 53a6c92 67e0ba1 388a122 83eae80 388a122 83eae80 388a122 83eae80 5d3f55d 83eae80 5d3f55d 66941bd 388a122 66941bd 870c866 198257d 388a122 66941bd 388a122 5d3f55d 388a122 5d3f55d 9a47423 fc770a7 388a122 5d3f55d fc770a7 c5cdc29 83eae80 388a122 83eae80 aa11727 5d3f55d 67e0ba1 aa11727 5d3f55d aa11727 5d3f55d aa11727 711bd88 aa11727 67e0ba1 aa11727 5d3f55d 83eae80 c2473dc 388a122 711bd88 83eae80 5d3f55d 67e0ba1 198257d 5d3f55d 67e0ba1 870c866 711bd88 83eae80 711bd88 5d3f55d 67e0ba1 388a122 67e0ba1 388a122 67e0ba1 388a122 66941bd 67e0ba1 711bd88 67e0ba1 541c800 67e0ba1 388a122 67e0ba1 aa11727 388a122 67e0ba1 388a122 66941bd 67e0ba1 711bd88 53a6c92 388a122 0e5f439 198257d 870c866 388a122 e67ff88 388a122 e67ff88 c2473dc 388a122 e67ff88 388a122 e67ff88 67e0ba1 711bd88 aa11727 388a122 e67ff88 aa11727 711bd88 388a122 711bd88 53a6c92 711bd88 53a6c92 83eae80 388a122 | 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 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 | import gradio as gr
import torch
import os
import numpy as np
import soundfile as sf
import tempfile
import json
import uuid
import re
import time
from datetime import datetime
from transformers import (
AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline,
AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
)
from peft import PeftModel
from huggingface_hub import snapshot_download, HfApi, hf_hub_download
import shutil
from threading import Thread
# โโ Config โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
WHISPER_BASE = "openai/whisper-large-v3-turbo"
WHISPER_REPO = "mozed54/whisper-finetuned"
GEMMA_BASE = "google/gemma-2-2b-it"
GEMMA_REPO = "mozed54/modelV3"
FEEDBACK_REPO = "mozed54/whisper-feedback"
FEEDBACK2_REPO = "mozed54/gemma-feedback"
HF_TOKEN = os.environ.get("HF_TOKEN")
device = "cuda" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if device == "cuda" else torch.float32
# โโ Chargement Whisper โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
print("Chargement Whisper...")
whisper_base = AutoModelForSpeechSeq2Seq.from_pretrained(
WHISPER_BASE, torch_dtype=torch_dtype, use_safetensors=True,
)
whisper_adapter = snapshot_download(
repo_id=WHISPER_REPO, repo_type="dataset",
token=HF_TOKEN if HF_TOKEN else None,
)
whisper_model = PeftModel.from_pretrained(whisper_base, whisper_adapter)
whisper_model = whisper_model.merge_and_unload()
whisper_model.to(device)
whisper_processor = AutoProcessor.from_pretrained(WHISPER_BASE)
whisper_pipe = pipeline(
"automatic-speech-recognition",
model=whisper_model,
tokenizer=whisper_processor.tokenizer,
feature_extractor=whisper_processor.feature_extractor,
torch_dtype=torch_dtype,
device=device,
generate_kwargs={"language": "arabic", "task": "transcribe"},
)
print("Whisper pret !")
# โโ Chargement Gemma โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
print("Chargement Gemma...")
gemma_tokenizer = AutoTokenizer.from_pretrained(GEMMA_BASE, token=HF_TOKEN)
gemma_base = AutoModelForCausalLM.from_pretrained(
GEMMA_BASE,
torch_dtype=torch_dtype,
token=HF_TOKEN,
)
gemma_adapter = snapshot_download(
repo_id=GEMMA_REPO, repo_type="dataset",
token=HF_TOKEN if HF_TOKEN else None,
)
gemma_model = PeftModel.from_pretrained(gemma_base, gemma_adapter, is_trainable=False)
gemma_model = gemma_model.merge_and_unload()
gemma_model.to(device)
print("Gemma pret !")
# โโ รtat global โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
current_audio = {"path": None, "filename": None}
current_exchange = {"transcription": None, "reponse": None}
stop_generation = {"value": False}
audio_state = {"mic_ready": False, "file_ready": False}
def btn_states():
mic_label = "๐ค Transcrire la voix"
file_label = "๐ Transcrire le fichier"
return (
gr.update(interactive=audio_state["mic_ready"], value=mic_label),
gr.update(interactive=audio_state["file_ready"], value=file_label),
)
def btn_states_disabled():
"""Dรฉsactive les deux boutons de transcription (traitement en cours)."""
return (
gr.update(interactive=False, value="๐ค Transcrire la voix"),
gr.update(interactive=False, value="๐ Transcrire le fichier"),
)
# โโ Helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def generate_audio_name():
dt = datetime.utcnow().strftime("%Y-%m-%d_%H-%M-%S")
uid = uuid.uuid4().hex[:6]
return f"{dt}{uid}.wav"
def process_audio(audio):
if audio is None:
return None
if isinstance(audio, tuple):
sample_rate, data = audio
if data.ndim > 1:
data = data.mean(axis=1)
data = data.astype(np.float32)
if np.abs(data).max() > 1.0:
data = data / 32768.0
tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
sf.write(tmp.name, data, sample_rate)
return tmp.name
return audio
def append_and_upload(feedback_file, entry, repo_id):
api = HfApi(token=HF_TOKEN)
local = f"/tmp/{repo_id.replace('/', '')}.jsonl"
try:
existing = hf_hub_download(
repo_id=repo_id, filename="feedback.jsonl",
repo_type="dataset", token=HF_TOKEN,
)
shutil.copy(existing, local)
except Exception:
pass
with open(local, "a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
api.upload_file(
path_or_fileobj=local, path_in_repo="feedback.jsonl",
repo_id=repo_id, repo_type="dataset", token=HF_TOKEN,
)
# โโ Prompt Gemma โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
SYSTEM_PROMPT = (
"ุฃูุช ู
ุณุงุนุฏ ุฐูุงุก ุงุตุทูุงุนู ู
ุชุฎุตุต ูู ุงูุฑุฏ ุนูู ุงูุชุนูููุงุช ุงูู
ูุชูุจุฉ ุจุงูุฏุงุฑุฌุฉ ุงูุฌุฒุงุฆุฑูุฉ "
"ุนู ู
ุนุงูุฌุฉ ุงููุตูุต ุงูุตูุชูุฉ. "
"ุฅุฐุง ูุงู ุงููุต ูุชุนูู ุจุฎุฏู
ุงุช ุงูุงุชุตุงูุงุช (ู
ูุฏู
ุ ููุจุฑุ ุดูููุ ุชุนุจุฆุฉ)ุ ูู
ุจุงูุฑุฏ ุนููู ู
ุจุงุดุฑุฉ "
"ุจุงุณู
ุฎุฏู
ุฉ ุงูุนู
ูุงุก ุจููุฌุฉ ุฌุฒุงุฆุฑูุฉ ู
ูุฐุจุฉ ูู
ููุฏุฉ. "
"ุฃู
ุง ุฅุฐุง ูุงู ุงููุต ุนุจุงุฑุฉ ุนู ุณุคุงู ุฃู ุงุณุชูุณุงุฑ ุนุงู
ูู ุฃู ู
ุฌุงู ุขุฎุฑุ ูุฃุฌุจ ุนููู ู
ุจุงุดุฑุฉ "
"ูุจุดูู ุทุจูุนู ุจุงูุฏุงุฑุฌุฉ ุงูุฌุฒุงุฆุฑูุฉ. "
"ุฅุฐุง ูุงู ุงููุต ุบูุฑ ู
ูููู
ุ ุงุนุชุฐุฑ ุจูุทู ูุงุทูุจ ุงูุชูุถูุญ. "
"ููู
ูุน ุงูุฑุฏ ุฅุฐุง ูุงู ุงููุต ูุญุชูู ุนูู ุดุชุงุฆู
ุ ุงุนุชุฐุฑ ุจุฃุฏุจ. "
"ู
ูู
ุฌุฏุงู: ุงูุชุจ ุงูุฑุฏ ุงูู
ุจุงุดุฑ ููุท. ูุง ุชูุชุจ ุฃู ุชุญูููุ ูุง ุชูุชุจ 'ุงููุฆุฉ'ุ ูุง ุชูุชุจ 'ุงูู
ูุฎุต'ุ "
"ููุง ุชูุชุจ 'ุงูุฑุฏ ุงูู
ูุชุฑุญ'. ุงูุชุจ ูุต ุงูุฑุฏ ููุท ู
ุจุงุดุฑุฉ ุจุฏูู ุฃู ู
ูุฏู
ุงุช."
)
def build_prompt(transcription: str) -> str:
messages = [
{
"role": "user",
"content": f"{SYSTEM_PROMPT}\n\nุงููุต: {transcription}",
}
]
return gemma_tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
# โโ Filtre caractรจres non-arabes โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def filter_arabic_only(text: str) -> str:
allowed = re.compile(
r'[^\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF'
r'\uFB50-\uFDFF\uFE70-\uFEFF'
r'\u0020\u00A0'
r'\u060C\u061B\u061F\u06D4'
r'\u0021-\u002F\u003A-\u0040'
r'\u005B-\u0060\u007B-\u007E'
r'\n]'
)
return allowed.sub('', text).strip()
def extract_reply(text: str) -> str:
lines = text.split('\n')
for i, line in enumerate(lines):
clean_line = re.sub(r'[*_()\[\]\s]+', ' ', line).strip()
if not re.search(r'ุงูุฑุฏ', clean_line):
continue
sep = ':' if ':' in line else ('๏ผ' if '๏ผ' in line else None)
if sep:
parts = line.split(sep, 1)
if len(parts) >= 2:
reply = parts[1].strip().strip('"\'\u201c\u201d\u2018\u2019\u00ab\u00bb')
reply = re.sub(r'[*_`#]+', '', reply).strip()
if len(reply) > 3:
return reply
next_parts = []
for j in range(i + 1, len(lines)):
nl = lines[j].strip().strip('"\'\u201c\u201d\u2018\u2019\u00ab\u00bb')
nl = re.sub(r'[*_`#*]+', '', nl).strip()
if nl:
next_parts.append(nl)
if next_parts:
reply = ' '.join(next_parts)
if len(reply) > 3:
return reply
return text
def truncate_gemma_output(text: str) -> str:
stop_tokens = [
"<end_of_turn>", "<start_of_turn>",
"\nุณุคุงู:", "\nุณูุงู:", "\nุงูุณุคุงู:",
"User:", "user:", "\nmodel\n",
"###", "---",
]
for token in stop_tokens:
if token in text:
text = text.split(token)[0].strip()
text = text.strip()
text = extract_reply(text)
text = filter_arabic_only(text)
sentences = re.split(r'(?<=[.!?ุ])\s+', text)
if len(sentences) > 4:
text = " ".join(sentences[:4]).strip()
if len(text) > 500:
text = text[:500].rsplit(" ", 1)[0].strip() + "..."
return text
# โโ Gรฉnรฉration Gemma avec streaming โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def generate_gemma_response(transcription: str, progress=None):
stop_generation["value"] = False
if progress:
progress(0.6, desc="๐ค Prรฉparation du prompt...")
prompt = build_prompt(transcription)
inputs = gemma_tokenizer(prompt, return_tensors="pt").to(device)
streamer = TextIteratorStreamer(
gemma_tokenizer,
skip_prompt=True,
skip_special_tokens=True,
decode_kwargs={"skip_special_tokens": True},
)
generation_kwargs = dict(
**inputs,
max_new_tokens=200,
do_sample=True,
temperature=0.2,
top_p=0.9,
top_k=40,
repetition_penalty=1.2,
no_repeat_ngram_size=4,
pad_token_id=gemma_tokenizer.eos_token_id,
eos_token_id=gemma_tokenizer.eos_token_id,
streamer=streamer,
)
if progress:
progress(0.75, desc="๐ค Gรฉnรฉration en cours...")
thread = Thread(target=gemma_model.generate, kwargs=generation_kwargs)
thread.start()
generated_text = ""
for new_text in streamer:
if stop_generation["value"]:
break
generated_text += new_text
truncated = truncate_gemma_output(generated_text)
yield truncated
thread.join()
final = truncate_gemma_output(generated_text)
yield final
# โโ รTAPE 1 : Transcription Whisper uniquement โโโโโโโโโโโโโโโโโโโโ
def transcribe_only(audio, progress=gr.Progress()):
path = process_audio(audio)
if path is None:
mic_u, file_u = btn_states()
yield (
"Aucun audio recu.",
gr.update(visible=False),
gr.update(visible=False),
mic_u,
file_u,
)
return
mic_u, file_u = btn_states_disabled()
yield (
gr.update(),
gr.update(visible=False),
gr.update(visible=False),
mic_u,
file_u,
)
try:
progress(0.3, desc="๐ Transcription audio...")
result = whisper_pipe(path, return_timestamps=False)
text = result["text"].strip()
current_audio["path"] = path
current_audio["filename"] = generate_audio_name()
current_exchange["transcription"] = text
current_exchange["reponse"] = None
progress(1.0, desc="โ
Transcription terminรฉe")
yield (
text,
gr.update(visible=False),
gr.update(visible=False),
gr.update(interactive=False),
gr.update(interactive=False),
)
except Exception as e:
mic_u, file_u = btn_states()
yield (
f"Erreur Whisper : {str(e)}",
gr.update(visible=False),
gr.update(visible=False),
mic_u,
file_u,
)
# โโ รTAPE 2 : Rรฉponse Gemma โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def respond_gemma(progress=gr.Progress()):
transcription = current_exchange.get("transcription")
if not transcription:
mic_u, file_u = btn_states()
yield (
"โ ๏ธ Pas de transcription disponible.",
gr.update(visible=False),
gr.update(visible=False),
mic_u,
file_u,
)
return
try:
progress(0.5, desc="๐ค Gemma rรฉflรฉchit...")
last_partial = ""
for partial in generate_gemma_response(transcription, progress=progress):
if stop_generation["value"]:
return
last_partial = partial
yield (
partial,
gr.update(visible=False),
gr.update(visible=False),
gr.update(interactive=False),
gr.update(interactive=False),
)
if stop_generation["value"]:
return
current_exchange["reponse"] = last_partial
progress(1.0, desc="โ
Terminรฉ")
mic_u, file_u = btn_states()
yield (
last_partial,
gr.update(visible=True),
gr.update(visible=True),
mic_u,
file_u,
)
except Exception as e:
mic_u, file_u = btn_states()
yield (
f"Erreur Gemma : {str(e)}",
gr.update(visible=False),
gr.update(visible=False),
mic_u,
file_u,
)
# โโ Rรฉgรฉnรฉration Gemma seule โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def regenerate_gemma_only(progress=gr.Progress()):
transcription = current_exchange.get("transcription")
if not transcription:
mic_u, file_u = btn_states()
yield "", gr.update(visible=False), mic_u, file_u
return
# Dรฉsactive les boutons de transcription pendant la rรฉgรฉnรฉration
mic_u, file_u = btn_states_disabled()
yield gr.update(), gr.update(visible=False), mic_u, file_u
try:
progress(0.3, desc="๐ Rรฉgรฉnรฉration...")
last_partial = ""
for partial in generate_gemma_response(transcription, progress=progress):
if stop_generation["value"]:
return
last_partial = partial
yield partial, gr.update(visible=False), gr.update(interactive=False), gr.update(interactive=False)
if stop_generation["value"]:
return
current_exchange["reponse"] = last_partial
progress(1.0, desc="โ
Prรชt")
mic_u, file_u = btn_states()
yield last_partial, gr.update(visible=True), mic_u, file_u
except Exception as e:
mic_u, file_u = btn_states()
yield f"Erreur : {str(e)}", gr.update(visible=False), mic_u, file_u
# โโ Gestion de l'enregistrement micro (attente de chargement) โโโโโ
def on_audio_recorded(audio):
if audio is None:
audio_state["mic_ready"] = False
# Audio supprimรฉ -> bouton inactif
return gr.update(interactive=False, value="๐ค Transcrire la voix")
audio_state["mic_ready"] = False
# On affiche un รฉtat "chargement" pendant l'attente
yield gr.update(interactive=False, value="โณ Chargement de l'audio...")
time.sleep(2)
audio_state["mic_ready"] = True
yield gr.update(interactive=True, value="๐ค Transcrire la voix")
def on_file_uploaded(audio):
"""
Appelรฉ dรจs qu'un fichier audio est chargรฉ (ou supprimรฉ) dans le composant upload.
On dรฉsactive le bouton 'Transcrire le fichier' si aucun fichier n'est prรฉsent,
et on attend 2 secondes avant de le rรฉactiver pour laisser le temps au fichier
de se charger cรดtรฉ navigateur.
"""
if audio is None:
audio_state["file_ready"] = False
return gr.update(interactive=False, value="๐ Transcrire le fichier")
audio_state["file_ready"] = False
yield gr.update(interactive=False, value="โณ Chargement du fichier...")
time.sleep(2)
audio_state["file_ready"] = True
yield gr.update(interactive=True, value="๐ Transcrire le fichier")
# โโ Reset โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def reset_all():
stop_generation["value"] = True
current_audio["path"] = None
current_audio["filename"] = None
current_exchange["transcription"] = None
current_exchange["reponse"] = None
audio_state["mic_ready"] = False
audio_state["file_ready"] = False
return (
None, None, "", "",
gr.update(visible=False), gr.update(visible=False),
None, None, "", "",
gr.update(interactive=False, value="๐ค Transcrire la voix"),
gr.update(interactive=False, value="๐ Transcrire le fichier"),
)
# โโ Feedback Whisper โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def save_feedback_whisper(transcription, note):
if not transcription or note is None:
return "โ ๏ธ Transcription ou note manquante."
try:
api = HfApi(token=HF_TOKEN)
ts = datetime.utcnow().isoformat()
audio_nm = current_audio["filename"] or "inconnu.wav"
entry = {
"timestamp": ts,
"audio_file": audio_nm,
"transcription": transcription,
"note": int(note),
}
append_and_upload("feedback.jsonl", entry, FEEDBACK_REPO)
if current_audio["path"] and os.path.exists(current_audio["path"]):
api.upload_file(
path_or_fileobj=current_audio["path"],
path_in_repo=f"audios/{audio_nm}",
repo_id=FEEDBACK_REPO, repo_type="dataset", token=HF_TOKEN,
)
return f"โ
Feedback enregistre โ {'โญ' * int(note)}"
except Exception as e:
return f"โ Erreur : {str(e)}"
# โโ Feedback Gemma โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def save_feedback_gemma(note):
t = current_exchange["transcription"]
r = current_exchange["reponse"]
if not t or not r or note is None:
return "โ ๏ธ Effectue une transcription d'abord."
try:
ts = datetime.utcnow().isoformat()
entry = {
"timestamp": ts,
"transcription": t,
"reponse": r,
"note": int(note),
}
append_and_upload("feedback.jsonl", entry, FEEDBACK2_REPO)
return f"โ
Feedback enregistre โ {'โญ' * int(note)}"
except Exception as e:
return f"โ Erreur : {str(e)}"
# โโ CSS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
css = """
@import url("https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600&display=swap");
body, .gradio-container { font-family: "DM Sans", sans-serif !important; background: #0f0f13 !important; }
.gradio-container { max-width: 900px !important; margin: 0 auto !important; padding: 2rem 1.5rem !important; }
#app-header { text-align: center; margin-bottom: 2rem; padding: 2rem 0 1.5rem; border-bottom: 1px solid #1e1e2a; }
#app-header h1 { font-size: 2rem; font-weight: 600; color: #f0f0f5; margin: 0 0 0.4rem; }
#app-header p { font-size: 0.9rem; color: #6b6b80; margin: 0; }
.section-label { font-size: 0.72rem; font-weight: 600; color: #4a4a60; letter-spacing: 0.12em; text-transform: uppercase; margin-bottom: 0.6rem; }
/* Bouton Transcrire le fichier - BLEU */
#file-btn {
background: linear-gradient(135deg, #5a5aff 0%, #4040d9 100%) !important;
color: #fff !important;
border: none !important;
border-radius: 10px !important;
font-weight: 600 !important;
font-size: 0.95rem !important;
padding: 0.75rem 1.4rem !important;
box-shadow: 0 4px 14px rgba(90, 90, 255, 0.35) !important;
transition: all 0.2s ease !important;
}
#file-btn:hover:not(:disabled) {
background: linear-gradient(135deg, #4848e0 0%, #3030c0 100%) !important;
box-shadow: 0 6px 20px rgba(90, 90, 255, 0.45) !important;
transform: translateY(-1px) !important;
}
/* Boutons Transcrire - รฉtat dรฉsactivรฉ / chargement */
#mic-btn:disabled, #mic-btn[disabled],
#file-btn:disabled, #file-btn[disabled] {
opacity: 0.55 !important;
cursor: not-allowed !important;
filter: grayscale(40%) !important;
}
/* Boutons Envoyer feedback - ORANGE/JAUNE */
#btn-whisper-feedback, #btn-gemma-feedback {
background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%) !important;
color: #1a1000 !important;
border: none !important;
border-radius: 10px !important;
font-weight: 600 !important;
font-size: 0.88rem !important;
padding: 0.6rem 1.4rem !important;
letter-spacing: 0.03em !important;
box-shadow: 0 3px 12px rgba(245, 158, 11, 0.35) !important;
transition: all 0.18s ease !important;
cursor: pointer !important;
margin-top: 0.5rem !important;
}
#btn-whisper-feedback:hover, #btn-gemma-feedback:hover {
background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%) !important;
box-shadow: 0 5px 18px rgba(245, 158, 11, 0.5) !important;
transform: translateY(-1px) !important;
}
#btn-whisper-feedback:active, #btn-gemma-feedback:active {
transform: translateY(0) !important;
box-shadow: 0 2px 8px rgba(245, 158, 11, 0.3) !important;
}
button.danger { background: #dc2626 !important; color: #fff !important; border: none !important; border-radius: 10px !important; font-weight: 500 !important; padding: 0.7rem 1.4rem !important; }
button.danger:hover { background: #b91c1c !important; }
button.regenerate { background: #7c3aed !important; color: #fff !important; border: none !important; border-radius: 10px !important; font-weight: 500 !important; padding: 0.5rem 1rem !important; }
button.regenerate:hover { background: #6d28d9 !important; }
#transcription-box textarea { background: #0f0f13 !important; border: 1.5px solid #1e1e2a !important; border-radius: 14px !important; color: #e0e0ec !important; font-size: 1rem !important; line-height: 1.7 !important; padding: 1.2rem !important; direction: rtl !important; text-align: right !important; min-height: 120px !important; }
#transcription-box.has-text textarea { border-color: #22c97a !important; box-shadow: 0 0 0 3px rgba(34,201,122,0.12) !important; }
#gemma-box textarea { background: #0f0f13 !important; border: 1.5px solid #1e1e2a !important; border-radius: 14px !important; color: #e0e0ec !important; font-size: 1rem !important; line-height: 1.7 !important; padding: 1.2rem !important; direction: rtl !important; text-align: right !important; min-height: 120px !important; }
#gemma-box.has-text textarea { border-color: #a855f7 !important; box-shadow: 0 0 0 3px rgba(168,85,247,0.12) !important; }
.feedback-panel { background: #16161f; border: 1px solid #1e1e2a; border-radius: 14px; padding: 1.2rem 1.5rem; margin-top: 0.8rem; }
@media (max-width: 768px) {
.gr-audio canvas,
[data-testid="audio"] canvas,
.waveform-component canvas {
display: none !important;
}
.gr-audio,
[data-testid="audio"] {
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
}
footer { display: none !important; }
"""
# โโ JS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
js = """
function() {
const addListener = (id, cls) => {
const setup = () => {
const box = document.querySelector(id + " textarea");
const wrapper = document.querySelector(id);
if (!box || !wrapper) return setTimeout(() => setup(), 100);
const toggleClass = () => {
if (box.value && box.value.trim().length > 0) {
wrapper.classList.add(cls);
} else {
wrapper.classList.remove(cls);
}
};
box.addEventListener('input', toggleClass);
box.addEventListener('change', toggleClass);
toggleClass();
};
setup();
};
addListener("#transcription-box", "has-text");
addListener("#gemma-box", "has-text");
return [];
}
"""
# โโ Interface โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Blocks(title="Whisper + Gemma ยท Darija", css=css, js=js) as demo:
gr.HTML('<div id="app-header"><h1>๐ Whisper ยท Gemma ยท Darija</h1><p>Transcription + Rรฉponse โ dialecte algรฉrien</p></div>')
gr.HTML('<div class="section-label">Source audio</div>')
with gr.Row():
with gr.Column(scale=1):
mic_input = gr.Audio(sources=["microphone"], type="numpy", label="๐ค Enregistrer ma voix")
mic_btn = gr.Button("๐ค Transcrire la voix", variant="primary", interactive=False, elem_id="mic-btn")
with gr.Column(scale=1):
file_input = gr.Audio(sources=["upload"], type="numpy", label="๐ Charger un fichier audio")
file_btn = gr.Button("๐ Transcrire le fichier", elem_id="file-btn", interactive=False)
gr.HTML("<hr style='border:none;border-top:1px solid #1e1e2a;margin:1.5rem 0;'>")
with gr.Row():
with gr.Column(scale=1):
gr.HTML('<div class="section-label">๐ Transcription </div>')
whisper_out = gr.Textbox(
label="", lines=5, placeholder="ุงููุต ุณูุธูุฑ ููุง",
interactive=False, elem_id="transcription-box", show_label=False,
)
with gr.Column(visible=False, elem_classes="feedback-panel") as fb_whisper:
gr.HTML('<div class="section-label" style="margin-top:0;">Evaluer Transcription</div>')
note_whisper = gr.Radio(choices=["1","2","3","4","5"], label="", info="1 = tres mauvais ยท 5 = parfait", show_label=False)
btn_whisper = gr.Button("Envoyer", elem_id="btn-whisper-feedback")
status_whisper = gr.Textbox(label="", show_label=False, interactive=False, lines=1)
with gr.Column(scale=1):
gr.HTML('<div class="section-label">๐ค Rรฉponse</div>')
gemma_out = gr.Textbox(
label="", lines=5, placeholder="ุงูุฌูุงุจ ุณูุธูุฑ ููุง",
interactive=False, elem_id="gemma-box", show_label=False,
)
with gr.Row():
regenerate_btn = gr.Button("๐ Rรฉgรฉnรฉrer", variant="regenerate", size="sm")
with gr.Column(visible=False, elem_classes="feedback-panel") as fb_gemma:
gr.HTML('<div class="section-label" style="margin-top:0;">Evaluer Rรฉponse</div>')
note_gemma = gr.Radio(choices=["1","2","3","4","5"], label="", info="1 = tres mauvais ยท 5 = parfait", show_label=False)
btn_gemma = gr.Button("Envoyer", elem_id="btn-gemma-feedback")
status_gemma = gr.Textbox(label="", show_label=False, interactive=False, lines=1)
gr.HTML("<hr style='border:none;border-top:1px solid #1e1e2a;margin:1.5rem 0;'>")
with gr.Row():
with gr.Column():
reset_btn = gr.Button("๐ Rรฉinitialiser tout", variant="danger")
mic_input.change(
fn=on_audio_recorded,
inputs=[mic_input],
outputs=[mic_btn],
)
file_input.change(
fn=on_file_uploaded,
inputs=[file_input],
outputs=[file_btn],
)
mic_btn.click(
fn=transcribe_only,
inputs=[mic_input],
outputs=[whisper_out, fb_whisper, fb_gemma, mic_btn, file_btn],
).then(
fn=respond_gemma,
inputs=[],
outputs=[gemma_out, fb_whisper, fb_gemma, mic_btn, file_btn],
)
file_btn.click(
fn=transcribe_only,
inputs=[file_input],
outputs=[whisper_out, fb_whisper, fb_gemma, mic_btn, file_btn],
).then(
fn=respond_gemma,
inputs=[],
outputs=[gemma_out, fb_whisper, fb_gemma, mic_btn, file_btn],
)
regenerate_btn.click(
fn=regenerate_gemma_only,
inputs=[],
outputs=[gemma_out, fb_gemma, mic_btn, file_btn],
)
btn_whisper.click(fn=save_feedback_whisper, inputs=[whisper_out, note_whisper], outputs=[status_whisper])
btn_gemma.click(fn=save_feedback_gemma, inputs=[note_gemma], outputs=[status_gemma])
reset_btn.click(
fn=reset_all,
outputs=[
mic_input, file_input, whisper_out, gemma_out,
fb_whisper, fb_gemma,
note_whisper, note_gemma, status_whisper, status_gemma,
mic_btn, file_btn,
],
)
demo.launch() |