Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -6,6 +6,7 @@ from dotenv import load_dotenv
|
|
6 |
import time
|
7 |
import traceback
|
8 |
import sys
|
|
|
9 |
|
10 |
# Load environment variables
|
11 |
load_dotenv()
|
@@ -15,16 +16,33 @@ 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 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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"""
|
@@ -34,13 +52,36 @@ def extract_text_with_gemini(image_path):
|
|
34 |
for attempt in range(max_retries):
|
35 |
try:
|
36 |
print(f"Attempt {attempt + 1} to extract text using Gemini...")
|
37 |
-
|
38 |
-
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 |
|
@@ -62,7 +103,7 @@ def extract_text_with_gemini(image_path):
|
|
62 |
print(f"Retrying in {retry_delay} seconds...")
|
63 |
time.sleep(retry_delay)
|
64 |
continue
|
65 |
-
return "Could not extract text from the image
|
66 |
|
67 |
|
68 |
def translate_text(text):
|
@@ -73,12 +114,27 @@ def translate_text(text):
|
|
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 |
-
#
|
81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
|
83 |
# Create prompt for translation
|
84 |
prompt = f"""
|
@@ -105,7 +161,7 @@ def translate_text(text):
|
|
105 |
print(f"Retrying in {retry_delay} seconds...")
|
106 |
time.sleep(retry_delay)
|
107 |
continue
|
108 |
-
return "Translation failed
|
109 |
|
110 |
|
111 |
@app.route('/')
|
@@ -113,6 +169,17 @@ 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")
|
@@ -133,6 +200,10 @@ def upload_file():
|
|
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):
|
@@ -163,7 +234,7 @@ def upload_file():
|
|
163 |
print(error_msg)
|
164 |
print(traceback.format_exc())
|
165 |
return jsonify({
|
166 |
-
'error':
|
167 |
}), 500
|
168 |
finally:
|
169 |
# Clean up temporary file if it exists
|
@@ -181,6 +252,13 @@ if __name__ == '__main__':
|
|
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)))
|
|
|
6 |
import time
|
7 |
import traceback
|
8 |
import sys
|
9 |
+
import json
|
10 |
|
11 |
# Load environment variables
|
12 |
load_dotenv()
|
|
|
16 |
if api_key == "AIzaSyB0IOx76FydAk4wabMz1juzzHF5oBiHW64":
|
17 |
print("WARNING: Using hardcoded API key. Set GEMINI_API_KEY environment variable instead.")
|
18 |
|
19 |
+
# Function to test API connectivity
|
20 |
+
def test_gemini_api():
|
21 |
+
try:
|
22 |
+
genai.configure(api_key=api_key)
|
23 |
+
|
24 |
+
# Test with a simple text prompt
|
25 |
+
model = genai.GenerativeModel('gemini-1.0-pro')
|
26 |
+
response = model.generate_content("Hello, please respond with 'API is working'")
|
27 |
+
|
28 |
+
if not response or not hasattr(response, 'text') or not response.text:
|
29 |
+
print("WARNING: Received empty response during API test")
|
30 |
+
return False
|
31 |
+
|
32 |
+
print(f"API Test Response: {response.text.strip()}")
|
33 |
+
return True
|
34 |
+
except Exception as e:
|
35 |
+
print(f"ERROR: Failed to connect to Gemini API: {str(e)}")
|
36 |
+
print(traceback.format_exc())
|
37 |
+
return False
|
38 |
|
39 |
# Initialize Flask app
|
40 |
app = Flask(__name__)
|
41 |
|
42 |
+
# Configure error responses
|
43 |
+
@app.errorhandler(500)
|
44 |
+
def server_error(e):
|
45 |
+
return jsonify(error="Internal server error: " + str(e)), 500
|
46 |
|
47 |
def extract_text_with_gemini(image_path):
|
48 |
"""Extract text from image using Gemini Vision model"""
|
|
|
52 |
for attempt in range(max_retries):
|
53 |
try:
|
54 |
print(f"Attempt {attempt + 1} to extract text using Gemini...")
|
55 |
+
|
56 |
+
# Try different model versions in case one is not available
|
57 |
+
model_options = ['gemini-1.0-pro-vision', 'gemini-pro-vision']
|
58 |
+
|
59 |
+
for model_name in model_options:
|
60 |
+
try:
|
61 |
+
print(f"Trying model: {model_name}")
|
62 |
+
model = genai.GenerativeModel(model_name)
|
63 |
+
break
|
64 |
+
except Exception as model_error:
|
65 |
+
print(f"Error with model {model_name}: {str(model_error)}")
|
66 |
+
if model_name == model_options[-1]: # Last model option
|
67 |
+
raise
|
68 |
+
continue
|
69 |
|
70 |
# Load the image
|
71 |
with Image.open(image_path) as img:
|
72 |
print(f"Image loaded from {image_path} (Size: {img.size}, Format: {img.format})")
|
73 |
|
74 |
+
# Resize image if too large (API may have size limits)
|
75 |
+
max_dimension = 1024
|
76 |
+
if img.width > max_dimension or img.height > max_dimension:
|
77 |
+
print(f"Resizing large image from {img.width}x{img.height}")
|
78 |
+
ratio = min(max_dimension / img.width, max_dimension / img.height)
|
79 |
+
new_width = int(img.width * ratio)
|
80 |
+
new_height = int(img.height * ratio)
|
81 |
+
img = img.resize((new_width, new_height))
|
82 |
+
print(f"Resized to {new_width}x{new_height}")
|
83 |
+
img.save(image_path) # Save resized image
|
84 |
+
|
85 |
# Create prompt for text extraction
|
86 |
prompt = "Extract all the text from this image. Return only the extracted text, nothing else."
|
87 |
|
|
|
103 |
print(f"Retrying in {retry_delay} seconds...")
|
104 |
time.sleep(retry_delay)
|
105 |
continue
|
106 |
+
return f"Could not extract text from the image: {str(e)}"
|
107 |
|
108 |
|
109 |
def translate_text(text):
|
|
|
114 |
# Check if there's text to translate
|
115 |
if not text or text.strip() == "":
|
116 |
return "No text to translate."
|
117 |
+
|
118 |
+
# If the text indicates an error occurred during extraction, don't try to translate
|
119 |
+
if text.startswith("Could not extract text from the image"):
|
120 |
+
return "Cannot translate due to OCR failure."
|
121 |
|
122 |
for attempt in range(max_retries):
|
123 |
try:
|
124 |
print(f"Attempt {attempt + 1} to translate text using Gemini...")
|
125 |
+
# Try different model versions
|
126 |
+
model_options = ['gemini-1.0-pro', 'gemini-pro']
|
127 |
+
|
128 |
+
for model_name in model_options:
|
129 |
+
try:
|
130 |
+
print(f"Trying model: {model_name}")
|
131 |
+
model = genai.GenerativeModel(model_name)
|
132 |
+
break
|
133 |
+
except Exception as model_error:
|
134 |
+
print(f"Error with model {model_name}: {str(model_error)}")
|
135 |
+
if model_name == model_options[-1]: # Last model option
|
136 |
+
raise
|
137 |
+
continue
|
138 |
|
139 |
# Create prompt for translation
|
140 |
prompt = f"""
|
|
|
161 |
print(f"Retrying in {retry_delay} seconds...")
|
162 |
time.sleep(retry_delay)
|
163 |
continue
|
164 |
+
return f"Translation failed: {str(e)}"
|
165 |
|
166 |
|
167 |
@app.route('/')
|
|
|
169 |
return render_template('index.html')
|
170 |
|
171 |
|
172 |
+
@app.route('/api-status', methods=['GET'])
|
173 |
+
def api_status():
|
174 |
+
"""Endpoint to check API status"""
|
175 |
+
api_working = test_gemini_api()
|
176 |
+
return jsonify({
|
177 |
+
'status': 'ok' if api_working else 'error',
|
178 |
+
'api_working': api_working,
|
179 |
+
'message': 'Gemini API is working correctly' if api_working else 'Gemini API is not working'
|
180 |
+
})
|
181 |
+
|
182 |
+
|
183 |
@app.route('/upload', methods=['POST'])
|
184 |
def upload_file():
|
185 |
print("Received upload request")
|
|
|
200 |
|
201 |
temp_path = None
|
202 |
try:
|
203 |
+
# Check API status before proceeding
|
204 |
+
if not test_gemini_api():
|
205 |
+
return jsonify({'error': 'Gemini API is not working. Please check your API key and try again.'}), 500
|
206 |
+
|
207 |
# Create temp directory if it doesn't exist
|
208 |
temp_dir = "temp"
|
209 |
if not os.path.exists(temp_dir):
|
|
|
234 |
print(error_msg)
|
235 |
print(traceback.format_exc())
|
236 |
return jsonify({
|
237 |
+
'error': error_msg
|
238 |
}), 500
|
239 |
finally:
|
240 |
# Clean up temporary file if it exists
|
|
|
252 |
os.makedirs('templates')
|
253 |
print("Created 'templates' directory. Please place your HTML files here.")
|
254 |
|
255 |
+
# Test API connectivity at startup
|
256 |
+
api_working = test_gemini_api()
|
257 |
+
if api_working:
|
258 |
+
print("✅ Gemini API connection successful!")
|
259 |
+
else:
|
260 |
+
print("❌ WARNING: Gemini API connection failed. The application may not work correctly!")
|
261 |
+
|
262 |
# For Hugging Face Spaces, we need to listen on 0.0.0.0 and port 7860
|
263 |
print(f"Starting Flask app on port {os.environ.get('PORT', 7860)}")
|
264 |
app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))
|