Spaces:
Paused
Paused
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import base64
|
| 4 |
+
import httpx
|
| 5 |
+
import google.generativeai as genai
|
| 6 |
+
|
| 7 |
+
from fastapi import FastAPI, HTTPException
|
| 8 |
+
from pydantic import BaseModel, HttpUrl
|
| 9 |
+
|
| 10 |
+
app = FastAPI(title="Business Card Analyzer")
|
| 11 |
+
|
| 12 |
+
# Input model for the API
|
| 13 |
+
class ImageRequest(BaseModel):
|
| 14 |
+
image_url: HttpUrl
|
| 15 |
+
|
| 16 |
+
# Configure the Google Generative AI client using an environment variable.
|
| 17 |
+
# Make sure to set the GOOGLE_API_KEY variable when running the app.
|
| 18 |
+
GOOGLE_API_KEY = "AIzaSyDcYyq3w21iwipYn17wCAQo3AYWhUIGDSI"
|
| 19 |
+
if not GOOGLE_API_KEY:
|
| 20 |
+
raise Exception("Please set the GOOGLE_API_KEY environment variable.")
|
| 21 |
+
|
| 22 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
| 23 |
+
|
| 24 |
+
# Define the prompt to instruct the model.
|
| 25 |
+
PROMPT = """
|
| 26 |
+
Analyze the business card and extract the following information in JSON format:
|
| 27 |
+
{
|
| 28 |
+
"name": "Full Name",
|
| 29 |
+
"mobile_number": "Mobile Number",
|
| 30 |
+
"company_name": "Company Name",
|
| 31 |
+
"email": "Email Address",
|
| 32 |
+
"job_title": "Job Title",
|
| 33 |
+
"address": "Address",
|
| 34 |
+
"website": "Website URL"
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
Ensure that the response is strictly in JSON format and includes all the fields mentioned above. If any information is missing or unclear, set the corresponding field to null.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
@app.post("/analyze", summary="Analyze a business card image")
|
| 41 |
+
async def analyze_business_card(request: ImageRequest):
|
| 42 |
+
# Fetch the image from the provided URL
|
| 43 |
+
try:
|
| 44 |
+
async with httpx.AsyncClient() as client:
|
| 45 |
+
response = await client.get(str(request.image_url))
|
| 46 |
+
response.raise_for_status()
|
| 47 |
+
img_bytes = response.content
|
| 48 |
+
except Exception as e:
|
| 49 |
+
raise HTTPException(status_code=400, detail=f"Failed to fetch image: {e}")
|
| 50 |
+
|
| 51 |
+
# Encode the image in base64
|
| 52 |
+
encoded_image = base64.b64encode(img_bytes).decode("utf-8")
|
| 53 |
+
|
| 54 |
+
# Create an instance of the Gemini model
|
| 55 |
+
model = genai.GenerativeModel(model_name="gemini-1.5-pro")
|
| 56 |
+
|
| 57 |
+
# Call the model and process its response
|
| 58 |
+
try:
|
| 59 |
+
result = model.generate_content([
|
| 60 |
+
{
|
| 61 |
+
"mime_type": "image/jpeg",
|
| 62 |
+
"data": encoded_image,
|
| 63 |
+
},
|
| 64 |
+
PROMPT,
|
| 65 |
+
])
|
| 66 |
+
# Get the raw text response
|
| 67 |
+
raw = result.text.strip()
|
| 68 |
+
|
| 69 |
+
# Remove markdown formatting if present (i.e. ```json ... ```)
|
| 70 |
+
if raw.startswith("```"):
|
| 71 |
+
lines = raw.splitlines()
|
| 72 |
+
if lines[0].startswith("```"):
|
| 73 |
+
lines = lines[1:]
|
| 74 |
+
if lines and lines[-1].startswith("```"):
|
| 75 |
+
lines = lines[:-1]
|
| 76 |
+
raw = "\n".join(lines).strip()
|
| 77 |
+
|
| 78 |
+
data = json.loads(raw)
|
| 79 |
+
except json.JSONDecodeError as jde:
|
| 80 |
+
raise HTTPException(status_code=500, detail=f"JSON decoding error: {jde}. Response text was: {raw}")
|
| 81 |
+
except Exception as e:
|
| 82 |
+
raise HTTPException(status_code=500, detail=f"An error occurred while processing the image: {e}")
|
| 83 |
+
|
| 84 |
+
return data
|
| 85 |
+
|
| 86 |
+
if __name__ == "__main__":
|
| 87 |
+
import uvicorn
|
| 88 |
+
|
| 89 |
+
uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True)
|