Update app.py
Browse files
app.py
CHANGED
|
@@ -1,97 +1,159 @@
|
|
| 1 |
import os
|
|
|
|
|
|
|
| 2 |
import threading
|
| 3 |
-
import queue
|
| 4 |
-
import re
|
| 5 |
-
import json
|
| 6 |
-
import requests
|
| 7 |
from flask import Flask, render_template, request, jsonify, Response
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
import april_asr as april
|
|
|
|
| 9 |
|
| 10 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
app = Flask(__name__)
|
| 12 |
|
| 13 |
-
# Global değişkenler
|
| 14 |
live_caption_instance = None
|
| 15 |
is_running = False
|
| 16 |
asr_queue = queue.Queue()
|
| 17 |
-
translator = None
|
| 18 |
|
| 19 |
-
# Basit Google Translate sınıfı (HTTP GET ile)
|
| 20 |
class SimpleGoogleTranslator:
|
| 21 |
def __init__(self):
|
| 22 |
self.session = requests.Session()
|
| 23 |
self.session.headers.update({
|
| 24 |
-
'User-Agent': 'Mozilla/5.0'
|
| 25 |
})
|
| 26 |
-
|
| 27 |
def translate(self, text, target_lang='tr', source_lang='en'):
|
| 28 |
try:
|
| 29 |
url = "https://translate.googleapis.com/translate_a/single"
|
| 30 |
-
params = {
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
except Exception as e:
|
| 36 |
print(f"Simple Google Translate error: {e}")
|
| 37 |
-
|
| 38 |
|
| 39 |
class ImprovedTranslator:
|
| 40 |
def __init__(self):
|
|
|
|
| 41 |
self.simple_translator = SimpleGoogleTranslator()
|
| 42 |
-
|
|
|
|
| 43 |
def translate(self, text, target_lang, service="Google Translate", deepl_key=""):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
text = text.strip()
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
try:
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
'pt': 'PT', 'nl': 'NL', 'ko': 'KO'
|
| 56 |
-
}
|
| 57 |
-
target = deepl_lang_map.get(target_lang, target_lang.upper())
|
| 58 |
-
result = translator.translate_text(text, target_lang=target)
|
| 59 |
-
return result.text if result else "[DeepL failed]"
|
| 60 |
except Exception as e:
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
-
# ASR modelini başlat
|
| 66 |
def init_asr():
|
|
|
|
| 67 |
global live_caption_instance
|
| 68 |
-
if live_caption_instance is
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
t = threading.Thread(target=init_asr)
|
| 92 |
-
t.start()
|
| 93 |
|
| 94 |
-
# Routes
|
| 95 |
@app.route('/')
|
| 96 |
def index():
|
| 97 |
return render_template('index.html')
|
|
@@ -100,7 +162,7 @@ def index():
|
|
| 100 |
def start_stream():
|
| 101 |
global is_running, translator
|
| 102 |
if not is_running:
|
| 103 |
-
|
| 104 |
translator = ImprovedTranslator()
|
| 105 |
is_running = True
|
| 106 |
return jsonify({"status": "started"})
|
|
@@ -110,18 +172,21 @@ def stop_stream():
|
|
| 110 |
global is_running, live_caption_instance
|
| 111 |
if is_running:
|
| 112 |
is_running = False
|
| 113 |
-
|
|
|
|
| 114 |
return jsonify({"status": "stopped"})
|
| 115 |
|
| 116 |
@app.route('/upload_audio', methods=['POST'])
|
| 117 |
def upload_audio():
|
| 118 |
audio_data = request.data
|
|
|
|
| 119 |
if live_caption_instance:
|
| 120 |
try:
|
| 121 |
live_caption_instance.feed_pcm16(audio_data)
|
| 122 |
except Exception as e:
|
| 123 |
print(f"[HATA] ASR feed hatası: {e}")
|
| 124 |
return jsonify({"status": "error", "message": str(e)}), 500
|
|
|
|
| 125 |
return '', 204
|
| 126 |
|
| 127 |
@app.route('/stream_results')
|
|
@@ -129,18 +194,35 @@ def stream_results():
|
|
| 129 |
target_lang = request.args.get("target_lang", "tr")
|
| 130 |
service = request.args.get("service", "Google Translate")
|
| 131 |
deepl_key = request.args.get("deepl_key", "")
|
| 132 |
-
|
| 133 |
def generate():
|
| 134 |
while is_running:
|
| 135 |
try:
|
| 136 |
result = asr_queue.get(timeout=0.1)
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
except queue.Empty:
|
| 141 |
continue
|
| 142 |
except Exception as e:
|
| 143 |
print(f"SSE hatası: {e}")
|
| 144 |
break
|
| 145 |
-
|
| 146 |
return Response(generate(), mimetype='text/event-stream')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import sys
|
| 3 |
+
import time
|
| 4 |
import threading
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
from flask import Flask, render_template, request, jsonify, Response
|
| 6 |
+
import numpy as np
|
| 7 |
+
import requests
|
| 8 |
+
import re
|
| 9 |
+
import queue
|
| 10 |
import april_asr as april
|
| 11 |
+
import json
|
| 12 |
|
| 13 |
+
# Google çeviri için farklı yaklaşım
|
| 14 |
+
try:
|
| 15 |
+
from googletrans import Translator
|
| 16 |
+
GOOGLE_TRANSLATE_AVAILABLE = True
|
| 17 |
+
except Exception as e:
|
| 18 |
+
print(f"Google Translate loading error: {e}")
|
| 19 |
+
GOOGLE_TRANSLATE_AVAILABLE = False
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
import deepl
|
| 23 |
+
DEEPL_AVAILABLE = True
|
| 24 |
+
except ImportError:
|
| 25 |
+
DEEPL_AVAILABLE = False
|
| 26 |
+
|
| 27 |
+
# Flask uygulamasını başlat
|
| 28 |
app = Flask(__name__)
|
| 29 |
|
| 30 |
+
# Global değişkenler ve nesneler
|
| 31 |
live_caption_instance = None
|
| 32 |
is_running = False
|
| 33 |
asr_queue = queue.Queue()
|
| 34 |
+
translator = None # Translator nesnesini global tanımla
|
| 35 |
|
|
|
|
| 36 |
class SimpleGoogleTranslator:
|
| 37 |
def __init__(self):
|
| 38 |
self.session = requests.Session()
|
| 39 |
self.session.headers.update({
|
| 40 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
|
| 41 |
})
|
| 42 |
+
|
| 43 |
def translate(self, text, target_lang='tr', source_lang='en'):
|
| 44 |
try:
|
| 45 |
url = "https://translate.googleapis.com/translate_a/single"
|
| 46 |
+
params = {
|
| 47 |
+
'client': 'gtx',
|
| 48 |
+
'sl': source_lang,
|
| 49 |
+
'tl': target_lang,
|
| 50 |
+
'dt': 't',
|
| 51 |
+
'q': text
|
| 52 |
+
}
|
| 53 |
+
response = self.session.get(url, params=params, timeout=10)
|
| 54 |
+
if response.status_code == 200:
|
| 55 |
+
result = response.json()
|
| 56 |
+
if result and len(result) > 0 and len(result[0]) > 0:
|
| 57 |
+
translated_text = ''.join([item[0] for item in result[0] if item[0]])
|
| 58 |
+
return translated_text
|
| 59 |
+
return None
|
| 60 |
except Exception as e:
|
| 61 |
print(f"Simple Google Translate error: {e}")
|
| 62 |
+
return None
|
| 63 |
|
| 64 |
class ImprovedTranslator:
|
| 65 |
def __init__(self):
|
| 66 |
+
self.google_translator = None
|
| 67 |
self.simple_translator = SimpleGoogleTranslator()
|
| 68 |
+
self.deepl_translator = None
|
| 69 |
+
|
| 70 |
def translate(self, text, target_lang, service="Google Translate", deepl_key=""):
|
| 71 |
+
if not text or not text.strip():
|
| 72 |
+
return ""
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
cleaned_text = self._clean_text(text)
|
| 76 |
+
|
| 77 |
+
if service == "Google Translate":
|
| 78 |
+
return self._google_translate(cleaned_text, target_lang)
|
| 79 |
+
elif service == "DeepL" and DEEPL_AVAILABLE and deepl_key:
|
| 80 |
+
return self._deepl_translate(cleaned_text, target_lang, deepl_key)
|
| 81 |
+
else:
|
| 82 |
+
return f"[{service} not available]"
|
| 83 |
+
|
| 84 |
+
except Exception as e:
|
| 85 |
+
return f"[Translation error: {str(e)[:50]}...]"
|
| 86 |
+
|
| 87 |
+
def _clean_text(self, text):
|
| 88 |
text = text.strip()
|
| 89 |
+
text = re.sub(r'\s+', ' ', text)
|
| 90 |
+
return text
|
| 91 |
+
|
| 92 |
+
def _google_translate(self, text, target_lang):
|
| 93 |
+
try:
|
| 94 |
+
result = self.simple_translator.translate(text, target_lang)
|
| 95 |
+
if result:
|
| 96 |
+
return result
|
| 97 |
+
except Exception as e:
|
| 98 |
+
print(f"Simple translator failed: {e}")
|
| 99 |
+
|
| 100 |
+
if GOOGLE_TRANSLATE_AVAILABLE:
|
| 101 |
try:
|
| 102 |
+
if self.google_translator is None:
|
| 103 |
+
self.google_translator = Translator()
|
| 104 |
+
result = self.google_translator.translate(text, dest=target_lang, src='en')
|
| 105 |
+
if result and result.text:
|
| 106 |
+
return result.text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
except Exception as e:
|
| 108 |
+
print(f"Googletrans failed: {e}")
|
| 109 |
+
|
| 110 |
+
return "[Google translation failed]"
|
| 111 |
+
|
| 112 |
+
def _deepl_translate(self, text, target_lang, deepl_key):
|
| 113 |
+
try:
|
| 114 |
+
if self.deepl_translator is None:
|
| 115 |
+
self.deepl_translator = deepl.Translator(deepl_key)
|
| 116 |
+
|
| 117 |
+
deepl_lang_map = {
|
| 118 |
+
'tr': 'TR', 'fr': 'FR', 'de': 'DE', 'es': 'ES',
|
| 119 |
+
'it': 'IT', 'ru': 'RU', 'ja': 'JA', 'zh-CN': 'ZH',
|
| 120 |
+
'pt': 'PT', 'nl': 'NL', 'ko': 'KO'
|
| 121 |
+
}
|
| 122 |
+
deepl_target = deepl_lang_map.get(target_lang, target_lang.upper())
|
| 123 |
+
|
| 124 |
+
result = self.deepl_translator.translate_text(text, target_lang=deepl_target)
|
| 125 |
+
return result.text if result else "[DeepL no result]"
|
| 126 |
+
|
| 127 |
+
except Exception as e:
|
| 128 |
+
return f"[DeepL error]"
|
| 129 |
|
|
|
|
| 130 |
def init_asr():
|
| 131 |
+
"""ASR modelini başlatır."""
|
| 132 |
global live_caption_instance
|
| 133 |
+
if live_caption_instance is None:
|
| 134 |
+
try:
|
| 135 |
+
model_path = "april-english-dev-01110_en.april"
|
| 136 |
+
if not os.path.exists(model_path):
|
| 137 |
+
print(f"[HATA] Model dosyası bulunamadı: {model_path}")
|
| 138 |
+
return
|
| 139 |
+
|
| 140 |
+
model = april.Model(model_path)
|
| 141 |
+
|
| 142 |
+
def asr_handler(result_type, tokens):
|
| 143 |
+
text = "".join(token.token for token in tokens).strip()
|
| 144 |
+
if not text:
|
| 145 |
+
return
|
| 146 |
+
if result_type == april.Result.PARTIAL_RECOGNITION:
|
| 147 |
+
asr_queue.put({"english": text, "type": "partial"})
|
| 148 |
+
elif result_type == april.Result.FINAL_RECOGNITION:
|
| 149 |
+
asr_queue.put({"english": text, "type": "final"})
|
| 150 |
+
|
| 151 |
+
live_caption_instance = april.Session(model, asr_handler, asynchronous=True)
|
| 152 |
+
print("ASR Model başarıyla başlatıldı.")
|
| 153 |
+
except Exception as e:
|
| 154 |
+
print(f"[HATA] ASR Model yükleme hatası: {e}")
|
| 155 |
+
live_caption_instance = None # Hata durumunda nesneyi None yap
|
|
|
|
|
|
|
| 156 |
|
|
|
|
| 157 |
@app.route('/')
|
| 158 |
def index():
|
| 159 |
return render_template('index.html')
|
|
|
|
| 162 |
def start_stream():
|
| 163 |
global is_running, translator
|
| 164 |
if not is_running:
|
| 165 |
+
init_asr()
|
| 166 |
translator = ImprovedTranslator()
|
| 167 |
is_running = True
|
| 168 |
return jsonify({"status": "started"})
|
|
|
|
| 172 |
global is_running, live_caption_instance
|
| 173 |
if is_running:
|
| 174 |
is_running = False
|
| 175 |
+
if live_caption_instance:
|
| 176 |
+
live_caption_instance = None
|
| 177 |
return jsonify({"status": "stopped"})
|
| 178 |
|
| 179 |
@app.route('/upload_audio', methods=['POST'])
|
| 180 |
def upload_audio():
|
| 181 |
audio_data = request.data
|
| 182 |
+
|
| 183 |
if live_caption_instance:
|
| 184 |
try:
|
| 185 |
live_caption_instance.feed_pcm16(audio_data)
|
| 186 |
except Exception as e:
|
| 187 |
print(f"[HATA] ASR feed hatası: {e}")
|
| 188 |
return jsonify({"status": "error", "message": str(e)}), 500
|
| 189 |
+
|
| 190 |
return '', 204
|
| 191 |
|
| 192 |
@app.route('/stream_results')
|
|
|
|
| 194 |
target_lang = request.args.get("target_lang", "tr")
|
| 195 |
service = request.args.get("service", "Google Translate")
|
| 196 |
deepl_key = request.args.get("deepl_key", "")
|
| 197 |
+
|
| 198 |
def generate():
|
| 199 |
while is_running:
|
| 200 |
try:
|
| 201 |
result = asr_queue.get(timeout=0.1)
|
| 202 |
+
english_text = result["english"]
|
| 203 |
+
result_type = result["type"]
|
| 204 |
+
|
| 205 |
+
translated_text = ""
|
| 206 |
+
if result_type == "partial":
|
| 207 |
+
translated_text = translator.translate(english_text, target_lang, "Google Translate", "")
|
| 208 |
+
elif result_type == "final":
|
| 209 |
+
translated_text = translator.translate(english_text, target_lang, service, deepl_key)
|
| 210 |
+
|
| 211 |
+
response_data = {
|
| 212 |
+
"english": english_text,
|
| 213 |
+
"type": result_type,
|
| 214 |
+
"translation": translated_text,
|
| 215 |
+
}
|
| 216 |
+
yield f"data: {json.dumps(response_data)}\n\n"
|
| 217 |
+
|
| 218 |
except queue.Empty:
|
| 219 |
continue
|
| 220 |
except Exception as e:
|
| 221 |
print(f"SSE hatası: {e}")
|
| 222 |
break
|
| 223 |
+
|
| 224 |
return Response(generate(), mimetype='text/event-stream')
|
| 225 |
+
|
| 226 |
+
if __name__ == '__main__':
|
| 227 |
+
init_asr()
|
| 228 |
+
app.run(host='0.0.0.0', port=5000, threaded=True)
|