vrindagopinath commited on
Commit
18f7ce1
·
verified ·
1 Parent(s): 9925ecb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -15
app.py CHANGED
@@ -1,12 +1,21 @@
1
  import os
2
  import io
3
- from flask import Flask, request, jsonify
4
- from flask_cors import CORS # Add CORS support
5
  from PIL import Image
6
  import google.generativeai as genai
 
7
 
8
- app = Flask(__name__)
9
- CORS(app) # Enable CORS for all routes
 
 
 
 
 
 
 
 
10
 
11
  # Configure Gemini API
12
  genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
@@ -37,23 +46,23 @@ def extract_mixed_text(image):
37
  return filtered_text.strip() if filtered_text.strip() else "No valid text detected."
38
 
39
  except Exception as e:
40
- return f"An error occurred: {str(e)}"
41
 
42
- @app.route("/extract_text", methods=["POST"])
43
- def extract_text():
44
  """API Endpoint for text extraction."""
45
  try:
46
- if "image" not in request.files:
47
- return jsonify({"error": "No image uploaded"}), 400
 
48
 
49
- image_file = request.files["image"]
50
- image = Image.open(io.BytesIO(image_file.read()))
51
 
52
- extracted_text = extract_mixed_text(image)
53
- return jsonify({"extracted_text": extracted_text})
54
 
55
  except Exception as e:
56
- return jsonify({"error": str(e)}), 500
57
 
58
  if __name__ == "__main__":
59
- app.run(host="0.0.0.0", port=7860, debug=True)
 
1
  import os
2
  import io
3
+ from fastapi import FastAPI, File, UploadFile, HTTPException
4
+ from fastapi.middleware.cors import CORSMiddleware
5
  from PIL import Image
6
  import google.generativeai as genai
7
+ import uvicorn
8
 
9
+ app = FastAPI()
10
+
11
+ # CORS Middleware
12
+ app.add_middleware(
13
+ CORSMiddleware,
14
+ allow_origins=["*"], # Allows all origins
15
+ allow_credentials=True,
16
+ allow_methods=["*"], # Allows all methods
17
+ allow_headers=["*"], # Allows all headers
18
+ )
19
 
20
  # Configure Gemini API
21
  genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
 
46
  return filtered_text.strip() if filtered_text.strip() else "No valid text detected."
47
 
48
  except Exception as e:
49
+ raise HTTPException(status_code=500, detail=f"Error extracting text: {str(e)}")
50
 
51
+ @app.post("/extract_text")
52
+ async def extract_text(image: UploadFile = File(...)):
53
  """API Endpoint for text extraction."""
54
  try:
55
+ # Read the image file
56
+ image_contents = await image.read()
57
+ pil_image = Image.open(io.BytesIO(image_contents))
58
 
59
+ # Extract text
60
+ extracted_text = extract_mixed_text(pil_image)
61
 
62
+ return {"extracted_text": extracted_text}
 
63
 
64
  except Exception as e:
65
+ raise HTTPException(status_code=400, detail=str(e))
66
 
67
  if __name__ == "__main__":
68
+ uvicorn.run(app, host="0.0.0.0", port=7860)