M-anglais / app.py
Docfile's picture
Create app.py
3a27f38 verified
raw
history blame
2.38 kB
from flask import Flask, render_template, request, jsonify
import PIL.Image
import io
import google.generativeai as genai
from werkzeug.utils import secure_filename
import os
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
app.config['UPLOAD_FOLDER'] = 'uploads'
# Ensure upload folder exists
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# Configure Google Generative AI
GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
genai.configure(api_key=GOOGLE_API_KEY)
safety_settings = [
{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
]
PROMPT_TEXT = """[Your existing prompt_text here]"""
PROMPT_IMAGE = """[Your existing prompt_image here]"""
@app.route('/')
def index():
return render_template('index.html')
@app.route('/analyze', methods=['POST'])
def analyze():
try:
analysis_type = request.form.get('analysis_type')
files = request.files.getlist('images')
if not files:
return jsonify({'error': 'No files uploaded'}), 400
image_parts = []
for file in files:
if file.filename:
# Save file temporarily
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
# Process image
image = PIL.Image.open(filepath)
image_parts.append(image)
# Clean up
os.remove(filepath)
# Select prompt based on analysis type
prompt = PROMPT_TEXT if analysis_type == 'text' else PROMPT_IMAGE
# Generate content
model = genai.GenerativeModel(model_name="gemini-2.0-flash-exp", safety_settings=safety_settings)
response = model.generate_content([prompt] + image_parts)
response.resolve()
return jsonify({'result': response.text})
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=True)