Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,7 @@
|
|
| 1 |
-
from flask import Flask, render_template, request, jsonify
|
| 2 |
-
import requests
|
| 3 |
import os
|
|
|
|
|
|
|
| 4 |
import re
|
| 5 |
-
from functools import lru_cache
|
| 6 |
-
|
| 7 |
-
app = Flask(__name__)
|
| 8 |
|
| 9 |
# Registry for Key Status
|
| 10 |
key_status_registry = {}
|
|
@@ -19,10 +16,9 @@ class AIService:
|
|
| 19 |
if key:
|
| 20 |
keys.append(key)
|
| 21 |
i += 1
|
| 22 |
-
else:
|
| 23 |
-
break
|
| 24 |
if not keys and os.environ.get(prefix.replace("_KEY_", "_KEY")):
|
| 25 |
-
|
| 26 |
return keys
|
| 27 |
|
| 28 |
@staticmethod
|
|
@@ -30,6 +26,7 @@ class AIService:
|
|
| 30 |
prefix = "GEMINI_API_KEY_" if "Gemini" in engine else "GROQ_API_KEY_" if "Llama" in engine else "SEA_LION_API_KEY"
|
| 31 |
keys = AIService.get_all_keys(prefix)
|
| 32 |
label = engine.split(" ")[-1]
|
|
|
|
| 33 |
status_label = "ααααΆαααΆα/Status"
|
| 34 |
html = f"<div style='display: flex; gap: 8px; align-items: center; margin-bottom: 10px;'><b style='color: #94a3b8; font-size: 12px;'>{label} {status_label}:</b>"
|
| 35 |
for k in keys:
|
|
@@ -54,61 +51,39 @@ class AIService:
|
|
| 54 |
key_status_registry[key] = "ready"
|
| 55 |
return res.json()['candidates'][0]['content']['parts'][0]['text'].strip()
|
| 56 |
key_status_registry[key] = "dead"
|
| 57 |
-
except
|
| 58 |
-
print(f"Gemini API error: {e}")
|
| 59 |
-
continue
|
| 60 |
elif "Llama" in engine:
|
| 61 |
keys = AIService.get_all_keys("GROQ_API_KEY_")
|
| 62 |
for key in keys:
|
| 63 |
try:
|
| 64 |
res = requests.post("https://api.groq.com/openai/v1/chat/completions",
|
| 65 |
headers={"Authorization": f"Bearer {key}"},
|
| 66 |
-
json={"model": "llama-3.3-70b-versatile", "messages": [{"role": "user", "content": prompt}], "temperature": temp},
|
| 67 |
-
timeout=30)
|
| 68 |
if res.status_code == 200:
|
| 69 |
key_status_registry[key] = "ready"
|
| 70 |
return res.json()['choices'][0]['message']['content'].strip()
|
| 71 |
key_status_registry[key] = "dead"
|
| 72 |
-
except
|
| 73 |
-
|
| 74 |
-
continue
|
| 75 |
-
else: # SEA-LION
|
| 76 |
key = os.environ.get("SEA_LION_API_KEY")
|
| 77 |
try:
|
| 78 |
res = requests.post("https://api.sea-lion.ai/v1/chat/completions",
|
| 79 |
headers={"Authorization": f"Bearer {key}"},
|
| 80 |
json={
|
| 81 |
"model": "aisingapore/Gemma-SEA-LION-v4-27B-IT",
|
| 82 |
-
"messages": [
|
| 83 |
-
|
| 84 |
-
{"role": "user", "content": prompt}
|
| 85 |
-
],
|
| 86 |
"temperature": 0.7
|
| 87 |
}, timeout=60)
|
| 88 |
if res.status_code == 200:
|
| 89 |
key_status_registry[key] = "ready"
|
| 90 |
return res.json()['choices'][0]['message']['content'].strip()
|
| 91 |
key_status_registry[key] = "dead"
|
| 92 |
-
except
|
| 93 |
-
print(f"SEA-LION API error: {e}")
|
| 94 |
return None
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
return render_template('index.html')
|
| 99 |
-
|
| 100 |
-
@app.route('/translate', methods=['POST'])
|
| 101 |
-
def translate():
|
| 102 |
-
data = request.json
|
| 103 |
-
text = data.get('text', '')
|
| 104 |
-
target_lang = data.get('target_lang', 'π°π Khmer')
|
| 105 |
-
engine = data.get('engine', 'π Gemini')
|
| 106 |
-
|
| 107 |
-
if not text.strip():
|
| 108 |
-
return jsonify({
|
| 109 |
-
'translation': '',
|
| 110 |
-
'status_html': AIService.get_status_html(engine, target_lang)
|
| 111 |
-
})
|
| 112 |
|
| 113 |
lang_name = re.sub(r'[^\w\s]', '', target_lang).strip()
|
| 114 |
is_srt = bool(re.search(r'\d+\n\d{2}:\d{2}:\d{2}', text))
|
|
@@ -128,25 +103,43 @@ def translate():
|
|
| 128 |
if result:
|
| 129 |
cleaned = re.sub(r'```[a-zA-Z]*\n?|```', '', result).strip()
|
| 130 |
cleaned = re.sub(r'(?i)^(here is|translation|translated content):', '', cleaned).strip()
|
| 131 |
-
return
|
| 132 |
-
'translation': cleaned,
|
| 133 |
-
'status_html': AIService.get_status_html(engine, target_lang)
|
| 134 |
-
})
|
| 135 |
|
| 136 |
-
return
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
data = request.json
|
| 144 |
-
engine = data.get('engine', 'π Gemini')
|
| 145 |
-
target_lang = data.get('target_lang', 'π°π Khmer')
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
-
if __name__ ==
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import requests
|
| 3 |
+
import gradio as gr
|
| 4 |
import re
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
# Registry for Key Status
|
| 7 |
key_status_registry = {}
|
|
|
|
| 16 |
if key:
|
| 17 |
keys.append(key)
|
| 18 |
i += 1
|
| 19 |
+
else: break
|
|
|
|
| 20 |
if not keys and os.environ.get(prefix.replace("_KEY_", "_KEY")):
|
| 21 |
+
keys.append(os.environ.get(prefix.replace("_KEY_", "_KEY")))
|
| 22 |
return keys
|
| 23 |
|
| 24 |
@staticmethod
|
|
|
|
| 26 |
prefix = "GEMINI_API_KEY_" if "Gemini" in engine else "GROQ_API_KEY_" if "Llama" in engine else "SEA_LION_API_KEY"
|
| 27 |
keys = AIService.get_all_keys(prefix)
|
| 28 |
label = engine.split(" ")[-1]
|
| 29 |
+
# αααα αΆαααααΆαααΆαααΆ α’ ααΆααΆααΎααααΈαα»αα±αααα·ααΆα Refresh
|
| 30 |
status_label = "ααααΆαααΆα/Status"
|
| 31 |
html = f"<div style='display: flex; gap: 8px; align-items: center; margin-bottom: 10px;'><b style='color: #94a3b8; font-size: 12px;'>{label} {status_label}:</b>"
|
| 32 |
for k in keys:
|
|
|
|
| 51 |
key_status_registry[key] = "ready"
|
| 52 |
return res.json()['candidates'][0]['content']['parts'][0]['text'].strip()
|
| 53 |
key_status_registry[key] = "dead"
|
| 54 |
+
except: continue
|
|
|
|
|
|
|
| 55 |
elif "Llama" in engine:
|
| 56 |
keys = AIService.get_all_keys("GROQ_API_KEY_")
|
| 57 |
for key in keys:
|
| 58 |
try:
|
| 59 |
res = requests.post("https://api.groq.com/openai/v1/chat/completions",
|
| 60 |
headers={"Authorization": f"Bearer {key}"},
|
| 61 |
+
json={"model": "llama-3.3-70b-versatile", "messages": [{"role": "user", "content": prompt}], "temperature": temp}, timeout=30)
|
|
|
|
| 62 |
if res.status_code == 200:
|
| 63 |
key_status_registry[key] = "ready"
|
| 64 |
return res.json()['choices'][0]['message']['content'].strip()
|
| 65 |
key_status_registry[key] = "dead"
|
| 66 |
+
except: continue
|
| 67 |
+
else: # SEA-LION
|
|
|
|
|
|
|
| 68 |
key = os.environ.get("SEA_LION_API_KEY")
|
| 69 |
try:
|
| 70 |
res = requests.post("https://api.sea-lion.ai/v1/chat/completions",
|
| 71 |
headers={"Authorization": f"Bearer {key}"},
|
| 72 |
json={
|
| 73 |
"model": "aisingapore/Gemma-SEA-LION-v4-27B-IT",
|
| 74 |
+
"messages": [{"role": "system", "content": "You are an expert translator. Preserve proper names. Output ONLY translation."},
|
| 75 |
+
{"role": "user", "content": prompt}],
|
|
|
|
|
|
|
| 76 |
"temperature": 0.7
|
| 77 |
}, timeout=60)
|
| 78 |
if res.status_code == 200:
|
| 79 |
key_status_registry[key] = "ready"
|
| 80 |
return res.json()['choices'][0]['message']['content'].strip()
|
| 81 |
key_status_registry[key] = "dead"
|
| 82 |
+
except: pass
|
|
|
|
| 83 |
return None
|
| 84 |
|
| 85 |
+
def translator_hub(text, target_lang, engine):
|
| 86 |
+
if not text.strip(): return "", AIService.get_status_html(engine, target_lang)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
lang_name = re.sub(r'[^\w\s]', '', target_lang).strip()
|
| 89 |
is_srt = bool(re.search(r'\d+\n\d{2}:\d{2}:\d{2}', text))
|
|
|
|
| 103 |
if result:
|
| 104 |
cleaned = re.sub(r'```[a-zA-Z]*\n?|```', '', result).strip()
|
| 105 |
cleaned = re.sub(r'(?i)^(here is|translation|translated content):', '', cleaned).strip()
|
| 106 |
+
return cleaned, AIService.get_status_html(engine, target_lang)
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
+
return "β Error", AIService.get_status_html(engine, target_lang)
|
| 109 |
+
|
| 110 |
+
css = """
|
| 111 |
+
body { background-color: #0d1117; }
|
| 112 |
+
.btn-trans { background: linear-gradient(90deg, #238636, #2ea043) !important; color: white !important; border: none !important; }
|
| 113 |
+
.btn-clear { background: #30363d !important; color: #f85149 !important; border: 1px solid #f85149 !important; }
|
| 114 |
+
.btn-copy { background: #1f6feb !important; color: white !important; border: none !important; }
|
| 115 |
+
textarea { resize: both !important; }
|
| 116 |
+
"""
|
| 117 |
|
| 118 |
+
with gr.Blocks(title="SRT Pro (No Refresh)", css=css) as demo:
|
| 119 |
+
gr.Markdown("<h1 style='text-align: center; color: #58a6ff;'>π¬ SMART TRANSLATOR PRO</h1>")
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
+
with gr.Row():
|
| 122 |
+
with gr.Column(scale=1):
|
| 123 |
+
lang_opt = gr.Dropdown(
|
| 124 |
+
["π°π Khmer", "πΊπΈ English", "π¨π³ Chinese", "πΉπ Thai", "π―π΅ Japanese", "π°π· Korean"],
|
| 125 |
+
value="π°π Khmer", label="Target Language (ααΆααΆααααα
)"
|
| 126 |
+
)
|
| 127 |
+
engine_opt = gr.Radio(["π Gemini", "π¦ Llama", "π¦ SEA-LION"], value="π Gemini", label="AI Model (αααΌααα)")
|
| 128 |
+
status_ui = gr.HTML(AIService.get_status_html("π Gemini", "π°π Khmer"))
|
| 129 |
+
input_box = gr.Textbox(label="Original Content (α’αααααααΎα)", lines=12, placeholder="Paste text here...")
|
| 130 |
+
|
| 131 |
+
with gr.Row():
|
| 132 |
+
btn_clear = gr.Button("ποΈ Clear (αααα’αΆα)", variant="secondary", elem_classes="btn-clear")
|
| 133 |
+
btn_trans = gr.Button("β‘ Translate (αααααα)", variant="primary", elem_classes="btn-trans")
|
| 134 |
+
|
| 135 |
+
with gr.Column(scale=1):
|
| 136 |
+
output_box = gr.Textbox(label="Result (αααααα)", lines=23, interactive=False)
|
| 137 |
+
btn_copy = gr.Button("π Copy Result (α
αααα)", elem_classes="btn-copy")
|
| 138 |
+
|
| 139 |
+
# Events: ααααΌαααΆααΆαα·α Refresh UI αα ααΊααααΆααααααααΌαααααααααααΆαααααααα
|
| 140 |
+
btn_trans.click(translator_hub, [input_box, lang_opt, engine_opt], [output_box, status_ui])
|
| 141 |
+
btn_clear.click(lambda: ("", ""), None, [input_box, output_box])
|
| 142 |
+
btn_copy.click(None, output_box, js="(v) => { navigator.clipboard.writeText(v); alert('Copied!'); }")
|
| 143 |
|
| 144 |
+
if __name__ == "__main__":
|
| 145 |
+
demo.launch()
|