-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
51 lines (36 loc) · 1.77 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from transformers import pipeline
import httpx
import streamlit as st
app = FastAPI()
class TranslationRequest(BaseModel):
text: str
class TranslationResponse(BaseModel):
translation: str
translator = pipeline("translation_ru_to_en", model="Helsinki-NLP/opus-mt-ru-en")
@app.post("/translate", response_model=TranslationResponse)
async def translate_text(request: TranslationRequest):
try:
translated_text = (
translator(request.text, max_length=50)
[0]['translation_text']
)
return TranslationResponse(translation=translated_text)
except Exception as Ex:
raise HTTPException(status_code=500, detail=f"Error during translation: {str(Ex)}")
st.title("Translation App")
text_to_translate = st.text_area("Enter text for translation:", "Привет, как дела?")
if st.button("Translate"):
translation_request = TranslationRequest(text=text_to_translate)
try:
with httpx.Client() as client:
response = client.post("http://127.0.0.1:8000/translate", json=translation_request.dict())
translation_result = response.json()["translation"]
st.success(f"Translation: {translation_result}")
except Exception as e:
st.error(f"Error during translation: {str(e)}")
# Для запуска АПИ и ВЕБ интерфейса нужно:
# В командной строке запустить апи
# "uvicorn task3:app --reload --port 8000" - команда разворачивает на адрессе http://127.0.0.1:8000/ АПИ
# В другой командной строке запустить веб "streamlit run task3.py" - команда запускает веб интерфейс