Spaces:
Running
Running
lewiskimaru
commited on
Commit
•
5aa78f4
1
Parent(s):
e81d99c
Update main.py
Browse files
main.py
CHANGED
@@ -1,26 +1,125 @@
|
|
1 |
'''
|
2 |
Created By Lewis Kamau Kimaru
|
3 |
-
Sema translator
|
4 |
January 2024
|
5 |
Docker deployment
|
6 |
'''
|
7 |
|
8 |
-
from fastapi import FastAPI, HTTPException, Request
|
9 |
from fastapi.middleware.cors import CORSMiddleware
|
10 |
from fastapi.responses import HTMLResponse
|
11 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
import ctranslate2
|
13 |
import sentencepiece as spm
|
14 |
import fasttext
|
15 |
-
|
16 |
import pytz
|
17 |
from datetime import datetime
|
18 |
import os
|
19 |
|
20 |
app = FastAPI()
|
21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
fasttext.FastText.eprint = lambda x: None
|
23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
# Get time of request
|
25 |
|
26 |
def get_time():
|
@@ -111,23 +210,12 @@ def translate_enter(userinput: str, source_lang: str, target_lang: str):
|
|
111 |
# Return the source language and the translated text
|
112 |
return translations_desubword[0]
|
113 |
|
|
|
|
|
|
|
|
|
114 |
|
115 |
-
|
116 |
-
async def read_root():
|
117 |
-
gradio_interface = """
|
118 |
-
<html>
|
119 |
-
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0">
|
120 |
-
<head>
|
121 |
-
<title>Sema</title>
|
122 |
-
</head>
|
123 |
-
<frameset>
|
124 |
-
<frame src=https://kamau1-semaapi-frontend.hf.space/?embedded=true'>
|
125 |
-
</frameset>
|
126 |
-
</html>
|
127 |
-
"""
|
128 |
-
return HTMLResponse(content=gradio_interface)
|
129 |
-
|
130 |
-
|
131 |
@app.post("/translate_detect/")
|
132 |
async def translate_detect_endpoint(request: Request):
|
133 |
datad = await request.json()
|
|
|
1 |
'''
|
2 |
Created By Lewis Kamau Kimaru
|
3 |
+
Sema translator fastapi implementation
|
4 |
January 2024
|
5 |
Docker deployment
|
6 |
'''
|
7 |
|
8 |
+
from fastapi import FastAPI, HTTPException, Request, Depends
|
9 |
from fastapi.middleware.cors import CORSMiddleware
|
10 |
from fastapi.responses import HTMLResponse
|
11 |
+
import uvicorn
|
12 |
+
|
13 |
+
from pydantic import BaseModel
|
14 |
+
from pymongo import MongoClient
|
15 |
+
import jwt
|
16 |
+
from jwt import encode as jwt_encode
|
17 |
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
18 |
+
from bson import ObjectId
|
19 |
+
|
20 |
import ctranslate2
|
21 |
import sentencepiece as spm
|
22 |
import fasttext
|
23 |
+
|
24 |
import pytz
|
25 |
from datetime import datetime
|
26 |
import os
|
27 |
|
28 |
app = FastAPI()
|
29 |
|
30 |
+
origins = ["*"]
|
31 |
+
|
32 |
+
app.add_middleware(
|
33 |
+
CORSMiddleware,
|
34 |
+
allow_origins=origins,
|
35 |
+
allow_credentials=False,
|
36 |
+
allow_methods=["*"],
|
37 |
+
allow_headers=["*"],
|
38 |
+
)
|
39 |
+
|
40 |
fasttext.FastText.eprint = lambda x: None
|
41 |
|
42 |
+
# User interface
|
43 |
+
templates_folder = os.path.join(os.path.dirname(__file__), "templates")
|
44 |
+
|
45 |
+
# Authentication
|
46 |
+
class User(BaseModel):
|
47 |
+
username: str = None # Make the username field optional
|
48 |
+
email: str
|
49 |
+
password: str
|
50 |
+
|
51 |
+
# Connect to the MongoDB database
|
52 |
+
client = MongoClient("mongodb://localhost:27017")
|
53 |
+
db = client["mydatabase"]
|
54 |
+
users_collection = db["users"]
|
55 |
+
|
56 |
+
# Secret key for signing the token
|
57 |
+
SECRET_KEY = "helloworld"
|
58 |
+
security = HTTPBearer()
|
59 |
+
|
60 |
+
#Implement the login route:
|
61 |
+
|
62 |
+
@app.post("/login")
|
63 |
+
def login(user: User):
|
64 |
+
# Check if user exists in the database
|
65 |
+
user_data = users_collection.find_one(
|
66 |
+
{"email": user.email, "password": user.password}
|
67 |
+
)
|
68 |
+
if user_data:
|
69 |
+
# Generate a token
|
70 |
+
token = generate_token(user.email)
|
71 |
+
# Convert ObjectId to string
|
72 |
+
user_data["_id"] = str(user_data["_id"])
|
73 |
+
# Store user details and token in local storage
|
74 |
+
user_data["token"] = token
|
75 |
+
return user_data
|
76 |
+
return {"message": "Invalid email or password"}
|
77 |
+
|
78 |
+
#Implement the registration route:
|
79 |
+
@app.post("/register")
|
80 |
+
def register(user: User):
|
81 |
+
# Check if user already exists in the database
|
82 |
+
existing_user = users_collection.find_one({"email": user.email})
|
83 |
+
if existing_user:
|
84 |
+
return {"message": "User already exists"}
|
85 |
+
#Insert the new user into the database
|
86 |
+
user_dict = user.dict()
|
87 |
+
users_collection.insert_one(user_dict)
|
88 |
+
# Generate a token
|
89 |
+
token = generate_token(user.email)
|
90 |
+
# Convert ObjectId to string
|
91 |
+
user_dict["_id"] = str(user_dict["_id"])
|
92 |
+
# Store user details and token in local storage
|
93 |
+
user_dict["token"] = token
|
94 |
+
return user_dict
|
95 |
+
|
96 |
+
|
97 |
+
#Implement the `/api/user` route to fetch user data based on the JWT token
|
98 |
+
@app.get("/api/user")
|
99 |
+
def get_user(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
100 |
+
# Extract the token from the Authorization header
|
101 |
+
token = credentials.credentials
|
102 |
+
# Authenticate and retrieve the user data from the database based on the token
|
103 |
+
# Here, you would implement the authentication logic and fetch user details
|
104 |
+
# based on the token from the database or any other authentication mechanism
|
105 |
+
# For demonstration purposes, assuming the user data is stored in local storage
|
106 |
+
# Note: Local storage is not accessible from server-side code
|
107 |
+
# This is just a placeholder to demonstrate the concept
|
108 |
+
user_data = {
|
109 |
+
"username": "John Doe",
|
110 |
+
"email": "johndoe@example.com"
|
111 |
+
}
|
112 |
+
if user_data["username"] and user_data["email"]:
|
113 |
+
return user_data
|
114 |
+
raise HTTPException(status_code=401, detail="Invalid token")
|
115 |
+
|
116 |
+
#Define a helper function to generate a JWT token
|
117 |
+
def generate_token(email: str) -> str:
|
118 |
+
payload = {"email": email}
|
119 |
+
token = jwt_encode(payload, SECRET_KEY, algorithm="HS256")
|
120 |
+
return token
|
121 |
+
|
122 |
+
|
123 |
# Get time of request
|
124 |
|
125 |
def get_time():
|
|
|
210 |
# Return the source language and the translated text
|
211 |
return translations_desubword[0]
|
212 |
|
213 |
+
|
214 |
+
@app.get("/", response_class=HTMLResponse)
|
215 |
+
async def read_root(request: Request):
|
216 |
+
return HTMLResponse(content=open(os.path.join(templates_folder, "translator.html"), "r").read(), status_code=200)
|
217 |
|
218 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
219 |
@app.post("/translate_detect/")
|
220 |
async def translate_detect_endpoint(request: Request):
|
221 |
datad = await request.json()
|