Spaces:
Sleeping
Sleeping
Create main.py
Browse files
main.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
mport os
|
2 |
+
|
3 |
+
os.system("sudo apt-get install xclip")
|
4 |
+
|
5 |
+
import nltk
|
6 |
+
import pyclip
|
7 |
+
import pytesseract
|
8 |
+
from nltk.tokenize import sent_tokenize
|
9 |
+
from transformers import MarianMTModel, MarianTokenizer
|
10 |
+
# Newly added below
|
11 |
+
from fastapi import FastAPI, File, UploadFile, Body, Depends, HTTPException
|
12 |
+
from fastapi.security.api_key import APIKeyHeader
|
13 |
+
from typing import Optional
|
14 |
+
from fastapi.encoders import jsonable_encoder
|
15 |
+
|
16 |
+
API_KEY = os.environ.get("API_KEY")
|
17 |
+
|
18 |
+
app = FastAPI()
|
19 |
+
api_key_header = APIKeyHeader(name="api_key", auto_error=False)
|
20 |
+
|
21 |
+
def get_api_key(api_key: Optional[str] = Depends(api_key_header)):
|
22 |
+
if api_key is None or api_key != API_KEY:
|
23 |
+
raise HTTPException(status_code=401, detail="Unauthorized access")
|
24 |
+
return api_key
|
25 |
+
|
26 |
+
@app.post("/api/ocr", response_model=dict)
|
27 |
+
async def ocr(
|
28 |
+
api_key: str = Depends(get_api_key),
|
29 |
+
image: UploadFile = File(...),
|
30 |
+
languages: list = Body(["eng"])
|
31 |
+
):
|
32 |
+
# if api_key != API_KEY:
|
33 |
+
# return {"error": "Invalid API key"}, 401
|
34 |
+
|
35 |
+
try:
|
36 |
+
text = image_to_string(await image.read(), lang="+".join(languages))
|
37 |
+
except Exception as e:
|
38 |
+
return {"error": str(e)}, 500
|
39 |
+
|
40 |
+
return jsonable_encoder({"text": text})
|
41 |
+
|
42 |
+
|
43 |
+
@app.post("/api/translate", response_model=dict)
|
44 |
+
async def translate(
|
45 |
+
api_key: str = Depends(get_api_key),
|
46 |
+
text: str = Body(...),
|
47 |
+
src: str = "en",
|
48 |
+
trg: str = "zh",
|
49 |
+
):
|
50 |
+
# if api_key != API_KEY:
|
51 |
+
# return {"error": "Invalid API key"}, 401
|
52 |
+
|
53 |
+
tokenizer, model = get_model(src, trg)
|
54 |
+
|
55 |
+
translated_text = ""
|
56 |
+
for sentence in sent_tokenize(text):
|
57 |
+
translated_sub = model.generate(**tokenizer(sentence, return_tensors="pt"))[0]
|
58 |
+
translated_text += tokenizer.decode(translated_sub, skip_special_tokens=True) + "\n"
|
59 |
+
|
60 |
+
return jsonable_encoder({"translated_text": translated_text})
|
61 |
+
|
62 |
+
|
63 |
+
def get_model(src: str, trg: str):
|
64 |
+
model_name = f"Helsinki-NLP/opus-mt-{src}-{trg}"
|
65 |
+
tokenizer = MarianTokenizer.from_pretrained(model_name)
|
66 |
+
model = MarianMTModel.from_pretrained(model_name)
|
67 |
+
return tokenizer, model
|