import os import base64 import re from flask import Flask, render_template, request, redirect, url_for, flash from openai import OpenAI from PIL import Image from io import BytesIO # Initialize Flask app app = Flask(__name__) app.secret_key = 'supersecretkey' # Set upload folder and ensure it exists with correct permissions UPLOAD_FOLDER = 'static/uploads' os.makedirs(UPLOAD_FOLDER, mode=0o777, exist_ok=True) # Ensure folder exists with correct permissions app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER # Initialize OpenAI client api_key = os.getenv("OPENAI_API_KEY") if not api_key: raise ValueError("❌ Error: OPENAI_API_KEY is not set! Check Hugging Face Secrets.") client = OpenAI(api_key=api_key) # Function to convert image to Base64 PNG string def convert_to_png_base64(image_path): try: with Image.open(image_path) as img: img = img.convert("RGBA") buffer = BytesIO() img.save(buffer, format="PNG") return base64.b64encode(buffer.getvalue()).decode("utf-8") except Exception as e: print(f"Error: {e}") return None # Function to format response into clean HTML def format_response(message_content): # Replace ### Heading with

Heading

formatted = re.sub(r'^### (.*?)$', r'

\1

', message_content, flags=re.M) # Replace **bold** with bold formatted = re.sub(r'\*\*(.*?)\*\*', r'\1', formatted) # Replace "- " with list items formatted = re.sub(r'^\- (.*?)$', r'
  • \1
  • ', formatted, flags=re.M) # Wrap lists with