test-api / app.py
LalitMahale
model name and new api added
e1d7951
raw
history blame
3 kB
from fastapi import FastAPI, HTTPException,UploadFile,File
from pydantic import BaseModel
from deep_translator import GoogleTranslator
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import os
from main import process,audio_process
from dotenv import load_dotenv
import base64
from pathlib import Path
load_dotenv()
# Create the FastAPI app instance
os.makedirs("/tmp/huggingface_cache", exist_ok=True)
os.environ["HF_HOME"] = "/tmp/huggingface_cache"
app = FastAPI()
# Allow all CORS (for local testing)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Root endpoint
@app.get("/")
async def home():
return {"message": "Testing_api"}
# Token verification function
def verify_token(token: str):
if token != os.getenv("TOKEN"):
raise HTTPException(status_code=401, detail="Token not matched")
# Translate endpoint that accepts a query parameter 'text'
@app.get("/translate")
async def translate(text: str = "", token: str = ""):
if not text or not token:
raise HTTPException(status_code=400, detail="No text or token provided")
verify_token(token)
translator = GoogleTranslator(source="auto", target="mr")
result = translator.translate(text)
return {"result": result}
@app.get("/chatbot")
async def chatbot(text: str = "", token: str = ""):
if not text or not token:
raise HTTPException(status_code=400, detail="No text provided")
verify_token(token)
result = process(user_query=text)
return {"result": result}
@app.post("/audio_chat")
async def audio_chat(audio: UploadFile = File(...), token: str = ""):
if not audio or not token:
raise HTTPException(status_code=400, detail="No audio file provided")
verify_token(token)
try:
result = audio_process(audio.file) # Replace with actual audio processing logic
return {"result": result}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
UPLOAD_DIR = "uploads"
Path(UPLOAD_DIR).mkdir(exist_ok=True)
# Request model
class FileUploadRequest(BaseModel):
filename: str
content_type: str
base64_file: str
@app.post("/summarizer")
async def upload_base64(file_data: FileUploadRequest):
try:
print(file_data.filename)
file_path = os.path.join(UPLOAD_DIR, file_data.filename)
# Decode and save file
with open(file_path, "wb") as f:
f.write(base64.b64decode(file_data.base64_file))
# Simulate processing
extracted_text = f"Saved file: {file_path}\nContent-Type: {file_data.content_type}\n"
extracted_text += f"(First 100 bytes shown)\n\n"
with open(file_path, "rb") as f:
extracted_text += repr(f.read(100))
return {"text": extracted_text}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))