File size: 2,207 Bytes
cc91688
 
 
 
 
77ed5d2
cc91688
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77ed5d2
 
 
cc91688
 
 
 
 
 
77ed5d2
cc91688
 
 
 
 
 
 
77ed5d2
cc91688
77ed5d2
cc91688
 
 
 
 
77ed5d2
 
cc91688
 
 
 
 
 
 
 
 
 
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from fastapi import FastAPI, UploadFile, Query, HTTPException
from starlette.responses import RedirectResponse
from typing import Union, List
from pydantic import BaseModel
from translator import ServerTranslator
from LanguageTranslator.utils.constants import set_api_key
import json
import uvicorn

app = FastAPI()


# Define a data model for the input
class TranslationInput(BaseModel):
    text: str
    dest_language: str


class TranslationResult(BaseModel):
    text: Union[str, List[str]]
    language_translation: str


@app.get("/", include_in_schema=False)
async def index():
    return RedirectResponse(url="/docs")


@app.post("/translate", response_model=TranslationResult)
async def run_translation_manual(
        text: str = Query(..., description="Input text to translate"),
        dest_language: str = Query(..., description="Destination language"),
        api_key: str = Query(..., description="OpenAI API Key")):
    set_api_key(api_key)
    # Splitting the input text
    text = text.split(',')
    # Creating and processing the translator
    processing_language = ServerTranslator.language_translator(
        text=text,
        dest_language=dest_language,
        openai_api_key=api_key
    )
    # Getting the translated result
    result_response = processing_language.translate()
    return result_response


@app.post("/translate_json", response_model=TranslationResult)
async def run_translation_auto(json_file: UploadFile,  api_key: str = Query(..., description="OpenAI API Key")):
    try:
        set_api_key(api_key)
        # Reading the JSON content from the file
        json_content = await json_file.read()
        json_data = json.loads(json_content.decode("utf-8"))
        # Creating and processing the translator
        processing_language = ServerTranslator.language_translator(
            json_data,
            openai_api_key=api_key
        )
        # Getting the translated result
        result_response = processing_language.translate()
        return result_response
    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="Invalid JSON input")


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)