Spaces:
Sleeping
Sleeping
Rename app.py to main.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259import osimport timeimport reimport uuidimport requestsfrom fastapi import FastAPI, Request, HTTPExceptionfrom fastapi.staticfiles import StaticFilesfrom linebot.v3 import WebhookHandlerfrom linebot.v3.messaging import ( Configuration, ApiClient, MessagingApi, ReplyMessageRequest, TextMessage, AudioMessage)from linebot.v3.webhooks import MessageEvent, TextMessageContentfrom linebot.v3.exceptions import InvalidSignatureErrorfrom llama_cpp import Llamafrom huggingface_hub import hf_hub_download
# ================= 🔐 Load Config from ENV =================LINE_ACCESS_TOKEN = os.getenv("LINE_ACCESS_TOKEN")LINE_CHANNEL_SECRET = os.getenv("LINE_CHANNEL_SECRET")ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")ELEVENLABS_VOICE_ID = os.getenv("ELEVENLABS_VOICE_ID", "exsUS4vynmxd379XN4yO")BASE_URL = os.getenv("SPACE_HOST_URL")
# ================= 🧠 Load 2 Models =================print("⏳ Loading Models... (This may take a while)")
# --- Model 1: Isan -> English ---print("📥 Downloading Model 1 (Isan -> English)...")model_path_1 = hf_hub_download( repo_id="watcharabest/Isan-to-Englsish-Llama3.2-3B-IT", filename="llama-3.2-3b-instruct.Q4_K_M.gguf")llm_isan_to_eng = Llama( model_path=model_path_1, n_ctx=1024, n_gpu_layers=0, # CPU only verbose=False)
# --- Model 2: English -> Isan ---print("📥 Downloading Model 2 (English -> Isan)...")model_path_2 = hf_hub_download( repo_id="watcharabest/English-to-Isan-Llama3.2-3B-IT", filename="llama-3.2-3b-instruct.Q4_K_M.gguf")llm_eng_to_isan = Llama( model_path=model_path_2, n_ctx=1024, n_gpu_layers=0, verbose=False)
print("✅ Models Loaded Successfully!")
# ================= Helper Functions =================def is_thai(text): pattern = re.compile(r"[\u0E00-\u0E7F]+") return pattern.search(text) is not None
def clean_model_output(raw_text): if not raw_text: return "" # ตัดส่วนคิด <think>...</think> result = re.sub(r'<think>.*?</think>', '', raw_text, flags=re.DOTALL) result = re.sub(r'<think>.*', '', result, flags=re.DOTALL) stop_words = ["<|im_end|>", "<|im_end|", "<|im_end", "<|endoftext|>", "</s>"] for word in stop_words: if word in result: result = result.split(word)[0] artifacts = ["<|im_start|>", "assistant", "user", "model"] for art in artifacts: result = result.replace(art, "") return result.strip().strip('"').strip("'")
def generate_audio_elevenlabs(text): if not ELEVENLABS_API_KEY: print("⚠️ No ElevenLabs API Key provided.") return None, 0 url = f"https://api.elevenlabs.io/v1/text-to-speech/{ELEVENLABS_VOICE_ID}?output_format=mp3_44100_128" headers = {"xi-api-key": ELEVENLABS_API_KEY, "Content-Type": "application/json"} payload = { "text": text, "model_id": "eleven_turbo_v2_5", "voice_settings": {"stability": 0.5, "similarity_boost": 0.75} }
try: response = requests.post(url, json=payload, headers=headers, timeout=30) if response.status_code == 200: filename = f"{uuid.uuid4()}.mp3" filepath = os.path.join("static", filename) with open(filepath, "wb") as f: f.write(response.content) file_size_bytes = os.path.getsize(filepath) duration_ms = int((file_size_bytes * 8 / 128000) * 1000) return f"static/{filename}", duration_ms else: print(f"❌ ElevenLabs Error: {response.text}") return None, 0 except Exception as e: print(f"❌ ElevenLabs Exception: {e}") return None, 0
# ================= Setup Server =================app = FastAPI()
os.makedirs("static", exist_ok=True)app.mount("/static", StaticFiles(directory="static"), name="static")
configuration = Configuration(access_token=LINE_ACCESS_TOKEN)handler = WebhookHandler(LINE_CHANNEL_SECRET)
@app.get("/")def home(): return {"status": "Running", "service": "Isan Translator Bot"}
@app.post("/callback")async def callback(request: Request): signature = request.headers.get('X-Line-Signature', '') body = await request.body() body_str = body.decode('utf-8') try: handler.handle(body_str, signature) except InvalidSignatureError: raise HTTPException(status_code=400, detail="Invalid signature") return "OK"
@handler.add(MessageEvent, message=TextMessageContent)def handle_message(event): user_msg = event.message.text.strip() if not user_msg: return
print(f"\n📩 Message: {user_msg}") start_time = time.time()
try: # --- Logic เลือกโมเดล --- if is_thai(user_msg): # Thai/Isan -> English prompt = f"""<|im_start|>systemYou are a precise translator. Translate Isan (Northeastern Thai) to English.Rules:1. Translate directly and concisely2. Do not explain or add commentary3. Match the length and tone of the input4. For casual phrases, use casual English<|im_end|><|im_start|>userแปลเป็นอังกฤษ: สบายดีบ่<|im_end|><|im_start|>assistantHow are you?<|im_end|><|im_start|>userแปลเป็นอังกฤษ: เป็นจั่งได๋<|im_end|><|im_start|>assistantWhat's up?<|im_end|><|im_start|>userแปลเป็นอังกฤษ: กินข้าวแล้วบ่<|im_end|><|im_start|>assistantHave you eaten?<|im_end|><|im_start|>userแปลเป็นอังกฤษ: {user_msg}<|im_end|><|im_start|>assistant""" selected_model = llm_isan_to_eng model_name = "Isan→English" gen_kwargs = { "max_tokens": 256, "temperature": 0.1, "top_p": 0.9, "repeat_penalty": 1.2, "stop": ["<|im_end|>", "<|im_start|>", "แปล", "\n", "\n\n"] } else: # English -> Isan prompt = f"""<|im_start|>systemYou are an expert translator from English to Isan (Northeastern Thai dialect).Your translations should be:1. Natural and authentic Isan language2. Appropriate for casual conversation3. Emotionally resonant while preserving original meaning4. Free from Central Thai vocabulary5. Concise and smooth<|im_end|><|im_start|>userTranslate to Isan: It's very delicious.<|im_end|><|im_start|>assistantแซ่บอีหลี<|im_end|><|im_start|>userTranslate to Isan: I don't know.<|im_end|><|im_start|>assistantบ่ฮู้<|im_end|><|im_start|>userTranslate to Isan: How are you?<|im_end|><|im_start|>assistantสบายดีบ่<|im_end|><|im_start|>userTranslate to Isan: {user_msg}<|im_end|><|im_start|>assistant""" selected_model = llm_eng_to_isan model_name = "English→Isan" gen_kwargs = { "max_tokens": 512, "temperature": 0.1, "top_p": 0.9, "repeat_penalty": 1.2, "stop": ["<|im_end|>", "<|im_start|>", "แปล", "\n", "\n\n"] }
# --- Generate --- output = selected_model( prompt, echo=False, **gen_kwargs ) result_text = clean_model_output(output['choices'][0]['text']) if not result_text or len(result_text) < 2: result_text = "ขอโทดน้อ บ่สามาดแปลได้" if is_thai(user_msg) else "Sorry, translation failed"
elapsed = time.time() - start_time final_reply = f"{result_text}\n\n⏱ {elapsed:.1f}s | {model_name}" messages_to_send = [TextMessage(text=final_reply)]
# --- Audio Logic --- if BASE_URL and not is_thai(result_text): audio_path, duration_ms = generate_audio_elevenlabs(result_text) if audio_path and duration_ms > 0: clean_base_url = BASE_URL.rstrip("/") audio_url = f"{clean_base_url}/{audio_path}" print(f"🔗 Audio URL: {audio_url}") messages_to_send.append( AudioMessage( original_content_url=audio_url, duration=duration_ms ) )
# Send Reply with ApiClient(configuration) as api_client: line_bot_api = MessagingApi(api_client) line_bot_api.reply_message( ReplyMessageRequest( reply_token=event.reply_token, messages=messages_to_send ) )
except Exception as e: print(f"❌ Error: {e}") import traceback traceback.print_exc()app.pyDeleted
main.pyAdded+259