File size: 50,262 Bytes
d65d3e4 c135088 d65d3e4 c135088 46c09c6 c135088 46c09c6 c135088 f89469b d65d3e4 6b6a76c ae87233 46c09c6 2dbcd48 7833b57 8a47287 cc73131 46c09c6 d65d3e4 2dbcd48 c135088 f89469b cc73131 c135088 cc73131 c135088 fe2c2fe 46c09c6 d65d3e4 c135088 cc73131 f89469b c135088 cc73131 c135088 cc73131 c135088 d1588a4 7739564 d1588a4 8c6438d 7833b57 8c6438d c135088 7739564 c135088 46c09c6 fe2c2fe 46c09c6 4f03bf3 fe2c2fe 46c09c6 c135088 cc73131 d65d3e4 c135088 d65d3e4 c135088 cc73131 d65d3e4 c135088 cc73131 d65d3e4 c135088 cc73131 d65d3e4 c135088 cc73131 d65d3e4 c135088 cc73131 d65d3e4 c135088 cc73131 d65d3e4 c135088 cc73131 f89469b 46c09c6 4f03bf3 46c09c6 4f03bf3 46c09c6 cc73131 c135088 cc73131 c135088 cc73131 c135088 f89469b cc73131 c135088 cc73131 c135088 20a492d c135088 20a492d c135088 7739564 d1588a4 7739564 c135088 d1588a4 7739564 20a492d c135088 7739564 c135088 7739564 c135088 7739564 c135088 d65d3e4 f89469b c135088 cc73131 c135088 d65d3e4 c135088 3d3e0f1 c135088 f89469b d65d3e4 55c27e2 46c09c6 55c27e2 46c09c6 55c27e2 c61799e 46c09c6 55c27e2 46c09c6 55c27e2 c61799e 55c27e2 46c09c6 55c27e2 46c09c6 55c27e2 46c09c6 55c27e2 c135088 46c09c6 c135088 46c09c6 c135088 46c09c6 c135088 c61799e 46c09c6 d69a5d8 46c09c6 c61799e 46c09c6 d69a5d8 46c09c6 d69a5d8 46c09c6 d69a5d8 46c09c6 c61799e 46c09c6 c61799e 46c09c6 c135088 46c09c6 c61799e 46c09c6 3d3e0f1 46c09c6 f89469b c135088 7739564 c135088 491f53e 7739564 491f53e c135088 7739564 491f53e 7739564 c135088 d65d3e4 c135088 491f53e 7739564 491f53e 7739564 c135088 d65d3e4 491f53e 3d3e0f1 c135088 cc73131 491f53e 3d3e0f1 7739564 3d3e0f1 7739564 c135088 f89469b 491f53e 7739564 c135088 f89469b c135088 7739564 c135088 cc73131 491f53e 7739564 491f53e 7739564 491f53e 7739564 c135088 f89469b 491f53e 7739564 c135088 f89469b c135088 7739564 c135088 7739564 491f53e 7739564 491f53e 7739564 c135088 f89469b c135088 7739564 c135088 f89469b c135088 7739564 c135088 f89469b c135088 7739564 491f53e 7739564 c135088 f89469b c135088 d69a5d8 c135088 f89469b d69a5d8 fe2c2fe d69a5d8 fe2c2fe d69a5d8 fe2c2fe 3d3e0f1 d69a5d8 3d3e0f1 d69a5d8 3d3e0f1 d69a5d8 c135088 f89469b c135088 491f53e 7739564 491f53e 7739564 491f53e 7739564 491f53e 7739564 491f53e 7739564 491f53e 7739564 491f53e 7739564 491f53e 7739564 d65d3e4 cc73131 f89469b c135088 491f53e c135088 491f53e c135088 d69a5d8 3d3e0f1 c135088 f89469b c61799e d69a5d8 fe2c2fe e44e7d1 491f53e 46c09c6 d69a5d8 46c09c6 d69a5d8 46c09c6 fe2c2fe d69a5d8 fe2c2fe d69a5d8 fe2c2fe f89469b 491f53e 46c09c6 f89469b 491f53e 46c09c6 c135088 46c09c6 2dbcd48 46c09c6 3d3e0f1 46c09c6 c135088 fe2c2fe 3d3e0f1 d69a5d8 fe2c2fe d69a5d8 fe2c2fe 3d3e0f1 fe2c2fe 46c09c6 3d3e0f1 46c09c6 c135088 46c09c6 c135088 46c09c6 2dbcd48 c135088 cc73131 3d3e0f1 f89469b cc73131 f89469b c135088 491f53e cc73131 c135088 6b6a76c 7739564 |
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 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 |
# =========================================
# ENV FIXES
# =========================================
import os
os.environ["OMP_NUM_THREADS"] = "1" # libgomp hatası fix
# =========================================
# IMPORTS
# =========================================
import logging
from pathlib import Path
from typing import Dict, Tuple, List, Optional, Any
from collections import defaultdict
from uuid import uuid4
import numpy as np
import librosa
import soundfile as sf
import torch
from transformers import AutoProcessor, AutoModelForSpeechSeq2Seq, AutoFeatureExtractor, AutoModel
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
import gradio as gr
from elevenlabs import ElevenLabs, save
from regions_geojson import TURKEY_REGIONS_GEOJSON
# =========================================
# LOGGING SETUP
# =========================================
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
# =========================================
# CONSTANTS
# =========================================
MODEL_ID = "openai/whisper-large-v3"
MIN_AUDIO_DURATION = 3.0 # seconds
VOWEL_SHIFT_WEIGHT = 0.35
MARKER_WEIGHT = 0.40
PROSODY_WEIGHT = 0.25
FAST_TEMPO_THRESHOLD = 140.0
SLOW_TEMPO_THRESHOLD = 80.0
TARGET_SAMPLE_RATE = 16000
EMBED_MODEL_ID = "facebook/wav2vec2-large-xlsr-53" # Turkish finetuning otomatik algılanır
EMBED_SAMPLE_RATE = 16000
DIALECT_REF_DIR = Path("data/dialects")
ELEVENLABS_VOICE_ID = "Q5n6GDIjpN0pLOlycRFT"
ELEVENLABS_MODEL_ID = "eleven_multilingual_v2"
# =========================================
# DEVICE CONFIGURATION
# =========================================
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
DTYPE = torch.float16 if DEVICE == "cuda" else torch.float32
logger.info(f"Using device: {DEVICE}, dtype: {DTYPE}")
# =========================================
# MODEL INITIALIZATION
# =========================================
try:
processor = AutoProcessor.from_pretrained(MODEL_ID)
model = AutoModelForSpeechSeq2Seq.from_pretrained(
MODEL_ID,
torch_dtype=DTYPE
)
model = model.to(DEVICE)
model.eval()
logger.info("Model loaded successfully")
except Exception as e:
logger.error(f"Error loading model: {e}")
raise
# =========================================
# EMBEDDING MODEL INITIALIZATION
# Note: Embedding model is disabled - we use transcription-based dialect analysis instead
# =========================================
embed_feature_extractor = None
embed_model = None
logger.debug("Embedding model disabled - using transcription-based analysis only")
DIALECT_REF_EMBEDDINGS: Dict[str, List[np.ndarray]] = defaultdict(list)
DIALECT_PROTOTYPES: Dict[str, np.ndarray] = {}
# =========================================
# ELEVENLABS CLIENT
# =========================================
ELEVENLABS_API_KEY = os.environ.get("ELEVENLABS_API_KEY")
if ELEVENLABS_API_KEY:
try:
elevenlabs_client = ElevenLabs(api_key=ELEVENLABS_API_KEY)
logger.info("ElevenLabs client initialized")
except Exception as e:
elevenlabs_client = None
logger.warning(f"Failed to initialize ElevenLabs client: {e}")
else:
elevenlabs_client = None
logger.warning("ELEVENLABS_API_KEY not found. Voice replies will be disabled.")
# =========================================
# DIALECT PROFILES
# =========================================
DIALECT_PROFILES: Dict[str, Dict[str, Any]] = {
"Marmara": {
"description": "İstanbul-Trakya şehir aksanı, düz prosodi.",
"vowel_shifts": {"a→ı": 0.1, "ı→i": 0.15, "e→i": 0.15, "o→u": 0.1},
"markers": ["abi", "aynen", "bi şey dicem", "baksana"],
"prosody": "düz-orta",
"tempo_range": (100, 130),
"pitch_range": "neutral"
},
"Ege": {
"description": "Melodik, uzatmalı, 'gari', 'hee' kültürüne sahip.",
"vowel_shifts": {"e→ee": 0.85, "o→oo": 0.75, "a→aa": 0.4},
"markers": ["gari", "hee", "ebe", "söyleyiver"],
"prosody": "yavaş-uzatmalı",
"tempo_range": (60, 90),
"pitch_range": "medium"
},
"Akdeniz": {
"description": "Hızlı, enerjik, 'la' baskın aksan.",
"vowel_shifts": {"a→aa": 0.65, "ı→i": 0.35},
"markers": ["la", "naapıyon la", "hee la"],
"prosody": "enerjik-hızlı",
"tempo_range": (130, 160),
"pitch_range": "high"
},
"İç Anadolu": {
"description": "Düz ritmik, ı/i kaymaları belirgin.",
"vowel_shifts": {"ı→i": 0.7, "a→ı": 0.5, "o→u": 0.3},
"markers": ["gelisen", "gideceksen", "hele bi dur"],
"prosody": "düz-ritmik",
"tempo_range": (100, 125),
"pitch_range": "neutral"
},
"Karadeniz": {
"description": "Yüksek tonlama, hızlı, ünlü daralması.",
"vowel_shifts": {"e→i": 0.9, "ö→u": 0.8, "a→e": 0.3},
"markers": ["ha bu", "da gel daa", "nere gideysin"],
"prosody": "yüksek-inişli-çıkışlı",
"tempo_range": (120, 150),
"pitch_range": "high-oscillating"
},
"Doğu Anadolu": {
"description": "Ağır tempo, geniş ünlü uzatmaları.",
"vowel_shifts": {"ı→i": 0.75, "u→o": 0.65, "a→â": 0.4},
"markers": ["he vallah", "gardaş", "ağabey"],
"prosody": "düşük-ağır",
"tempo_range": (70, 100),
"pitch_range": "low"
},
"Güneydoğu Anadolu": {
"description": "Ê/Î uzatmaları, uzun vurgu, ağır tempo.",
"vowel_shifts": {"a→ê": 0.9, "e→ê": 0.95, "i→î": 0.6},
"markers": ["ê", "hele", "gardaş", "bacı"],
"prosody": "uzun-vurgulu-ağır",
"tempo_range": (65, 95),
"pitch_range": "low-elongated"
}
}
# =========================================
# DIALECT EMBEDDING HELPERS
# =========================================
REGION_ALIAS_MAP = {
region.lower().replace(" ", ""): region
for region in DIALECT_PROFILES.keys()
}
def _resolve_region_from_name(name: str) -> Optional[str]:
key = (
name.lower()
.replace("-", "")
.replace("_", "")
.replace(" ", "")
)
if key in REGION_ALIAS_MAP:
return REGION_ALIAS_MAP[key]
for alias_key, region_name in REGION_ALIAS_MAP.items():
if alias_key in key or key in alias_key:
return region_name
return None
def embed_audio(audio_path: str) -> Optional[np.ndarray]:
"""
Convert an audio file into a fixed-length embedding vector.
"""
if embed_model is None or embed_feature_extractor is None:
logger.warning("Embedding model unavailable; cannot embed audio.")
return None
try:
audio_data, sr = sf.read(audio_path)
if audio_data.ndim > 1:
audio_data = np.mean(audio_data, axis=1)
if sr != EMBED_SAMPLE_RATE:
audio_data = librosa.resample(
audio_data,
orig_sr=sr,
target_sr=EMBED_SAMPLE_RATE
)
sr = EMBED_SAMPLE_RATE
inputs = embed_feature_extractor(
audio_data,
sampling_rate=sr,
return_tensors="pt"
)
inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
with torch.no_grad():
outputs = embed_model(**inputs)
hidden_states = outputs.last_hidden_state
embedding = hidden_states.mean(dim=1).squeeze().cpu().numpy()
return embedding
except Exception as e:
logger.error(f"Audio embedding failed: {e}")
return None
def load_reference_embeddings() -> Tuple[Dict[str, List[np.ndarray]], Dict[str, np.ndarray]]:
"""
Load reference embeddings for each dialect region from local wav files.
"""
# Check if embedding model is available (globally defined)
try:
if embed_model is None or embed_feature_extractor is None:
logger.warning("Embedding model missing; reference embeddings disabled.")
return {}, {}
except NameError:
# embed_model not defined - embedding model disabled
logger.debug("Embedding model not defined; reference embeddings disabled.")
return {}, {}
if not DIALECT_REF_DIR.exists():
logger.warning(f"Dialect reference directory not found: {DIALECT_REF_DIR}")
return {}, {}
embeddings: Dict[str, List[np.ndarray]] = defaultdict(list)
for wav_path in sorted(DIALECT_REF_DIR.glob("*.wav")):
region_name = _resolve_region_from_name(wav_path.stem)
if not region_name:
logger.debug(f"Could not resolve region for reference file {wav_path.name}")
continue
emb = embed_audio(str(wav_path))
if emb is not None:
embeddings[region_name].append(emb)
prototypes: Dict[str, np.ndarray] = {}
for region_name, vectors in embeddings.items():
if vectors:
prototypes[region_name] = np.mean(vectors, axis=0)
logger.info(f"Loaded {len(vectors)} reference embeddings for {region_name}")
if not prototypes:
logger.warning("No dialect reference prototypes were built.")
return embeddings, prototypes
# Embedding model disabled - reference embeddings not needed
DIALECT_REF_EMBEDDINGS: Dict[str, List[np.ndarray]] = {}
DIALECT_PROTOTYPES: Dict[str, np.ndarray] = {}
logger.debug("Embedding model disabled - skipping reference embeddings loading")
# =========================================
# ZERO-SHOT DIALECT CLASSIFIER
# =========================================
def cosine_similarity(vec_a: np.ndarray, vec_b: np.ndarray) -> float:
denom = (np.linalg.norm(vec_a) * np.linalg.norm(vec_b)) + 1e-10
return float(np.dot(vec_a, vec_b) / denom)
def predict_dialect(audio_path: str) -> Tuple[str, Dict[str, float]]:
"""
Predict dialect region using cosine similarity against reference prototypes.
"""
if not DIALECT_PROTOTYPES:
logger.warning("No dialect prototypes available; returning fallback prediction.")
return "Bilinmiyor", {}
user_embedding = embed_audio(audio_path)
if user_embedding is None:
return "Bilinmiyor", {}
scores: Dict[str, float] = {}
for region_name, prototype_vec in DIALECT_PROTOTYPES.items():
similarity = cosine_similarity(user_embedding, prototype_vec)
normalized = max(0.0, min(1.0, (similarity + 1) / 2))
scores[region_name] = round(normalized, 4)
if not scores:
return "Bilinmiyor", {}
predicted_region = max(scores, key=scores.get)
return predicted_region, scores
def generate_reply_text(region: str) -> str:
templates = {
"Karadeniz": "Aaa, sen demek Karadenizlisin! Hızlı ritim ve enerjik ton hemen belli ediyor kendini. 🌊",
"Doğu Anadolu": "Hmm, Doğu’dan bir hava aldım. Güçlü vurgular ve ağır ritim çok tanıdık. 🏔️",
"İç Anadolu": "Sende İç Anadolu’nun sakin ve net konuşması var gibi. Rahat ve dengeli. 🚜",
"Ege": "Ege rüzgarı gibi yumuşak tınlıyor sesin; huzur veren bir anlatım. 🌅",
"Akdeniz": "Akdeniz’in sıcaklığı ve enerjisi var sesinde, çok hareketli! ☀️",
"Marmara": "Oldukça dengeli ve şehirli bir ton; Marmara aksanı hissediliyor. 🌆",
"Güneydoğu Anadolu": "Güneydoğu’nun uzun vurguları ve sıcaklığı geliyor sesinden. 🔥",
}
if region in templates:
return templates[region]
if region and region != "Bilinmiyor":
return f"Sesinde {region} bölgesine benzeyen bir tını var. Çok hoş bir karışım yakalamışsın. 🙂"
return "Şive tahmin edemedim ama sesin oldukça ilgi çekici!"
def synthesize_elevenlabs(
text: str,
speaking_rate: Optional[float] = None,
pitch: Optional[float] = None
) -> Optional[str]:
"""
Convert reply text into speech using ElevenLabs.
"""
if not text:
return None
if not elevenlabs_client:
logger.warning("ElevenLabs client unavailable; cannot synthesize audio.")
return None
voice_settings: Dict[str, Any] = {
"stability": 0.4,
"similarity_boost": 0.8,
}
if speaking_rate is not None:
voice_settings["speaking_rate"] = speaking_rate
if pitch is not None:
voice_settings["pitch"] = pitch
try:
audio = elevenlabs_client.text_to_speech.convert(
voice_id=ELEVENLABS_VOICE_ID,
model_id=ELEVENLABS_MODEL_ID,
text=text,
voice_settings=voice_settings,
)
out_path = f"reply_{uuid4().hex}.wav"
save(audio, out_path)
return out_path
except Exception as e:
logger.error(f"ElevenLabs synthesis failed: {e}")
return None
# =========================================
# AUDIO PROCESSING
# =========================================
def process_audio(audio_data: np.ndarray, sample_rate: int) -> Tuple[np.ndarray, int]:
"""
Process audio: convert to mono, normalize, resample if needed.
Args:
audio_data: Audio signal as numpy array
sample_rate: Original sample rate
Returns:
Processed audio data and sample rate
"""
try:
# Convert stereo to mono if needed
if len(audio_data.shape) > 1:
audio_data = librosa.to_mono(audio_data)
logger.info("Converted stereo to mono")
# Resample to target rate if needed
if sample_rate != TARGET_SAMPLE_RATE:
audio_data = librosa.resample(
audio_data,
orig_sr=sample_rate,
target_sr=TARGET_SAMPLE_RATE
)
sample_rate = TARGET_SAMPLE_RATE
logger.info(f"Resampled to {TARGET_SAMPLE_RATE} Hz")
# Normalize audio
audio_data = librosa.util.normalize(audio_data)
return audio_data, sample_rate
except Exception as e:
logger.error(f"Error processing audio: {e}")
raise ValueError(f"Ses işleme hatası: {e}")
def validate_audio(audio_data: np.ndarray, sample_rate: int) -> None:
"""
Validate audio duration and quality.
Args:
audio_data: Audio signal
sample_rate: Sample rate
Raises:
ValueError: If audio is invalid
"""
duration = len(audio_data) / sample_rate
if duration < MIN_AUDIO_DURATION:
raise ValueError(
f"Ses süresi en az {MIN_AUDIO_DURATION} saniye olmalı. "
f"Mevcut süre: {duration:.2f} saniye."
)
if len(audio_data) == 0:
raise ValueError("Ses verisi boş.")
# =========================================
# ASR CORE
# =========================================
def run_asr(audio_data: np.ndarray, sample_rate: int) -> str:
"""
Run Whisper ASR on audio.
Args:
audio_data: Processed audio signal
sample_rate: Sample rate
Returns:
Transcription text
"""
try:
# Ensure audio is float32 (Whisper expects fp32 input)
audio_float = audio_data.astype(np.float32)
inputs = processor(
audio_float,
sampling_rate=sample_rate,
return_tensors="pt"
)
# Move to device and cast to target dtype (fp16 on GPU, fp32 on CPU)
input_features = inputs.input_features.to(device=DEVICE, dtype=DTYPE)
with torch.no_grad():
generated_ids = model.generate(
input_features,
max_length=400,
language="tr",
task="transcribe"
)
hypothesis = processor.batch_decode(
generated_ids,
skip_special_tokens=True
)[0]
logger.info(f"ASR output: {hypothesis}")
return hypothesis
except Exception as e:
logger.error(f"ASR error: {e}")
raise ValueError(f"Konuşma tanıma hatası: {e}")
# =========================================
# DIALECT ANALYSIS
# =========================================
def vowel_shift_score(transcription: str, profile: Dict[str, Any]) -> float:
"""
Score vowel shifts in transcription.
Enhanced scoring based on phonetic patterns.
Args:
transcription: ASR transcription
profile: Dialect profile
Returns:
Vowel shift score [0, 1]
"""
transcription_lower = transcription.lower()
shifts = profile["vowel_shifts"]
total_weight = sum(shifts.values())
if total_weight == 0:
return 0.0
score = 0.0
text_length = len(transcription_lower)
for shift_pattern, weight in shifts.items():
if "→" not in shift_pattern:
continue
source, target = shift_pattern.split("→")
# Count occurrences of target vowel/diphthong
# For elongated vowels (ee, oo, aa), look for repeated patterns
if len(target) > 1 and target[0] == target[1]:
# Look for elongated vowels
pattern = target[0] * 2
count = transcription_lower.count(pattern)
# Also check for common elongated patterns in Turkish
count += transcription_lower.count(target[0] + "ğ")
count += transcription_lower.count(target[0] + "y")
else:
count = transcription_lower.count(target)
# Normalize by text length
normalized_count = count / max(text_length, 1) * 100
score += normalized_count * weight
# Normalize by total weight
normalized_score = score / (total_weight * 10 + 1e-6)
return min(normalized_score, 1.0)
def marker_score(transcription: str, profile: Dict[str, Any]) -> float:
"""
Score lexical markers in transcription.
Args:
transcription: ASR transcription
profile: Dialect profile
Returns:
Marker score [0, 1]
"""
transcription_lower = transcription.lower()
markers = profile["markers"]
if not markers:
return 0.0
matches = sum(1 for marker in markers if marker in transcription_lower)
# Score based on proportion of markers found
score = matches / len(markers)
# Bonus for multiple occurrences
total_occurrences = sum(transcription_lower.count(marker) for marker in markers)
if total_occurrences > len(markers):
score = min(score * 1.2, 1.0)
return score
def prosody_score(
audio_data: np.ndarray,
sample_rate: int,
profile: Dict[str, Any]
) -> float:
"""
Analyze prosody: tempo, pitch characteristics.
Args:
audio_data: Audio signal
sample_rate: Sample rate
profile: Dialect profile
Returns:
Prosody score [0, 1]
"""
try:
# Normalize audio
audio_normalized = librosa.util.normalize(audio_data)
# Tempo analysis
tempo = float(librosa.beat.tempo(y=audio_normalized, sr=sample_rate)[0])
# Pitch analysis (fundamental frequency)
pitches, magnitudes = librosa.piptrack(
y=audio_normalized,
sr=sample_rate,
threshold=0.1
)
# Get pitch statistics
pitch_values = []
for t in range(pitches.shape[1]):
index = magnitudes[:, t].argmax()
pitch = pitches[index, t]
if pitch > 0:
pitch_values.append(pitch)
avg_pitch = np.mean(pitch_values) if pitch_values else 0.0
pitch_std = np.std(pitch_values) if len(pitch_values) > 1 else 0.0
# Score based on profile characteristics
prosody_type = profile["prosody"]
tempo_range = profile.get("tempo_range", (80, 120))
pitch_range_type = profile.get("pitch_range", "neutral")
# Tempo scoring
tempo_min, tempo_max = tempo_range
if tempo_min <= tempo <= tempo_max:
tempo_score = 1.0
else:
# Distance from range
if tempo < tempo_min:
tempo_score = max(0.0, tempo / tempo_min)
else:
tempo_score = max(0.0, 1.0 - (tempo - tempo_max) / tempo_max)
# Pitch scoring based on profile
pitch_score = 0.5 # default
if pitch_range_type == "high" or pitch_range_type == "high-oscillating":
if avg_pitch > 200:
pitch_score = 1.0
elif avg_pitch > 150:
pitch_score = 0.7
elif pitch_range_type == "low" or pitch_range_type == "low-elongated":
if avg_pitch < 150:
pitch_score = 1.0
elif avg_pitch < 200:
pitch_score = 0.7
else: # neutral
if 150 <= avg_pitch <= 250:
pitch_score = 1.0
# Oscillation scoring (for Karadeniz)
oscillation_score = 0.5
if "oscillating" in pitch_range_type or "inişli-çıkışlı" in prosody_type:
if pitch_std > 50:
oscillation_score = 1.0
elif pitch_std > 30:
oscillation_score = 0.7
# Combine scores
if "oscillating" in pitch_range_type or "inişli-çıkışlı" in prosody_type:
final_score = (tempo_score * 0.4 + pitch_score * 0.3 + oscillation_score * 0.3)
else:
final_score = (tempo_score * 0.6 + pitch_score * 0.4)
return min(final_score, 1.0)
except Exception as e:
logger.warning(f"Prosody analysis error: {e}")
return 0.5 # Default neutral score
def dialect_similarity(
transcription: str,
audio_data: np.ndarray,
sample_rate: int
) -> Tuple[Dict[str, float], List[Tuple[str, float]]]:
"""
Calculate dialect similarity scores for all regions.
Args:
transcription: ASR transcription
audio_data: Audio signal
sample_rate: Sample rate
Returns:
Dictionary of scores and sorted predictions
"""
scores: Dict[str, float] = {}
for region, profile in DIALECT_PROFILES.items():
try:
vowel_score = vowel_shift_score(transcription, profile)
marker_score_val = marker_score(transcription, profile)
prosody_score_val = prosody_score(audio_data, sample_rate, profile)
# Weighted combination
combined_score = (
vowel_score * VOWEL_SHIFT_WEIGHT +
marker_score_val * MARKER_WEIGHT +
prosody_score_val * PROSODY_WEIGHT
)
scores[region] = round(combined_score, 3)
logger.info(
f"{region}: vowel={vowel_score:.3f}, "
f"marker={marker_score_val:.3f}, "
f"prosody={prosody_score_val:.3f}, "
f"combined={combined_score:.3f}"
)
except Exception as e:
logger.error(f"Error calculating score for {region}: {e}")
scores[region] = 0.0
# Sort by score
sorted_predictions = sorted(
scores.items(),
key=lambda x: x[1],
reverse=True
)
return scores, sorted_predictions
# =========================================
# VISUALIZATION
# =========================================
def plot_region_heatmap(
scores: Dict[str, float],
highlight_region: Optional[str] = None
) -> go.Figure:
"""
Create an interactive choropleth-style region heatmap for Türkiye dialect scores.
"""
try:
if not scores:
raise ValueError("Score verisi yok")
df = pd.DataFrame({
"region_name": list(scores.keys()),
"score": list(scores.values()),
})
min_score = float(df["score"].min())
max_score = float(df["score"].max())
if min_score == max_score:
max_score = min_score + 0.01
fig = px.choropleth_mapbox(
df,
geojson=TURKEY_REGIONS_GEOJSON,
locations="region_name",
featureidkey="properties.name",
color="score",
color_continuous_scale="OrRd",
range_color=(min_score, max_score),
mapbox_style="carto-positron",
zoom=4.5,
center={"lat": 39.0, "lon": 35.0},
opacity=0.7,
labels={"score": "Benzerlik"},
)
fig.update_traces(marker_line_width=0.5, marker_line_color="white")
if highlight_region and highlight_region in df["region_name"].values:
highlight_df = df[df["region_name"] == highlight_region]
fig.add_choroplethmapbox(
geojson=TURKEY_REGIONS_GEOJSON,
locations=highlight_df["region_name"],
z=np.ones(len(highlight_df)),
featureidkey="properties.name",
colorscale=[[0, "rgba(0,0,0,0)"], [1, "rgba(0,0,0,0)"]],
showscale=False,
marker_opacity=0,
marker_line_width=3,
marker_line_color="black",
hovertext=highlight_df["region_name"],
name="Tahmin",
)
fig.add_annotation(
text=f"🗣 Tahmin: {highlight_region}",
x=0.5,
y=0.02,
xref="paper",
yref="paper",
showarrow=False,
bgcolor="white",
bordercolor="black",
borderwidth=1,
font=dict(size=14),
)
fig.update_layout(
margin=dict(l=10, r=10, t=40, b=10),
height=600,
coloraxis_colorbar=dict(title="Benzerlik"),
)
return fig
except Exception as e:
logger.error(f"Error creating heatmap: {e}")
fig = go.Figure()
fig.update_layout(
title="Harita yüklenemedi",
height=600
)
return fig
# =========================================
# MAIN PIPELINE
# =========================================
def analyze_and_reply(
audio_path: Optional[str]
) -> Tuple[str, str, str, Optional[str], go.Figure]:
"""
Full processing pipeline: audio → ASR → dialect analysis → TTS reply.
"""
def build_empty_fig(title: str = "Harita yüklenemedi") -> go.Figure:
fig = go.Figure()
fig.update_layout(title=title, height=600)
return fig
logger.info(f"Received audio_path: {audio_path}")
if audio_path is None:
logger.warning("Audio input is None.")
empty_fig = build_empty_fig()
return "Ses alınamadı. Lütfen tekrar deneyin.", "", "", None, empty_fig
# Check if file exists
if not os.path.exists(audio_path):
logger.error(f"Audio file does not exist: {audio_path}")
empty_fig = build_empty_fig()
return f"Ses dosyası bulunamadı: {audio_path}", "", "", None, empty_fig
try:
logger.info(f"Reading audio file: {audio_path}")
audio_data, sample_rate = sf.read(audio_path)
logger.info(f"Audio file read successfully. Duration: {len(audio_data)/sample_rate:.2f}s, Sample rate: {sample_rate}Hz")
if audio_data.ndim > 1:
audio_data = audio_data.T
audio_data = librosa.to_mono(audio_data)
audio_data = np.asarray(audio_data, dtype=np.float32)
except Exception as e:
logger.error(f"Error reading audio file: {e}")
empty_fig = build_empty_fig()
return f"Ses dosyası okunamadı: {e}", "", "", None, empty_fig
try:
processed_audio, processed_sr = process_audio(audio_data, sample_rate)
validate_audio(processed_audio, processed_sr)
except ValueError as e:
logger.error(f"Audio validation error: {e}")
empty_fig = build_empty_fig()
return str(e), "", "", None, empty_fig
try:
transcript = run_asr(processed_audio, processed_sr)
logger.info(f"ASR transcript: {transcript}")
except ValueError as e:
logger.error(f"ASR error: {e}")
empty_fig = build_empty_fig()
return str(e), "", "", None, empty_fig
# Use transcription-based dialect similarity analysis
similarity_scores, sorted_predictions = dialect_similarity(
transcript, processed_audio, processed_sr
)
# Also try embedding-based prediction as fallback
embedding_region, embedding_scores = predict_dialect(audio_path)
# Always use transcription-based prediction if available (it should always work)
if similarity_scores and sorted_predictions and len(sorted_predictions) > 0:
# Use transcription-based prediction
predicted_region = sorted_predictions[0][0]
scores = similarity_scores
top_score = sorted_predictions[0][1]
logger.info(f"Using transcription-based prediction: {predicted_region} (score: {top_score:.4f})")
# Log top 3 predictions for debugging
if len(sorted_predictions) >= 3:
logger.info(f"Top 3 predictions: {[(r, f'{s:.4f}') for r, s in sorted_predictions[:3]]}")
elif embedding_scores and embedding_region != "Bilinmiyor" and max(embedding_scores.values()) > 0.01:
# Fallback to embedding-based
predicted_region = embedding_region
scores = embedding_scores
logger.info(f"Using embedding-based prediction: {predicted_region} (score: {max(embedding_scores.values()):.4f})")
else:
# Last resort: ensure we always return a region
if similarity_scores and sorted_predictions and len(sorted_predictions) > 0:
predicted_region = sorted_predictions[0][0]
scores = similarity_scores
logger.warning(f"Using transcription-based with low scores: {predicted_region} (score: {sorted_predictions[0][1]:.4f})")
elif similarity_scores:
# Use first region from scores even if sorted_predictions is empty
predicted_region = max(similarity_scores, key=similarity_scores.get)
scores = similarity_scores
logger.warning(f"Using first region from scores: {predicted_region}")
else:
# Absolute last resort: use first region from DIALECT_PROFILES
predicted_region = list(DIALECT_PROFILES.keys())[0] if DIALECT_PROFILES else "Bilinmiyor"
scores = {region: 0.1 for region in DIALECT_PROFILES.keys()} if DIALECT_PROFILES else {}
logger.error(f"All prediction methods failed, using fallback: {predicted_region}")
reply_text = generate_reply_text(predicted_region)
reply_audio_path = synthesize_elevenlabs(reply_text) or None
heatmap_fig = plot_region_heatmap(scores, highlight_region=predicted_region if scores else None)
return (
transcript,
predicted_region,
reply_text,
reply_audio_path,
heatmap_fig
)
# =========================================
# UI — Ultra Modern Apple Glassmorphism Design
# =========================================
CSS = """
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
@keyframes float {
0%, 100% { transform: translateY(0px); }
50% { transform: translateY(-10px); }
}
@keyframes shimmer {
0% { background-position: -1000px 0; }
100% { background-position: 1000px 0; }
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.7; }
}
body {
background:
radial-gradient(circle at 20% 50%, rgba(120, 119, 198, 0.15) 0%, transparent 50%),
radial-gradient(circle at 80% 80%, rgba(255, 119, 198, 0.1) 0%, transparent 50%),
radial-gradient(circle at 40% 20%, rgba(99, 102, 241, 0.1) 0%, transparent 50%),
linear-gradient(135deg, #F8F9FA 0%, #E9ECEF 50%, #F1F3F5 100%) !important;
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", "Segoe UI", sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
min-height: 100vh;
position: relative;
overflow-x: hidden;
}
body::before {
content: '';
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background:
radial-gradient(circle at 20% 30%, rgba(99, 102, 241, 0.08) 0%, transparent 50%),
radial-gradient(circle at 80% 70%, rgba(168, 85, 247, 0.06) 0%, transparent 50%);
pointer-events: none;
z-index: 0;
}
.gradio-container {
background: transparent !important;
max-width: 1500px !important;
margin: 0 auto !important;
padding: 60px 30px !important;
position: relative;
z-index: 1;
}
h1 {
font-weight: 800 !important;
letter-spacing: -2.5px !important;
color: #1D1D1F !important;
margin: 0 !important;
background: linear-gradient(135deg, #1D1D1F 0%, #4A5568 50%, #1D1D1F 100%) !important;
background-size: 200% auto !important;
-webkit-background-clip: text !important;
-webkit-text-fill-color: #1D1D1F !important;
background-clip: text !important;
animation: shimmer 3s linear infinite !important;
opacity: 1 !important;
z-index: 10 !important;
position: relative !important;
visibility: visible !important;
}
.card {
background: rgba(255, 255, 255, 0.85) !important;
backdrop-filter: blur(30px) saturate(180%) !important;
-webkit-backdrop-filter: blur(30px) saturate(180%) !important;
padding: 28px !important;
border-radius: 20px !important;
border: 1px solid rgba(0, 0, 0, 0.08) !important;
margin-bottom: 20px !important;
box-shadow:
0 8px 32px rgba(0, 0, 0, 0.06),
0 4px 16px rgba(0, 0, 0, 0.04),
0 2px 8px rgba(0, 0, 0, 0.03),
inset 0 1px 0 rgba(255, 255, 255, 0.9) !important;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
position: relative;
overflow: hidden;
}
.card::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
transition: left 0.5s;
}
.card:hover::before {
left: 100%;
}
.card:hover {
transform: translateY(-4px) scale(1.01) !important;
box-shadow:
0 28px 80px rgba(0, 0, 0, 0.12),
0 12px 32px rgba(0, 0, 0, 0.08),
0 4px 12px rgba(0, 0, 0, 0.06),
inset 0 1px 0 rgba(255, 255, 255, 1),
inset 0 -1px 0 rgba(255, 255, 255, 0.6) !important;
border-color: rgba(255, 255, 255, 1) !important;
}
.label {
font-weight: 700 !important;
color: #1D1D1F !important;
margin-bottom: 14px !important;
font-size: 15px !important;
letter-spacing: -0.3px !important;
text-transform: uppercase;
font-size: 12px;
opacity: 0.8;
}
.textbox textarea,
.textbox input,
.dropdown select {
background: rgba(255, 255, 255, 0.95) !important;
backdrop-filter: blur(20px) saturate(180%) !important;
-webkit-backdrop-filter: blur(20px) saturate(180%) !important;
border: 1.5px solid rgba(0, 0, 0, 0.06) !important;
border-radius: 16px !important;
color: #1D1D1F !important;
padding: 16px 20px !important;
font-size: 15px !important;
font-weight: 500 !important;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
box-shadow:
0 4px 12px rgba(0, 0, 0, 0.04),
inset 0 1px 2px rgba(0, 0, 0, 0.02) !important;
}
.textbox:focus-within,
.dropdown:focus-within {
border-color: #007AFF !important;
box-shadow:
0 8px 24px rgba(0, 122, 255, 0.2),
0 4px 12px rgba(0, 122, 255, 0.15),
inset 0 1px 2px rgba(0, 122, 255, 0.1) !important;
transform: translateY(-1px);
}
button.primary {
background: linear-gradient(135deg, #007AFF 0%, #0051D5 50%, #007AFF 100%) !important;
background-size: 200% auto !important;
border: none !important;
border-radius: 18px !important;
font-weight: 700 !important;
padding: 18px 40px !important;
font-size: 17px !important;
color: white !important;
letter-spacing: -0.2px !important;
box-shadow:
0 8px 24px rgba(0, 122, 255, 0.4),
0 4px 12px rgba(0, 122, 255, 0.3),
inset 0 1px 0 rgba(255, 255, 255, 0.3),
inset 0 -1px 0 rgba(0, 0, 0, 0.1) !important;
transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1) !important;
cursor: pointer !important;
position: relative;
overflow: hidden;
text-transform: none !important;
}
button.primary::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
transition: left 0.5s;
}
button.primary:hover::before {
left: 100%;
}
button.primary:hover {
transform: translateY(-3px) scale(1.02) !important;
box-shadow:
0 12px 32px rgba(0, 122, 255, 0.5),
0 6px 16px rgba(0, 122, 255, 0.4),
inset 0 1px 0 rgba(255, 255, 255, 0.4),
inset 0 -1px 0 rgba(0, 0, 0, 0.15) !important;
background-position: right center !important;
}
button.primary:active {
transform: translateY(-1px) scale(1.01) !important;
box-shadow:
0 4px 16px rgba(0, 122, 255, 0.4),
inset 0 1px 0 rgba(255, 255, 255, 0.2) !important;
}
.json {
font-family: "SF Mono", "Monaco", "Menlo", "Courier New", monospace !important;
font-size: 13px !important;
background: rgba(248, 249, 250, 0.9) !important;
backdrop-filter: blur(20px) saturate(180%) !important;
-webkit-backdrop-filter: blur(20px) saturate(180%) !important;
border: 1px solid rgba(0, 0, 0, 0.05) !important;
border-radius: 16px !important;
padding: 24px !important;
color: #1D1D1F !important;
line-height: 1.7 !important;
box-shadow:
inset 0 2px 8px rgba(0, 0, 0, 0.03),
inset 0 1px 2px rgba(0, 0, 0, 0.02) !important;
}
.markdown {
color: #1D1D1F !important;
}
.markdown * {
visibility: visible !important;
opacity: 1 !important;
display: block !important;
}
.markdown div {
display: block !important;
visibility: visible !important;
opacity: 1 !important;
color: inherit !important;
}
.markdown h1, .header-markdown h1, .main-title {
color: #1D1D1F !important;
margin-bottom: 16px !important;
margin-top: 50px !important;
font-size: 3.5rem !important;
font-weight: 800 !important;
letter-spacing: -2px !important;
line-height: 1.2 !important;
text-shadow: 0 2px 8px rgba(0,0,0,0.1) !important;
-webkit-text-fill-color: #1D1D1F !important;
background: none !important;
background-image: none !important;
opacity: 1 !important;
z-index: 10 !important;
position: relative !important;
visibility: visible !important;
display: block !important;
text-align: center !important;
}
.header-markdown {
text-align: center !important;
}
.header-markdown p {
color: #6E6E73 !important;
font-size: 1.15rem !important;
margin-top: 8px !important;
opacity: 0.9 !important;
}
.markdown h1 span {
color: #1D1D1F !important;
-webkit-text-fill-color: #1D1D1F !important;
background: none !important;
display: inline-block !important;
}
.markdown p {
display: block !important;
visibility: visible !important;
opacity: 1 !important;
color: #6E6E73 !important;
margin: 0 !important;
}
.instruction-text {
display: block !important;
visibility: visible !important;
text-align: center !important;
margin-top: -20px !important;
margin-bottom: 40px !important;
color: #6E6E73 !important;
font-size: 1.1rem !important;
opacity: 0.9 !important;
padding: 0 20px !important;
}
.instruction-text p {
display: block !important;
visibility: visible !important;
opacity: 1 !important;
color: #6E6E73 !important;
margin: 0 !important;
}
.header-container {
display: block !important;
visibility: visible !important;
opacity: 1 !important;
}
.header-container h1 {
display: block !important;
visibility: visible !important;
opacity: 1 !important;
}
.header-container p {
display: block !important;
visibility: visible !important;
opacity: 1 !important;
}
/* HTML component styles */
.html-component, .html-component * {
display: block !important;
visibility: visible !important;
opacity: 1 !important;
}
.html-component h1, .html-component .main-title {
color: #1D1D1F !important;
-webkit-text-fill-color: #1D1D1F !important;
background: none !important;
background-image: none !important;
display: block !important;
}
.html-component p {
display: block !important;
visibility: visible !important;
color: #6E6E73 !important;
}
.markdown p {
color: #6E6E73;
opacity: 0.95;
font-size: 1.15rem;
font-weight: 400;
line-height: 1.6;
letter-spacing: -0.2px;
}
.audio-component {
background: rgba(255, 255, 255, 0.95) !important;
backdrop-filter: blur(30px) saturate(200%) !important;
-webkit-backdrop-filter: blur(30px) saturate(200%) !important;
border-radius: 20px !important;
border: 1.5px solid rgba(255, 255, 255, 0.8) !important;
padding: 20px !important;
box-shadow:
0 8px 24px rgba(0, 0, 0, 0.06),
0 4px 12px rgba(0, 0, 0, 0.04),
inset 0 1px 0 rgba(255, 255, 255, 0.9) !important;
transition: all 0.3s ease !important;
}
.audio-component:hover {
box-shadow:
0 12px 32px rgba(0, 0, 0, 0.08),
0 6px 16px rgba(0, 0, 0, 0.06),
inset 0 1px 0 rgba(255, 255, 255, 1) !important;
}
/* Ultra smooth scrollbar */
::-webkit-scrollbar {
width: 10px;
height: 10px;
}
::-webkit-scrollbar-track {
background: rgba(0, 0, 0, 0.02);
border-radius: 10px;
}
::-webkit-scrollbar-thumb {
background: linear-gradient(135deg, rgba(0, 122, 255, 0.3), rgba(0, 81, 213, 0.4));
border-radius: 10px;
border: 2px solid transparent;
background-clip: padding-box;
}
::-webkit-scrollbar-thumb:hover {
background: linear-gradient(135deg, rgba(0, 122, 255, 0.5), rgba(0, 81, 213, 0.6));
background-clip: padding-box;
}
/* Loading animation */
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
/* Enhanced focus states */
*:focus-visible {
outline: 2px solid #007AFF;
outline-offset: 2px;
border-radius: 4px;
}
"""
def build_ui() -> gr.Blocks:
"""
Build Gradio UI with Apple minimal white + smooth glass design.
Returns:
Gradio Blocks interface
"""
with gr.Blocks(
css=CSS,
fill_height=True,
theme=gr.themes.Soft()
) as demo:
gr.Markdown(
"""
# 🇹🇷 Dialect Intelligence Engine
Powered by Meta Omnilingual ASR & Whisper Large-v3
""",
elem_classes="header-markdown"
)
gr.Markdown(
"""
Mikrofona bas, doğal bir şekilde konuş. Sistem şiveni analiz edip seni haritada işaretlesin ve AI sesiyle cevap versin.
""",
elem_classes="instruction-text"
)
with gr.Row(equal_height=False):
with gr.Column(scale=1, min_width=400):
audio_input = gr.Audio(
sources=["microphone", "upload"],
type="filepath",
label="🎤 Mikrofona basın, konuşun, kaydı durdurun",
show_label=True,
interactive=True,
elem_classes="card"
)
analyze_button = gr.Button(
"🔍 Analiz Et ve Şive Tahmini Yap",
variant="primary",
elem_classes="primary",
visible=True,
scale=1
)
gr.Markdown(
"📝 Ses kaydını tamamladıktan sonra butona tıklayın",
elem_classes="instruction-text"
)
with gr.Column(scale=2, min_width=600):
transcript_output = gr.Textbox(
label="Transcript",
lines=4,
interactive=False,
placeholder="Konuşmanı bekliyorum...",
elem_classes="card"
)
with gr.Row():
predicted_dialect = gr.Textbox(
label="Tahmin Edilen Bölge",
interactive=False,
lines=2,
elem_classes="card"
)
reply_text_output = gr.Textbox(
label="Model Cevabı (Metin)",
interactive=False,
lines=2,
elem_classes="card"
)
reply_audio_output = gr.Audio(
label="Model Cevabı (Ses)",
type="filepath",
interactive=False,
autoplay=True,
elem_classes="card"
)
region_map = gr.Plot(
label="Bölgesel Harita Isı Dağılımı",
elem_classes="card"
)
def build_empty_fig_ui():
"""Build empty figure for UI"""
fig = go.Figure()
fig.update_layout(title="Harita yüklenemedi", height=600)
return fig
def analyze_and_reply_with_autoplay(audio_path):
"""Wrapper to ensure audio autoplays after generation"""
logger.info(f"analyze_and_reply_with_autoplay called with audio_path: {audio_path}")
if audio_path is None:
logger.warning("audio_path is None in wrapper")
empty_fig = build_empty_fig_ui()
return "", "", "", None, empty_fig
result = analyze_and_reply(audio_path)
# Return result - Gradio will handle autoplay if autoplay=True is set
return result
# Both button click and audio change trigger analysis
analyze_button.click(
fn=analyze_and_reply_with_autoplay,
inputs=audio_input,
outputs=[
transcript_output,
predicted_dialect,
reply_text_output,
reply_audio_output,
region_map
]
)
# Also trigger on change (for file uploads and when recording stops)
audio_input.change(
fn=analyze_and_reply_with_autoplay,
inputs=audio_input,
outputs=[
transcript_output,
predicted_dialect,
reply_text_output,
reply_audio_output,
region_map
]
)
# Add JavaScript for autoplay
demo.load(
fn=None,
js="""
function() {
// Auto-play audio when it's updated
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
mutation.addedNodes.forEach(function(node) {
if (node.nodeType === 1) {
const audio = node.querySelector('audio');
if (audio && audio.src && !audio.hasAttribute('data-autoplayed')) {
audio.setAttribute('data-autoplayed', 'true');
audio.play().catch(e => console.log('Autoplay prevented:', e));
}
}
});
});
});
observer.observe(document.body, {
childList: true,
subtree: true
});
}
"""
)
# Auto-play audio when it's generated using JavaScript callback
reply_audio_output.change(
fn=None,
inputs=None,
outputs=None,
js="""
function() {
setTimeout(function() {
// Find the audio element by looking for the reply audio component
const labels = Array.from(document.querySelectorAll('label'));
const replyLabel = labels.find(label =>
label.textContent && label.textContent.includes('Model Cevabı (Ses)')
);
if (replyLabel) {
const audioContainer = replyLabel.closest('.card') || replyLabel.parentElement;
const audioElement = audioContainer ? audioContainer.querySelector('audio') : null;
if (audioElement && audioElement.src) {
// Reset and play
audioElement.currentTime = 0;
const playPromise = audioElement.play();
if (playPromise !== undefined) {
playPromise.catch(function(error) {
console.log('Autoplay prevented by browser:', error);
});
}
}
}
}, 800); // Wait for audio to be fully loaded
return [];
}
"""
)
return demo
# =========================================
# MAIN
# =========================================
demo = build_ui()
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
ssr_mode=False # Fix for HF Spaces microphone bug
)
|