athspi / app.py
Athspi's picture
Update app.py
6a59f88 verified
raw
history blame
1.85 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
# Load environment variables
load_dotenv()
# Initialize Flask app
app = Flask(__name__, static_folder='static')
CORS(app) # Enable CORS for all routes
# Configure Gemini
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
model = genai.GenerativeModel('gemini-2.5-flash')
def convert_markdown_to_html(text):
# Convert markdown to HTML
html = markdown2.markdown(text)
# Add custom styling to code blocks
html = html.replace('<code>', '<code class="code-block">')
# Convert **bold** to <strong> for better visibility
html = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', html)
# Convert *italic* to <em>
html = re.sub(r'\*(.*?)\*', r'<em>\1</em>', html)
return html
@app.route('/chat', methods=['POST'])
def chat():
try:
data = request.json
user_message = data.get('message')
if not user_message:
return jsonify({"error": "No message provided"}), 400
# Generate response using Gemini
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('/')
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)