File size: 1,999 Bytes
d33ff1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# from fastapi import FastAPI, File, UploadFile
# from transformers import MarianMTModel, MarianTokenizer

# app = FastAPI()

# # Load the translation model and tokenizer
# model_name = "Helsinki-NLP/opus-mt-de-en"
# model = MarianMTModel.from_pretrained(model_name)
# tokenizer = MarianTokenizer.from_pretrained(model_name)

# @app.get("/")
# def read_root():
#     return {"message": "Welcome to the German to English Translation API!"}

# @app.post("/translate/")
# async def translate_text(text: str):
#     # Perform translation
#     input_text = f"translate German to English: {text}"
    
#     # Tokenize input text
#     input_ids = tokenizer.encode(input_text, return_tensors="pt")
    
#     # Generate translation
#     with torch.no_grad():
#         output_ids = model.generate(input_ids)
    
#     # Decode the output
#     translated_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
    
#     return {"translated_text": translated_text}



from fastapi import FastAPI
from transformers import MarianMTModel, MarianTokenizer
import torch

app = FastAPI()

# Load the translation model and tokenizer
model_name = "Helsinki-NLP/opus-mt-de-en"
model = MarianMTModel.from_pretrained(model_name)
tokenizer = MarianTokenizer.from_pretrained(model_name)

@app.get("/")
def read_root():
    return {"message": "Welcome to the German to English Translation API!"}

@app.post("/translate/")
async def translate_text(input_text: dict):
    # Extract the input text from the JSON payload
    text = input_text.get("text", "")
    
    # Perform translation
    input_text = f"translate German to English: {text}"
    
    # Tokenize input text
    input_ids = tokenizer.encode(input_text, return_tensors="pt")
    
    # Generate translation
    with torch.no_grad():
        output_ids = model.generate(input_ids)
    
    # Decode the output
    translated_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
    
    return {"translated_text": translated_text}