Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,154 +1,186 @@
|
|
| 1 |
-
import os
|
| 2 |
-
from flask import Flask, render_template, request, jsonify
|
| 3 |
-
import google.generativeai as genai
|
| 4 |
-
from PIL import Image
|
| 5 |
-
from dotenv import load_dotenv
|
| 6 |
-
import time
|
| 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 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
#
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
file
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
})
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from flask import Flask, render_template, request, jsonify
|
| 3 |
+
import google.generativeai as genai
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
import time
|
| 7 |
+
import traceback
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
# Load environment variables
|
| 11 |
+
load_dotenv()
|
| 12 |
+
|
| 13 |
+
# Configure Gemini API with key from environment variable
|
| 14 |
+
api_key = os.getenv("GEMINI_API_KEY", "AIzaSyB0IOx76FydAk4wabMz1juzzHF5oBiHW64")
|
| 15 |
+
if api_key == "AIzaSyB0IOx76FydAk4wabMz1juzzHF5oBiHW64":
|
| 16 |
+
print("WARNING: Using hardcoded API key. Set GEMINI_API_KEY environment variable instead.")
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
genai.configure(api_key=api_key)
|
| 20 |
+
print("Successfully configured Gemini API with provided key")
|
| 21 |
+
except Exception as e:
|
| 22 |
+
print(f"Error configuring Gemini API: {str(e)}")
|
| 23 |
+
print(traceback.format_exc())
|
| 24 |
+
|
| 25 |
+
# Initialize Flask app
|
| 26 |
+
app = Flask(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def extract_text_with_gemini(image_path):
|
| 30 |
+
"""Extract text from image using Gemini Vision model"""
|
| 31 |
+
max_retries = 3
|
| 32 |
+
retry_delay = 2
|
| 33 |
+
|
| 34 |
+
for attempt in range(max_retries):
|
| 35 |
+
try:
|
| 36 |
+
print(f"Attempt {attempt + 1} to extract text using Gemini...")
|
| 37 |
+
# Initialize Gemini Pro Vision model
|
| 38 |
+
model = genai.GenerativeModel('gemini-1.0-pro-vision') # Fallback to a stable model
|
| 39 |
+
|
| 40 |
+
# Load the image
|
| 41 |
+
with Image.open(image_path) as img:
|
| 42 |
+
print(f"Image loaded from {image_path} (Size: {img.size}, Format: {img.format})")
|
| 43 |
+
|
| 44 |
+
# Create prompt for text extraction
|
| 45 |
+
prompt = "Extract all the text from this image. Return only the extracted text, nothing else."
|
| 46 |
+
|
| 47 |
+
# Generate response with image
|
| 48 |
+
print("Sending request to Gemini API for text extraction...")
|
| 49 |
+
response = model.generate_content([prompt, img])
|
| 50 |
+
|
| 51 |
+
# Validate response
|
| 52 |
+
if not response or not hasattr(response, 'text') or not response.text:
|
| 53 |
+
raise ValueError("Received empty response from Gemini API")
|
| 54 |
+
|
| 55 |
+
extracted_text = response.text.strip()
|
| 56 |
+
print(f"Successfully extracted text (length: {len(extracted_text)})")
|
| 57 |
+
return extracted_text
|
| 58 |
+
except Exception as e:
|
| 59 |
+
print(f"Attempt {attempt + 1} failed: {str(e)}")
|
| 60 |
+
print(traceback.format_exc())
|
| 61 |
+
if attempt < max_retries - 1:
|
| 62 |
+
print(f"Retrying in {retry_delay} seconds...")
|
| 63 |
+
time.sleep(retry_delay)
|
| 64 |
+
continue
|
| 65 |
+
return "Could not extract text from the image. Please try with a clearer image."
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def translate_text(text):
|
| 69 |
+
"""Translate text from English to Hindi using Gemini"""
|
| 70 |
+
max_retries = 3
|
| 71 |
+
retry_delay = 2
|
| 72 |
+
|
| 73 |
+
# Check if there's text to translate
|
| 74 |
+
if not text or text.strip() == "":
|
| 75 |
+
return "No text to translate."
|
| 76 |
+
|
| 77 |
+
for attempt in range(max_retries):
|
| 78 |
+
try:
|
| 79 |
+
print(f"Attempt {attempt + 1} to translate text using Gemini...")
|
| 80 |
+
# Initialize Gemini model
|
| 81 |
+
model = genai.GenerativeModel('gemini-1.0-pro') # Fallback to a stable model
|
| 82 |
+
|
| 83 |
+
# Create prompt for translation
|
| 84 |
+
prompt = f"""
|
| 85 |
+
Translate the following English text to Hindi.
|
| 86 |
+
Keep proper names, titles, and organization names unchanged.
|
| 87 |
+
Text to translate: {text}
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
# Generate response
|
| 91 |
+
print("Sending request to Gemini API for translation...")
|
| 92 |
+
response = model.generate_content(prompt)
|
| 93 |
+
|
| 94 |
+
# Validate response
|
| 95 |
+
if not response or not hasattr(response, 'text') or not response.text:
|
| 96 |
+
raise ValueError("Received empty response from Gemini API")
|
| 97 |
+
|
| 98 |
+
translated_text = response.text.strip()
|
| 99 |
+
print(f"Successfully translated text (length: {len(translated_text)})")
|
| 100 |
+
return translated_text
|
| 101 |
+
except Exception as e:
|
| 102 |
+
print(f"Translation attempt {attempt + 1} failed: {str(e)}")
|
| 103 |
+
print(traceback.format_exc())
|
| 104 |
+
if attempt < max_retries - 1:
|
| 105 |
+
print(f"Retrying in {retry_delay} seconds...")
|
| 106 |
+
time.sleep(retry_delay)
|
| 107 |
+
continue
|
| 108 |
+
return "Translation failed. Please try again later."
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@app.route('/')
|
| 112 |
+
def home():
|
| 113 |
+
return render_template('index.html')
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@app.route('/upload', methods=['POST'])
|
| 117 |
+
def upload_file():
|
| 118 |
+
print("Received upload request")
|
| 119 |
+
if 'file' not in request.files:
|
| 120 |
+
print("No file part in the request")
|
| 121 |
+
return jsonify({'error': 'No file uploaded'}), 400
|
| 122 |
+
|
| 123 |
+
file = request.files['file']
|
| 124 |
+
if file.filename == '':
|
| 125 |
+
print("No file selected")
|
| 126 |
+
return jsonify({'error': 'No file selected'}), 400
|
| 127 |
+
|
| 128 |
+
# Check file extension
|
| 129 |
+
allowed_extensions = {'png', 'jpg', 'jpeg', 'gif', 'bmp'}
|
| 130 |
+
if '.' not in file.filename or file.filename.rsplit('.', 1)[1].lower() not in allowed_extensions:
|
| 131 |
+
print(f"Invalid file format: {file.filename}")
|
| 132 |
+
return jsonify({'error': 'Invalid file format. Please upload an image (PNG, JPG, JPEG, GIF, BMP).'}), 400
|
| 133 |
+
|
| 134 |
+
temp_path = None
|
| 135 |
+
try:
|
| 136 |
+
# Create temp directory if it doesn't exist
|
| 137 |
+
temp_dir = "temp"
|
| 138 |
+
if not os.path.exists(temp_dir):
|
| 139 |
+
os.makedirs(temp_dir)
|
| 140 |
+
print(f"Created temp directory: {temp_dir}")
|
| 141 |
+
|
| 142 |
+
# Save the uploaded file temporarily with a unique name
|
| 143 |
+
temp_path = os.path.join(temp_dir, f"temp_image_{int(time.time())}.png")
|
| 144 |
+
file.save(temp_path)
|
| 145 |
+
print(f"Saved uploaded file to {temp_path}")
|
| 146 |
+
|
| 147 |
+
# Extract text using Gemini
|
| 148 |
+
print("Starting text extraction...")
|
| 149 |
+
extracted_text = extract_text_with_gemini(temp_path)
|
| 150 |
+
print(f"Text extraction result: {extracted_text[:100]}...")
|
| 151 |
+
|
| 152 |
+
# Translate text
|
| 153 |
+
print("Starting text translation...")
|
| 154 |
+
translated_text = translate_text(extracted_text)
|
| 155 |
+
print(f"Translation result: {translated_text[:100]}...")
|
| 156 |
+
|
| 157 |
+
return jsonify({
|
| 158 |
+
'original_text': extracted_text,
|
| 159 |
+
'translated_text': translated_text
|
| 160 |
+
})
|
| 161 |
+
except Exception as e:
|
| 162 |
+
error_msg = f"Error processing image: {str(e)}"
|
| 163 |
+
print(error_msg)
|
| 164 |
+
print(traceback.format_exc())
|
| 165 |
+
return jsonify({
|
| 166 |
+
'error': 'An error occurred while processing your image. Please try again.'
|
| 167 |
+
}), 500
|
| 168 |
+
finally:
|
| 169 |
+
# Clean up temporary file if it exists
|
| 170 |
+
try:
|
| 171 |
+
if temp_path and os.path.exists(temp_path):
|
| 172 |
+
os.remove(temp_path)
|
| 173 |
+
print(f"Removed temporary file: {temp_path}")
|
| 174 |
+
except Exception as e:
|
| 175 |
+
print(f"Failed to remove temporary file: {str(e)}")
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
if __name__ == '__main__':
|
| 179 |
+
# Ensure the template folder exists
|
| 180 |
+
if not os.path.exists('templates'):
|
| 181 |
+
os.makedirs('templates')
|
| 182 |
+
print("Created 'templates' directory. Please place your HTML files here.")
|
| 183 |
+
|
| 184 |
+
# For Hugging Face Spaces, we need to listen on 0.0.0.0 and port 7860
|
| 185 |
+
print(f"Starting Flask app on port {os.environ.get('PORT', 7860)}")
|
| 186 |
app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))
|