athspi / app.py
Athspi's picture
Update app.py
ba4d3af verified
raw
history blame
3.76 kB
# app.py - Flask Backend
from flask import Flask, request, jsonify, send_from_directory
import google.generativeai as genai
from dotenv import load_dotenv
import os
from flask_cors import CORS
import markdown2
import re
import tempfile
from werkzeug.utils import secure_filename
# Load environment variables
load_dotenv()
# Initialize Flask app
app = Flask(__name__, static_folder='static')
CORS(app) # Enable CORS for all routes
# Configuration
UPLOAD_FOLDER = 'uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
ALLOWED_EXTENSIONS = {'pdf', 'txt', 'docx', 'pptx', 'xlsx', 'jpg', 'jpeg', 'png'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Configure Gemini
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
model = genai.GenerativeModel('gemini-2.5-flash')
vision_model = genai.GenerativeModel('gemini-2.5-flash')
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def convert_markdown_to_html(text):
# Convert markdown to HTML
html = markdown2.markdown(text)
# Add custom styling
html = html.replace('<code>', '<code class="code-block">')
html = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', html)
html = re.sub(r'\*(.*?)\*', r'<em>\1</em>', html)
html = html.replace('<a ', '<a target="_blank" rel="noopener noreferrer" ')
return html
@app.route('/chat', methods=['POST'])
def chat():
try:
data = request.json
user_message = data.get('message')
file_path = data.get('file_path')
if not user_message and not file_path:
return jsonify({"error": "No message or file provided"}), 400
# Generate response based on input type
if file_path:
# Process file with vision model if it's an image
if file_path.lower().endswith(('.jpg', '.jpeg', '.png')):
response = vision_model.generate_content([user_message, genai.upload_file(file_path)])
else:
# Process text-based files
with open(file_path, 'r') as file:
file_content = file.read()
prompt = f"{user_message}\n\nFile content:\n{file_content}"
response = model.generate_content(prompt)
else:
# Regular text chat
response = model.generate_content(user_message)
# Convert markdown to HTML with styling
formatted_response = convert_markdown_to_html(response.text)
return jsonify({
"response": formatted_response
})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/upload', methods=['POST'])
def upload_file():
try:
if 'file' not in request.files:
return jsonify({"error": "No file part"}), 400
file = request.files['file']
if file.filename == '':
return jsonify({"error": "No selected file"}), 400
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(file_path)
return jsonify({
"message": "File uploaded successfully",
"file_path": file_path
})
else:
return jsonify({"error": "File type not allowed"}), 400
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/')
def serve_index():
return send_from_directory('static', 'index.html')
@app.route('/<path:path>')
def serve_static(path):
return send_from_directory('static', path)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=7860