yunuseduran commited on
Commit
7548acc
·
verified ·
1 Parent(s): 288adc7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -66
app.py CHANGED
@@ -6,107 +6,71 @@ import shutil
6
  import tempfile
7
  import uuid
8
  import torch
 
9
 
10
  # Whisper modeli yükleme
11
- MODEL_SIZE = os.getenv("MODEL_SIZE", "base")
12
  device = "cuda" if torch.cuda.is_available() else "cpu"
13
- print(f"Kullanılan cihaz: {device}") # Cihaz bilgisi
14
  yerel_model = whisper.load_model(MODEL_SIZE).to(device)
15
 
16
  # Kısıtlamalar
17
- MAX_DOSYA_BOYUTU_MB = int(os.getenv("MAX_FILE_SIZE_MB", 50)) # 25MB sınırı
18
  DESTEKLENEN_FORMATLAR = {"mp3", "wav", "m4a", "ogg"}
19
 
20
- def dosya_sil(dosya_yolu, deneme=3, bekleme=1):
21
- """
22
- Ses dosyasını güvenli bir şekilde silme fonksiyonu.
23
- """
24
- for i in range(deneme):
25
- try:
26
- if dosya_yolu and os.path.exists(dosya_yolu):
27
- os.remove(dosya_yolu)
28
- print(f"Dosya başarıyla silindi: {dosya_yolu}")
29
- return True
30
- except Exception as e:
31
- print(f"Dosya silme hatası (Deneme {i+1}/{deneme}): {e}")
32
- return False
33
-
34
- def metin_formatla(metin: str) -> str:
35
- """Metni okunaklı hale getirme"""
36
- noktalama_isaretleri = [".", "?", "!", "。", ".", "?", "!"]
37
- for isaret in noktalama_isaretleri:
38
- metin = metin.replace(isaret, isaret + "\n")
39
- return "\n".join(filter(bool, metin.split("\n")))
40
 
41
  async def ses_cozasync(ses_dosyasi, dil):
42
- """
43
- Ses kaydını asenkron olarak yazıya döken fonksiyon
44
- """
45
  return await ses_isle_ve_coz(ses_dosyasi, dil)
46
 
47
  async def ses_isle_ve_coz(ses_yolu, dil):
48
- """
49
- Ses dosyasını işleyip yazıya dökme
50
- """
51
  if not ses_yolu or not os.path.exists(ses_yolu):
52
  return "", "❌ Ses dosyası yüklenmedi."
53
 
54
- dosya_uzantisi = os.path.splitext(ses_yolu)[-1].lower().lstrip(".")
55
- if dosya_uzantisi not in DESTEKLENEN_FORMATLAR:
56
- return "", f"❌ Desteklenen formatlar: {', '.join(DESTEKLENEN_FORMATLAR)} (Mevcut: {dosya_uzantisi})"
 
 
 
57
 
58
- gecici_ses_yolu = os.path.join(tempfile.gettempdir(), f"{uuid.uuid4()}.{dosya_uzantisi}")
59
- shutil.copy(ses_yolu, gecici_ses_yolu)
60
-
61
  try:
62
- dosya_boyutu_mb = os.path.getsize(gecici_ses_yolu) / (1024 * 1024)
63
- if dosya_boyutu_mb > MAX_DOSYA_BOYUTU_MB:
64
- dosya_sil(gecici_ses_yolu)
65
- return "", f"❌ Dosya boyutu sınırı {MAX_DOSYA_BOYUTU_MB} MB (Mevcut: {dosya_boyutu_mb:.2f} MB)"
66
-
67
  metin = await ses_yazıya_dok(gecici_ses_yolu, dil)
68
- duzenlenmis_metin = metin_formatla(metin)
69
- return duzenlenmis_metin, "✅ Yazıya dökme tamamlandı."
70
-
71
  except Exception as e:
72
  return "", f"⚠️ Hata oluştu: {str(e)}"
73
-
74
  finally:
75
- if gecici_ses_yolu and os.path.exists(gecici_ses_yolu):
76
- dosya_sil(gecici_ses_yolu)
77
 
78
  async def ses_yazıya_dok(ses_yolu, dil):
79
- """
80
- Whisper kullanarak sesi yazıya döken fonksiyon
81
- """
82
- ayarlar = {"Türkçe": {"language": "tr", "temperature": 0.0, "beam_size": 5, "best_of": 5}}
83
- secilen_ayar = ayarlar.get(dil, ayarlar["Türkçe"])
84
-
85
  sonuc = await asyncio.to_thread(
86
  yerel_model.transcribe,
87
  ses_yolu,
88
- language=secilen_ayar["language"],
89
- temperature=secilen_ayar["temperature"],
90
- beam_size=secilen_ayar["beam_size"],
91
- fp16=False
92
  )
93
  return sonuc["text"]
94
 
95
  with gr.Blocks() as uygulama:
96
  gr.Markdown("## 🎤 Türkçe Ses Kayıtlarını Yazıya Dökme Aracı")
97
- gr.Markdown("""
98
- Ses kaydı yükleyin veya mikrofon ile kaydedin. **25MB'tan büyük dosyalar desteklenmez.**
99
- """)
100
-
101
- with gr.Row():
102
- ses_girdisi = gr.Audio(label="Ses kaydı yükleyin veya kaydedin", type="filepath")
103
- with gr.Row():
104
- dil_girdisi = gr.Radio(choices=["Türkçe"], label="Dil", value="Türkçe")
105
 
 
 
106
  cevir_buton = gr.Button("Çevir")
107
  durum_yazisi = gr.Textbox(label="Durum", interactive=False)
108
- with gr.Row():
109
- sonuc_metin = gr.Textbox(label="Çıktı")
110
 
111
  cevir_buton.click(fn=ses_isle_ve_coz, inputs=[ses_girdisi, dil_girdisi], outputs=[sonuc_metin, durum_yazisi])
112
 
 
6
  import tempfile
7
  import uuid
8
  import torch
9
+ import subprocess
10
 
11
  # Whisper modeli yükleme
12
+ MODEL_SIZE = os.getenv("MODEL_SIZE", "base") # Daha hızlı model seçildi
13
  device = "cuda" if torch.cuda.is_available() else "cpu"
 
14
  yerel_model = whisper.load_model(MODEL_SIZE).to(device)
15
 
16
  # Kısıtlamalar
17
+ MAX_DOSYA_BOYUTU_MB = int(os.getenv("MAX_FILE_SIZE_MB", 50)) # 50MB sınırı
18
  DESTEKLENEN_FORMATLAR = {"mp3", "wav", "m4a", "ogg"}
19
 
20
+ def ses_dosyasini_donustur(girdi_yolu, cikti_yolu):
21
+ """Ses dosyasını 16kHz mono formata çevirir."""
22
+ try:
23
+ subprocess.run([
24
+ "ffmpeg", "-i", girdi_yolu, "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", cikti_yolu
25
+ ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
26
+ return cikti_yolu
27
+ except Exception as e:
28
+ print(f"Ses dönüştürme hatası: {e}")
29
+ return girdi_yolu
 
 
 
 
 
 
 
 
 
 
30
 
31
  async def ses_cozasync(ses_dosyasi, dil):
 
 
 
32
  return await ses_isle_ve_coz(ses_dosyasi, dil)
33
 
34
  async def ses_isle_ve_coz(ses_yolu, dil):
 
 
 
35
  if not ses_yolu or not os.path.exists(ses_yolu):
36
  return "", "❌ Ses dosyası yüklenmedi."
37
 
38
+ dosya_boyutu_mb = os.path.getsize(ses_yolu) / (1024 * 1024)
39
+ if dosya_boyutu_mb > MAX_DOSYA_BOYUTU_MB:
40
+ return "", f"❌ Dosya boyutu sınırı {MAX_DOSYA_BOYUTU_MB} MB (Mevcut: {dosya_boyutu_mb:.2f} MB)"
41
+
42
+ gecici_ses_yolu = os.path.join(tempfile.gettempdir(), f"{uuid.uuid4()}.wav")
43
+ ses_dosyasini_donustur(ses_yolu, gecici_ses_yolu)
44
 
 
 
 
45
  try:
 
 
 
 
 
46
  metin = await ses_yazıya_dok(gecici_ses_yolu, dil)
47
+ return metin, "✅ Yazıya dökme tamamlandı."
 
 
48
  except Exception as e:
49
  return "", f"⚠️ Hata oluştu: {str(e)}"
 
50
  finally:
51
+ if os.path.exists(gecici_ses_yolu):
52
+ os.remove(gecici_ses_yolu)
53
 
54
  async def ses_yazıya_dok(ses_yolu, dil):
 
 
 
 
 
 
55
  sonuc = await asyncio.to_thread(
56
  yerel_model.transcribe,
57
  ses_yolu,
58
+ language="tr",
59
+ temperature=0.0,
60
+ beam_size=5,
61
+ fp16=True if device == "cuda" else False
62
  )
63
  return sonuc["text"]
64
 
65
  with gr.Blocks() as uygulama:
66
  gr.Markdown("## 🎤 Türkçe Ses Kayıtlarını Yazıya Dökme Aracı")
67
+ gr.Markdown("Ses kaydı yükleyin veya mikrofon ile kaydedin. **50MB'a kadar dosyalar desteklenir.**")
 
 
 
 
 
 
 
68
 
69
+ ses_girdisi = gr.Audio(label="Ses kaydı yükleyin veya kaydedin", type="filepath")
70
+ dil_girdisi = gr.Radio(choices=["Türkçe"], label="Dil", value="Türkçe")
71
  cevir_buton = gr.Button("Çevir")
72
  durum_yazisi = gr.Textbox(label="Durum", interactive=False)
73
+ sonuc_metin = gr.Textbox(label="Çıktı")
 
74
 
75
  cevir_buton.click(fn=ses_isle_ve_coz, inputs=[ses_girdisi, dil_girdisi], outputs=[sonuc_metin, durum_yazisi])
76