# START # Türkçe Konuşma Tanıma ve Sentezleme Uygulaması - v7 # Bu uygulama, mikrofondan alınan Türkçe konuşmayı tanıyarak metne çevirmekte # ve bu metni Facebook MMS modeliyle tekrar sentezlemektedir. # Whisper modeli konuşma tanıma (STT) için, Facebook MMS (VITS) modeli ise metin-konuşma (TTS) için kullanılmaktadır. # Tüm modeller ve işlemler HF Spaces içinde çalışmaktadır, harici API kullanımı yoktur. import streamlit as st import numpy as np import torch from transformers import WhisperProcessor, WhisperForConditionalGeneration import soundfile as sf import tempfile import os import time import psutil from audio_recorder_streamlit import audio_recorder from scipy.signal import resample import torchaudio import shutil import glob import sys import importlib.util import subprocess # Sayfa düzeni st.set_page_config(layout="wide", page_title="Türkçe STT ve TTS - v7") col1, col2 = st.columns([2, 1]) with col1: # Ana içerik st.title("Mikrofondan Türkçe Konuşma Tanıma ve Sentezleme v7") # Debug modunu ayarla show_debug = st.checkbox("Debug Bilgilerini Göster", value=False) # Gerekli paketleri yükle (phonemizer) def install_required_packages(): """Facebook MMS modeli için gerekli paketleri yükler.""" packages = ["phonemizer"] for package in packages: try: # Paket yüklü mü kontrol et importlib.util.find_spec(package) if show_debug: st.write(f"📦 {package} zaten yüklü") except ImportError: # Yüklü değilse yükle st.info(f"📦 {package} yükleniyor... (bu biraz zaman alabilir)") subprocess.check_call([sys.executable, "-m", "pip", "install", package]) if show_debug: st.success(f"📦 {package} başarıyla yüklendi") # Gerekli paketleri yükle with st.spinner("Gerekli paketler kontrol ediliyor..."): install_required_packages() # Model yükleme @st.cache_resource def load_whisper_model(): """Whisper modelini yükler ve döndürür.""" start_time = time.time() processor = WhisperProcessor.from_pretrained("openai/whisper-small") model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-small") device = "cuda" if torch.cuda.is_available() else "cpu" model = model.to(device) end_time = time.time() return processor, model, device, end_time - start_time # Facebook MMS model yükleme - VITS modeli için gerekli ayarlamalar yapıldı @st.cache_resource def load_facebook_mms(): """Facebook MMS VITS modelini yükler ve döndürür.""" start_time = time.time() device = "cuda" if torch.cuda.is_available() else "cpu" # Debug için mevcut transformers modüllerini kontrol et ve göster if show_debug: import transformers st.write(f"Transformers versiyonu: {transformers.__version__}") trf_classes = dir(transformers) speech_classes = [cls for cls in trf_classes if "speech" in cls.lower() or "tts" in cls.lower() or "vits" in cls.lower()] st.write(f"TTS ile ilgili transformers sınıfları: {speech_classes}") # VITS modeli için gerekli sınıfları import et from transformers import VitsModel, VitsTokenizer try: # Modeli ve tokenizer'ı yükle processor = VitsTokenizer.from_pretrained("facebook/mms-tts-tur") model = VitsModel.from_pretrained("facebook/mms-tts-tur").to(device) if show_debug: st.write(f"MMS model tipi: {type(model).__name__}") st.write(f"MMS processor tipi: {type(processor).__name__}") # Model metodlarını listele model_methods = [method for method in dir(model) if not method.startswith('_')] st.write(f"Model metodları: {model_methods}") except Exception as e: if show_debug: st.error(f"Facebook MMS modelini yüklerken hata: {str(e)}") import traceback st.code(traceback.format_exc()) raise e end_time = time.time() return model, processor, device, end_time - start_time # Özel TTS sentezleme fonksiyonu def synthesize_with_facebook_mms(text, output_path, model=None, processor=None): """VITS modelini kullanarak TTS gerçekleştirir.""" if not text or len(text.strip()) < 2: raise ValueError("Metin çok kısa, sentezleme yapılamıyor.") try: # Eğer model ve processor sağlanmadıysa, yükle if model is None or processor is None: model, processor, device, _ = load_facebook_mms() else: device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = model.to(device) # Model tipini kontrol et model_type = model.__class__.__name__ if show_debug: st.write(f"Sentezleme model tipi: {model_type}") # Çıktı dizini kontrol et output_dir = os.path.dirname(output_path) os.makedirs(output_dir, exist_ok=True) # Metni işleme inputs = processor(text=text, return_tensors="pt").to(device) # VitsModel sınıfının forward metodu ile ses sentezleme with torch.no_grad(): outputs = model(**inputs) # Waveform çıktısını al waveform = outputs.waveform[0].cpu().numpy() # Ses dosyasını kaydet (sample rate 16000 Hz) sf.write(output_path, waveform, 16000) return True except Exception as e: if show_debug: st.error(f"Sentezleme hatası: {str(e)}") import traceback st.code(traceback.format_exc()) # Hata ayıklama için çıktı yapısını kontrol et if 'outputs' in locals(): st.write("Model çıktı özellikleri:") for key, value in outputs.items(): if isinstance(value, torch.Tensor): st.write(f"- {key}: Tensor şekli {value.shape}") else: st.write(f"- {key}: {type(value)}") raise e # Ses kaydı al st.write("Mikrofon kaydı için aşağıdaki butona tıklayın:") audio_bytes = audio_recorder() # Performans metrikleri için placeholder if 'performance_logs' not in st.session_state: st.session_state.performance_logs = [] if audio_bytes: # Zaman takibi başlangıcı process_start_time = time.time() performance_log = [] # Geçici dizin yönetimi temp_dir = tempfile.mkdtemp() if show_debug: st.write(f"Geçici dizin: {temp_dir}") # 1. Whisper Model yükleme load_start = time.time() st.write("Konuşma tanıma modeli yükleniyor...") processor, model, device, model_load_time = load_whisper_model() load_end = time.time() performance_log.append({"adım": "Whisper modeli yükleme", "süre_ms": round((load_end - load_start) * 1000, 2)}) # 2. Ses dosyasını kaydetme file_start = time.time() input_audio_path = os.path.join(temp_dir, "input_audio.wav") with open(input_audio_path, "wb") as temp_audio: temp_audio.write(audio_bytes) file_end = time.time() performance_log.append({"adım": "Ses dosyası kaydetme", "süre_ms": round((file_end - file_start) * 1000, 2)}) if show_debug: st.write(f"Kaydedilen ses dosyası: {input_audio_path}") if os.path.exists(input_audio_path): st.write(f"Dosya boyutu: {os.path.getsize(input_audio_path)} bytes") else: st.error(f"Dosya bulunamadı: {input_audio_path}") # Ses dosyasını işle with st.spinner("Ses tanıma yapılıyor..."): try: # 3. Ses dosyasını yükleme load_audio_start = time.time() audio_array, sampling_rate = sf.read(input_audio_path) load_audio_end = time.time() performance_log.append({"adım": "Ses dosyası yükleme", "süre_ms": round((load_audio_end - load_audio_start) * 1000, 2)}) # 4. Ses işleme preprocess_start = time.time() # Stereo ise mono'ya dönüştür if len(audio_array.shape) > 1: audio_array = np.mean(audio_array, axis=1) # Ses ön işleme if sampling_rate != 16000: audio_array = resample(audio_array, int(len(audio_array) * 16000 / sampling_rate)) sampling_rate = 16000 # İşleme için hazırla input_features = processor( audio_array, sampling_rate=16000, return_tensors="pt" ).input_features.to(device) # Türkçe için ayarla forced_decoder_ids = processor.get_decoder_prompt_ids(language="turkish", task="transcribe") preprocess_end = time.time() performance_log.append({"adım": "Ses ön işleme", "süre_ms": round((preprocess_end - preprocess_start) * 1000, 2)}) # 5. Tanıma işlemi inference_start = time.time() with torch.no_grad(): predicted_ids = model.generate( input_features, forced_decoder_ids=forced_decoder_ids, max_length=448 ) inference_end = time.time() performance_log.append({"adım": "Model çıkarım (inference)", "süre_ms": round((inference_end - inference_start) * 1000, 2)}) # 6. Metne dönüştürme decode_start = time.time() transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)[0] decode_end = time.time() performance_log.append({"adım": "Metin oluşturma", "süre_ms": round((decode_end - decode_start) * 1000, 2)}) # Toplam STT süresini hesapla stt_total_time = time.time() - process_start_time performance_log.append({"adım": "Toplam STT işlemi", "süre_ms": round(stt_total_time * 1000, 2)}) # Sonucu göster st.success("Tanıma tamamlandı!") st.write("### Tanıma Sonucu:") st.write(transcription) # Ses dosyasını oynat st.write("### Orijinal Ses:") st.audio(audio_bytes) # 7. Facebook MMS ile ses sentezleme st.write("### Ses Sentezleme:") with st.spinner("Facebook MMS ile ses sentezleme yapılıyor..."): try: # Facebook MMS modelini yükle tts_load_start = time.time() st.info("Facebook MMS modeli yükleniyor... (ilk kez çalıştırıyorsanız bu biraz zaman alabilir)") mms_model, mms_processor, tts_device, mms_load_time = load_facebook_mms() tts_load_end = time.time() performance_log.append({"adım": "Facebook MMS yükleme", "süre_ms": round((tts_load_end - tts_load_start) * 1000, 2)}) # Metni sentezle tts_start = time.time() synth_audio_path = os.path.join(temp_dir, "synthesized_audio.wav") # Facebook MMS ile sentezleme synthesize_result = synthesize_with_facebook_mms( text=transcription, output_path=synth_audio_path, model=mms_model, processor=mms_processor ) tts_end = time.time() performance_log.append({"adım": "Ses sentezleme", "süre_ms": round((tts_end - tts_start) * 1000, 2)}) # Sentezlenen sesi göster if os.path.exists(synth_audio_path): with open(synth_audio_path, "rb") as synth_file: synth_audio_bytes = synth_file.read() st.write("### Sentezlenen Ses:") st.audio(synth_audio_bytes) else: st.warning("Sentezleme tamamlandı ancak ses dosyası oluşturulamadı.") # Toplam TTS süresini hesapla tts_total_time = tts_end - tts_load_start performance_log.append({"adım": "Toplam TTS işlemi", "süre_ms": round(tts_total_time * 1000, 2)}) except Exception as tts_error: st.error(f"Ses sentezleme hatası: {str(tts_error)}") if show_debug: import traceback st.code(traceback.format_exc()) # Genel toplam süreyi hesapla total_time = time.time() - process_start_time performance_log.append({"adım": "Toplam uçtan uca işlem", "süre_ms": round(total_time * 1000, 2)}) # Debug bilgileri if show_debug: st.write("### Debug Bilgileri") st.write(f"Geçici dizin: {temp_dir}") st.write(f"Geçici dizindeki dosyalar: {os.listdir(temp_dir)}") st.write(f"Girdi ses dosyası: {input_audio_path}") if 'synth_audio_path' in locals() and os.path.exists(synth_audio_path): st.write(f"Sentezlenmiş ses dosyası: {synth_audio_path}") st.write(f"Sentezlenmiş ses dosyası boyutu: {os.path.getsize(synth_audio_path)} bytes") # TTS ile ilgili ek bilgiler st.write("### TTS Debug Bilgileri") st.write(f"Sentezlenecek metin: '{transcription}'") if 'mms_model' in locals(): st.write(f"MMS model tipi: {type(mms_model).__name__}") if 'mms_processor' in locals(): st.write(f"MMS processor tipi: {type(mms_processor).__name__}") # Sistem durumu bilgileri st.write("### Sistem Durumu:") st.write(f"Python sürümü: {sys.version}") st.write(f"PyTorch sürümü: {torch.__version__}") st.write(f"Mevcut çalışma dizini: {os.getcwd()}") st.write(f"Geçici dizin: {tempfile.gettempdir()}") # Yüklü paketleri kontrol et st.write("### Yüklü Paketler:") try: import pkg_resources packages = sorted(["%s==%s" % (i.key, i.version) for i in pkg_resources.working_set]) for package in packages: if "phonemizer" in package or "transformers" in package or "torch" in package: st.write(f"- {package}") except: st.write("Paket bilgileri alınamadı.") # Temizlik (Debug modunda temizlemeyi atla) if not show_debug: try: # Geçici dizindeki tüm dosyaları temizle for temp_file in glob.glob(os.path.join(temp_dir, "*")): os.remove(temp_file) # Geçici dizini sil os.rmdir(temp_dir) except Exception as e: if show_debug: st.warning(f"Temizlik hatası: {str(e)}") # Performans loglarını kaydet st.session_state.performance_logs = performance_log except Exception as e: st.error(f"Hata: {str(e)}") if show_debug: import traceback st.code(traceback.format_exc()) # Performans bilgilerini gösteren yan panel with col2: st.title("Performans Analizi") # Performans metrikleri göster if st.session_state.performance_logs: st.write("### Adım Süreleri (ms)") for log in st.session_state.performance_logs: st.write(f"**{log['adım']}:** {log['süre_ms']} ms") # Sistem kaynak kullanımı st.write("### Sistem Kaynak Kullanımı") # Gerçek zamanlı CPU ve RAM kullanımı cpu_usage = psutil.cpu_percent() ram_usage = psutil.virtual_memory().percent # CPU ve RAM göstergeleri st.progress(cpu_usage / 100, text=f"CPU Kullanımı: {cpu_usage}%") st.progress(ram_usage / 100, text=f"RAM Kullanımı: {ram_usage}%") # Detaylı sistem bilgileri st.write("### Detaylı Sistem Bilgileri") # CPU bilgileri cpu_count = psutil.cpu_count(logical=False) cpu_threads = psutil.cpu_count(logical=True) st.write(f"**CPU Çekirdek Sayısı:** {cpu_count} (Toplam {cpu_threads} iş parçacığı)") # RAM bilgileri ram = psutil.virtual_memory() st.write(f"**Toplam RAM:** {ram.total / (1024**3):.2f} GB") st.write(f"**Kullanılan RAM:** {ram.used / (1024**3):.2f} GB") # Torch cihaz bilgisi st.write(f"**PyTorch Cihazı:** {'CUDA' if torch.cuda.is_available() else 'CPU'}") if torch.cuda.is_available(): st.write(f"**GPU Modeli:** {torch.cuda.get_device_name(0)}") st.write(f"**CUDA Versiyonu:** {torch.version.cuda}") # Model bilgileri st.write("### Model Bilgileri") st.write("**STT Modeli:** openai/whisper-small") st.write("**TTS Modeli:** facebook/mms-tts-tur (VITS)") # Transformers bilgileri try: import transformers st.write(f"**Transformers Versiyonu:** {transformers.__version__}") except: st.write("**Transformers Versiyonu:** Bilinmiyor") # Phonemizer durumu try: import phonemizer st.write(f"**Phonemizer Versiyonu:** {phonemizer.__version__}") st.write("**Phonemizer Durumu:** ✅ Yüklü") except ImportError: st.write("**Phonemizer Durumu:** ❌ Yüklü değil") # Ekranı güncelle if st.button("Sistem Durumunu Güncelle"): st.experimental_rerun() # STOP