-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslation.py
79 lines (59 loc) · 2.44 KB
/
translation.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import StreamingResponse
from google.cloud import translate
import uvicorn
import tempfile
import os
import mimetypes
## doesnt work because of google api :(
app = FastAPI()
@app.post("/translate-pdf/")
async def translate_pdf(
file: UploadFile = File(...),
source_language: str = "en",
target_language: str = "pt"
):
try:
if file.content_type != 'application/pdf' and not file.filename.endswith('.pdf'):
raise HTTPException(status_code=400, detail="O arquivo enviado não é um PDF.")
# Salvar o arquivo
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf_file:
temp_pdf_file.write(await file.read())
temp_pdf_file_path = temp_pdf_file.name
client = translate.TranslationServiceClient()
project_id = "seu-id-do-projeto"
location = "global"
parent = f"projects/{project_id}/locations/{location}"
# Ler o conteúdo do arquivo PDF
with open(temp_pdf_file_path, 'rb') as document:
content = document.read()
document_input_config = {
"content": content,
"mime_type": "application/pdf",
}
# Fazer a solicitação de tradução
response = client.translate_document(
request={
"parent": parent,
"source_language_code": source_language,
"target_language_code": target_language,
"document_input_config": document_input_config,
}
)
translated_document = response.document_translation.byte_stream_outputs[0]
mime_type, _ = mimetypes.guess_type(file.filename)
# Retornar o arquivo PDF traduzido como uma resposta
return StreamingResponse(
content=iter([translated_document]),
media_type=mime_type,
headers={"Content-Disposition": f"attachment; filename=translated_{file.filename}"}
)
except Exception as e:
if 'temp_pdf_file_path' in locals() and os.path.exists(temp_pdf_file_path):
os.remove(temp_pdf_file_path)
raise HTTPException(status_code=500, detail=str(e))
finally:
if 'temp_pdf_file_path' in locals() and os.path.exists(temp_pdf_file_path):
os.remove(temp_pdf_file_path)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=9000)