File size: 3,761 Bytes
3ebc508 1deacc5 3ebc508 1deacc5 9018379 3ebc508 1deacc5 3ebc508 9018379 3ebc508 ba4d3af 9018379 3ebc508 1deacc5 9018379 1deacc5 9018379 1deacc5 3ebc508 9018379 3ebc508 9018379 3ebc508 9018379 3ebc508 1deacc5 3ebc508 1deacc5 3ebc508 9018379 3ebc508 1deacc5 3ebc508 ba4d3af |
1 2 3 4 5 6 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 |
# 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 |