|
|
|
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_dotenv() |
|
|
|
|
|
app = Flask(__name__, static_folder='static') |
|
CORS(app) |
|
|
|
|
|
genai.configure(api_key=os.getenv("GEMINI_API_KEY")) |
|
model = genai.GenerativeModel('gemini-2.5-flash') |
|
|
|
def convert_markdown_to_html(text): |
|
|
|
html = markdown2.markdown(text) |
|
|
|
|
|
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) |
|
|
|
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 |
|
|
|
|
|
response = model.generate_content(user_message) |
|
|
|
|
|
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) |