Jedi09 commited on
Commit
b11923b
·
verified ·
1 Parent(s): d37e425

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -89
app.py CHANGED
@@ -9,106 +9,95 @@ from faster_whisper import WhisperModel
9
  import tempfile
10
  import time
11
  import os
 
12
  # import requests # Artık gerek yok
13
- from transformers import pipeline
14
- import torch
15
 
16
  # ==================== CONFIG & MODELS ====================
17
 
18
- # 1. WHISPER MODEL (Ses Deşifre)
19
  MODEL_SIZE = "medium"
20
  model = None
21
 
22
  try:
23
- print(f" Whisper {MODEL_SIZE} modeli yükleniyor...")
24
  model = WhisperModel(MODEL_SIZE, device="cpu", compute_type="int8")
25
  print("✅ Whisper Modeli Hazır!")
26
  except Exception as e:
27
  print(f"❌ Whisper Yükleme Hatası: {e}")
28
  model = None
29
 
30
- # 2. LOCAL AI PIPELINES (Cache)
31
- summarizer_pipe = None
32
- translator_pipe = None
33
-
34
- def load_summarizer():
35
- global summarizer_pipe
36
- if summarizer_pipe is None:
37
- print("📥 Özetleme Modeli (mT5-Small) yükleniyor...")
38
- device = "cpu" # GPU varsa 0 yapabilirsiniz
39
- summarizer_pipe = pipeline("summarization", model="ozcangundes/mt5-small-turkish-summarization", device=-1)
40
- print("✅ Özetleme Modeli Hazır!")
41
- return summarizer_pipe
42
-
43
- def load_translator():
44
- global translator_pipe
45
- if translator_pipe is None:
46
- print("📥 Çeviri Modeli (NLLB-1.3B) yükleniyor... (Bu biraz zaman alabilir)")
47
- # Daha büyük ve kaliteli model: 1.3B
48
- translator_pipe = pipeline("translation", model="facebook/nllb-200-distilled-1.3B", device=-1)
49
- print("✅ Çeviri Modeli Hazır!")
50
- return translator_pipe
51
-
52
- # ==================== AI FUNCTIONS (LOCAL) ====================
53
-
54
- def summarize_locally(text: str, progress=gr.Progress()) -> str:
55
- """Yerel model (mT5) ile özetleme."""
56
- if not text or "⚠️" in text: return "⚠️ Önce geçerli bir metin oluşturun."
57
 
58
- clean_text = text.split("───────────────────────────────────")[0].strip()
59
- if len(clean_text) < 50: return "⚠️ Metin özetlemek için çok kısa."
60
 
 
 
 
 
 
 
 
 
 
61
  try:
62
- progress(0.2, desc="Özetleme modeli yükleniyor...")
63
- pipe = load_summarizer()
64
-
65
- progress(0.5, desc="Metin özetleniyor...")
66
- # Uyarıları önlemek için parametreler düzeltildi
67
- # max_length yerine max_new_tokens kullanıyoruz
68
- result = pipe(clean_text, max_new_tokens=128, min_length=10, do_sample=False)
69
 
70
- return result[0]['summary_text']
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
  except Exception as e:
73
- return f"❌ Özetleme Hatası: {str(e)}"
 
 
 
 
 
 
 
 
 
 
74
 
75
- def translate_locally(text: str, target_language: str, progress=gr.Progress()) -> str:
76
- """Yerel model (NLLB) ile çeviri."""
77
  if not text or "⚠️" in text: return "⚠️ Çevrilecek metin yok."
78
 
79
  clean_text = text.split("───────────────────────────────────")[0].strip()
80
 
81
- # NLLB Dil Kodları
82
- lang_map = {
83
- "İngilizce": "eng_Latn",
84
- "Almanca": "deu_Latn",
85
- "Fransızca": "fra_Latn",
86
- "Türkçe": "tur_Latn"
87
- }
88
- src_lang = "tur_Latn" # Varsayılan giriş Türkçe
89
- tgt_lang = lang_map.get(target_language, "eng_Latn")
90
 
91
- try:
92
- progress(0.2, desc="Çeviri modeli yükleniyor...")
93
- pipe = load_translator()
94
-
95
- progress(0.5, desc=f"Çeviriliyor ({target_language})...")
96
- # NLLB pipeline kullanımı: src_lang ve tgt_lang belirtilmeli
97
- # Tekrarı önlemek için paramatreler eklendi
98
- result = pipe(
99
- clean_text,
100
- src_lang=src_lang,
101
- tgt_lang=tgt_lang,
102
- max_length=512,
103
- repetition_penalty=1.2, # Tekrar cezası
104
- no_repeat_ngram_size=3, # 3 kelimelik tekrarları yasakla
105
- num_beams=3 # Rota arama kalitesini artır
106
- )
107
-
108
- return result[0]['translation_text']
109
-
110
- except Exception as e:
111
- return f"❌ Çeviri Hatası: {str(e)}"
112
 
113
 
114
  # ==================== TRANSCRIPTION (WHISPER) ====================
@@ -166,48 +155,55 @@ def transcribe(audio_path: str, progress=gr.Progress()):
166
 
167
  # ==================== UI (GRADIO) ====================
168
 
169
- with gr.Blocks(title="Ses Deşifre Pro (Local AI)") as demo:
170
 
171
  gr.HTML("""
172
  <style>
173
  footer { display: none !important; }
174
  .gradio-container { max-width: 900px !important; margin: auto !important; }
175
  </style>
176
- <div style="text-align: center; padding: 30px; background: linear-gradient(135deg, #10b981 0%, #059669 100%); border-radius: 20px; margin-bottom: 20px; color: white;">
177
- <h1 style="font-size: 2.2rem; margin: 0;">🎙️ Ses Deşifre & Local AI</h1>
178
- <p style="opacity: 0.9;">%100 Çevrimdışı Token YokLimit Yok</p>
179
  </div>
180
  """)
181
 
182
  with gr.Row():
183
  with gr.Column():
184
  audio_input = gr.Audio(label="Ses Dosyası", type="filepath", sources=["upload", "microphone"])
185
- submit_btn = gr.Button("🚀 Başlat", variant="primary", size="lg")
186
 
187
  with gr.Row():
188
  with gr.Column():
189
- output_text = gr.Textbox(label="Deşifre Metni", placeholder="Sonuçlar burada görünecek...", lines=10, interactive=False)
190
- download_file = gr.File(label="Metni İndir (.txt)")
191
 
192
- # --- LOCAL AI ARAÇLARI ---
193
- gr.HTML("<h3 style='margin-top: 20px; border-bottom: 1px solid #ddd; padding-bottom: 10px;'>🧠 Yerel Yapay Zeka (CPU)</h3>")
 
 
 
 
 
 
 
194
 
195
  with gr.Tabs():
196
- with gr.TabItem("✨ Özetle (mT5)"):
197
- summary_btn = gr.Button("📝 Metni Özetle")
198
  summary_output = gr.Textbox(label="Özet Sonucu", lines=6)
199
 
200
- with gr.TabItem("🌍 Çevir (NLLB)"):
201
  with gr.Row():
202
  target_lang = gr.Dropdown(["İngilizce", "Almanca", "Fransızca"], label="Hedef Dil", value="İngilizce")
203
- translate_btn = gr.Button("A Çevir")
204
  translate_output = gr.Textbox(label="Çeviri Sonucu", lines=6)
205
 
206
  # --- BAĞLANTILAR ---
207
  submit_btn.click(transcribe, inputs=[audio_input], outputs=[output_text, download_file])
208
 
209
- summary_btn.click(summarize_locally, inputs=[output_text], outputs=summary_output)
210
- translate_btn.click(translate_locally, inputs=[output_text, target_lang], outputs=translate_output)
211
 
212
  if __name__ == "__main__":
213
  demo.launch(share=False)
 
9
  import tempfile
10
  import time
11
  import os
12
+ import requests
13
  # import requests # Artık gerek yok
14
+ # from transformers import pipeline
15
+ # import torch
16
 
17
  # ==================== CONFIG & MODELS ====================
18
 
19
+ # 1. WHISPER MODEL (Ses Deşifre - CPU/Local)
20
  MODEL_SIZE = "medium"
21
  model = None
22
 
23
  try:
24
+ print(f"📥 Whisper {MODEL_SIZE} modeli yükleniyor...")
25
  model = WhisperModel(MODEL_SIZE, device="cpu", compute_type="int8")
26
  print("✅ Whisper Modeli Hazır!")
27
  except Exception as e:
28
  print(f"❌ Whisper Yükleme Hatası: {e}")
29
  model = None
30
 
31
+ # ==================== AI API FUNCTIONS (Hugging Face) ====================
32
+
33
+ def call_huggingface_api(prompt, api_key, model_id):
34
+ """
35
+ Hugging Face Serverless Inference API (Legacy Endpoint).
36
+ Standart 'Read' token ile çalışır.
37
+ """
38
+ if not api_key: return "⚠️ HF Token girilmedi."
39
+ if not api_key.startswith("hf_"): return "⚠️ Token 'hf_' ile başlamalıdır."
40
+
41
+ url = f"https://api-inference.huggingface.co/models/{model_id}"
42
+ headers = {"Authorization": f"Bearer {api_key}"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
+ # Zephyr/Mistral Prompt Formatı
45
+ formatted_prompt = f"<|system|>\nSen yardımsever bir asistansın.\n<|user|>\n{prompt}\n<|assistant|>\n"
46
 
47
+ payload = {
48
+ "inputs": formatted_prompt,
49
+ "parameters": {
50
+ "max_new_tokens": 512,
51
+ "return_full_text": False,
52
+ "temperature": 0.3
53
+ }
54
+ }
55
+
56
  try:
57
+ response = requests.post(url, headers=headers, json=payload, timeout=60)
 
 
 
 
 
 
58
 
59
+ if response.status_code == 200:
60
+ result = response.json()
61
+ if isinstance(result, list) and len(result) > 0 and "generated_text" in result[0]:
62
+ return result[0]["generated_text"].strip()
63
+ elif isinstance(result, dict) and "generated_text" in result:
64
+ return result["generated_text"].strip()
65
+ return f"❌ API Beklenmedik Yanıt: {result}"
66
+
67
+ elif response.status_code == 503:
68
+ return "⚠️ Model şu an yükleniyor (Cold Boot). 30 saniye sonra tekrar deneyin."
69
+
70
+ else:
71
+ return f"❌ API Hatası ({response.status_code}): {response.text}"
72
 
73
  except Exception as e:
74
+ return f"❌ Bağlantı Hatası: {str(e)}"
75
+
76
+ def summarize_with_api(text: str, api_key: str) -> str:
77
+ """Zephyr-7B kullanarak özetler."""
78
+ if not text or "⚠️" in text: return "⚠️ Özetlenecek metin yok."
79
+
80
+ clean_text = text.split("───────────────────────────────────")[0].strip()
81
+ prompt = f"Aşağıdaki metni Türkçe olarak maddeler halinde özetle:\n\n{clean_text}"
82
+
83
+ # Model: Zephyr 7B Beta (Genelde çok stabil ve ücretsiz)
84
+ return call_huggingface_api(prompt, api_key, "HuggingFaceH4/zephyr-7b-beta")
85
 
86
+ def translate_with_api(text: str, target_language: str, api_key: str) -> str:
87
+ """Facebook NLLB kullanarak çevirir (API üzerinden)."""
88
  if not text or "⚠️" in text: return "⚠️ Çevrilecek metin yok."
89
 
90
  clean_text = text.split("───────────────────────────────────")[0].strip()
91
 
92
+ # Dil haritası
93
+ lang_map = {"İngilizce": "English", "Almanca": "German", "Fransızca": "French", "Türkçe": "Turkish"}
94
+ tgt = lang_map.get(target_language, "English")
 
 
 
 
 
 
95
 
96
+ prompt = f"Translate the following text to {tgt}. Only provide the translation, no extra text.\n\nText:\n{clean_text}"
97
+
98
+ # Model: Zephyr çeviri için de iyidir, NLLB API'si bazen kararsız olabilir.
99
+ # Yine de NLLB deneyebiliriz ama Zephyr daha genel amaçlı ve sağlamdır.
100
+ return call_huggingface_api(prompt, api_key, "HuggingFaceH4/zephyr-7b-beta")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
 
103
  # ==================== TRANSCRIPTION (WHISPER) ====================
 
155
 
156
  # ==================== UI (GRADIO) ====================
157
 
158
+ with gr.Blocks(title="Ses Deşifre Pro (Whisper + HF API)") as demo:
159
 
160
  gr.HTML("""
161
  <style>
162
  footer { display: none !important; }
163
  .gradio-container { max-width: 900px !important; margin: auto !important; }
164
  </style>
165
+ <div style="text-align: center; padding: 30px; background: linear-gradient(135deg, #6366f1 0%, #a855f7 100%); border-radius: 20px; margin-bottom: 20px; color: white;">
166
+ <h1 style="font-size: 2.2rem; margin: 0;">🎙️ Ses Deşifre & HF API</h1>
167
+ <p style="opacity: 0.9;">Whisper (Local) + Zephyr AI (Cloud) Hızlı & Ücretsiz</p>
168
  </div>
169
  """)
170
 
171
  with gr.Row():
172
  with gr.Column():
173
  audio_input = gr.Audio(label="Ses Dosyası", type="filepath", sources=["upload", "microphone"])
174
+ submit_btn = gr.Button("🚀 Deşifre Et", variant="primary", size="lg")
175
 
176
  with gr.Row():
177
  with gr.Column():
178
+ output_text = gr.Textbox(label="Metin", placeholder="Sonuçlar burada...", lines=10, interactive=False)
179
+ download_file = gr.File(label="İndir (.txt)")
180
 
181
+ # --- API GİRİŞİ ---
182
+ gr.HTML("<h3 style='margin-top: 20px; border-bottom: 1px solid #ddd; padding-bottom: 10px;'>☁️ Hugging Face API (Özet & Çeviri)</h3>")
183
+
184
+ with gr.Row():
185
+ api_key_input = gr.Textbox(
186
+ label="🔑 HF Token (Örn: hf_...)",
187
+ placeholder="Read yetkili token yapıştırın...",
188
+ type="password"
189
+ )
190
 
191
  with gr.Tabs():
192
+ with gr.TabItem("✨ Özetle"):
193
+ summary_btn = gr.Button("📝 Token ile Özetle (Zephyr)")
194
  summary_output = gr.Textbox(label="Özet Sonucu", lines=6)
195
 
196
+ with gr.TabItem("🌍 Çevir"):
197
  with gr.Row():
198
  target_lang = gr.Dropdown(["İngilizce", "Almanca", "Fransızca"], label="Hedef Dil", value="İngilizce")
199
+ translate_btn = gr.Button("A Çevir (Zephyr)")
200
  translate_output = gr.Textbox(label="Çeviri Sonucu", lines=6)
201
 
202
  # --- BAĞLANTILAR ---
203
  submit_btn.click(transcribe, inputs=[audio_input], outputs=[output_text, download_file])
204
 
205
+ summary_btn.click(summarize_with_api, inputs=[output_text, api_key_input], outputs=summary_output)
206
+ translate_btn.click(translate_with_api, inputs=[output_text, target_lang, api_key_input], outputs=translate_output)
207
 
208
  if __name__ == "__main__":
209
  demo.launch(share=False)