File size: 1,830 Bytes
545c27e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import tempfile
from fastapi import FastAPI, File, UploadFile, Form
from fastapi.responses import JSONResponse
from gradio_client import Client, handle_file
from deep_translator import GoogleTranslator

app = FastAPI()

HF_TOKEN = os.getenv("HF_TOKEN")
if not HF_TOKEN:
    raise ValueError("HF_TOKEN environment variable is not set.")

try:
    client = Client("Luisgust/moondream1", hf_token=HF_TOKEN)
except Exception as e:
    print(f"Failed to initialize Gradio client: {e}")
    raise

@app.post("/get_caption")
async def get_caption(image: UploadFile = File(...), context: str = Form(...)):
    try:
        # Create a temporary file
        with tempfile.NamedTemporaryFile(delete=False) as temp_file:
            # Write the uploaded file contents to the temp file
            contents = await image.read()
            temp_file.write(contents)
            temp_file_path = temp_file.name

        # Use the temporary file path with handle_file or any other processing
        image_data = handle_file(temp_file_path)

        # Call the Gradio API to get the description
        description = client.predict(
            image=image_data,
            question=context,
            api_name="/answer_question"
        )

        # Translate the description to Arabic
        translator = GoogleTranslator(source='auto', target='ar')
        translated_description = translator.translate(description)

        # Return the translated result as a JSON response
        return JSONResponse(content={"caption": translated_description})

    except Exception as e:
        print(f"Error during prediction: {e}")
        return JSONResponse(content={"error": str(e)}, status_code=500)

    finally:
        # Remove the temporary file
        if os.path.exists(temp_file_path):
            os.remove(temp_file_path)