import os
import requests
from fastapi import APIRouter
from pydantic import BaseModel
from dotenv import load_dotenv
from fastapi import APIRouter, UploadFile, File, HTTPException
from fastapi.responses import JSONResponse
from dotenv import load_dotenv
from models import *

router = APIRouter()

load_dotenv()
HUGGING_TOKEN = os.environ["HUGGING_TOKEN"]

async def whsiper_to_text(file: UploadFile):
    API_URL = "https://api-inference.huggingface.co/models/openai/whisper-large-v3"
    headers = {"Authorization": f"Bearer {HUGGING_TOKEN}"}
    contents = await file.read()
    response = requests.post(API_URL, headers=headers, data=contents)
    if response.status_code != 200:
        print(f"Error status {response.status_code}")
        return None
    return response.json()

async def blip_image(file: UploadFile):
    API_URL = "https://api-inference.huggingface.co/models/Salesforce/blip-image-captioning-large"
    headers = {"Authorization": f"Bearer {HUGGING_TOKEN}"}
    contents = await file.read()
    response = requests.post(API_URL, headers=headers, data=contents)
    if response.status_code != 200:
        print(f"Error status {response.status_code}")
        return None
    return response.json()

@router.post("/akeno/whsiper")
async def whsiper_new(file: UploadFile = File(...)):
    try:
        response_data = await whsiper_to_text(file)
        if response_data is None:
            raise HTTPException(status_code=400, detail="Failed to process the file")
            
        return JSONResponse(
            status_code=200,
            content={"status": "True", "message": response_data.get("text")}
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")

@router.post("/akeno/blip-image-captioning-large", response_model=SuccessResponse, responses={422: {"model": SuccessResponse}})
async def blip_images(file: UploadFile = File(...)):
    try:
        response_data = await blip_image(file)
        if response_data is None:
            raise HTTPException(status_code=400, detail="Failed to process the file")
            
        return JSONResponse(
            status_code=200,
            content={"status": "True", "message": response_data}
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")