Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from fastapi import FastAPI
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 5 |
+
import uvicorn
|
| 6 |
+
|
| 7 |
+
app = FastAPI()
|
| 8 |
+
|
| 9 |
+
MODEL_ID = "Qwen/Qwen1.5-1.8B-Chat"
|
| 10 |
+
|
| 11 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 12 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 13 |
+
MODEL_ID,
|
| 14 |
+
torch_dtype=torch.bfloat16,
|
| 15 |
+
device_map="auto",
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
pipe = pipeline(
|
| 19 |
+
"text-generation",
|
| 20 |
+
model=model,
|
| 21 |
+
tokenizer=tokenizer,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
class TranslationRequest(BaseModel):
|
| 25 |
+
text: str
|
| 26 |
+
target_lang: str
|
| 27 |
+
|
| 28 |
+
@app.post("/translate")
|
| 29 |
+
async def translate(request: TranslationRequest):
|
| 30 |
+
korean_text = request.text
|
| 31 |
+
target_lang = request.target_lang
|
| 32 |
+
|
| 33 |
+
if target_lang == 'english':
|
| 34 |
+
prompt = f"Translate the following Korean sentence into natural, everyday English. Provide only the translated sentence, without any additional explanations or quotation marks.\n\nKorean: \"{korean_text}\"\n\nEnglish:"
|
| 35 |
+
elif target_lang == 'japanese':
|
| 36 |
+
prompt = f"Translate the following Korean sentence into natural, everyday Japanese. Provide only the translated sentence, without any additional explanations or quotation marks.\n\nKorean: \"{korean_text}\"\n\nJapanese:"
|
| 37 |
+
else:
|
| 38 |
+
return {"error": "Invalid target language"}
|
| 39 |
+
|
| 40 |
+
messages = [
|
| 41 |
+
{"role": "user", "content": prompt}
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
outputs = pipe(
|
| 45 |
+
messages,
|
| 46 |
+
max_new_tokens=150,
|
| 47 |
+
do_sample=True,
|
| 48 |
+
temperature=0.7,
|
| 49 |
+
top_k=50,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
generated_text = outputs[0]["generated_text"]
|
| 53 |
+
translated_text = generated_text.split("assistant\n")[-1].strip()
|
| 54 |
+
|
| 55 |
+
return {"translated_text": translated_text}
|
| 56 |
+
|
| 57 |
+
@app.get("/")
|
| 58 |
+
def read_root():
|
| 59 |
+
return {"message": "Translation API is running"}
|