KoreAI-API / main.py
rairo's picture
Update main.py
02784e4 verified
raw
history blame
4.82 kB
import os
import io
import uuid
import re
import time
import json
import traceback
import wave
from datetime import datetime, timedelta
from flask import Flask, request, jsonify, Response
from flask_cors import CORS
import firebase_admin
from firebase_admin import credentials, db, storage, auth
from PIL import Image
from io import BytesIO
import requests
from elevenlabs import ElevenLabs
# Import and configure Google GenAI, matching the Streamlit app
# from google import genai # Assuming you might use this later
# from google.genai import types
# -----------------------------------------------------------------------------
# 1. CONFIGURATION & INITIALIZATION
# -----------------------------------------------------------------------------
# Initialize Flask app and CORS
app = Flask(__name__)
CORS(app)
# --- Firebase Initialization ---
try:
# Best practice: Load credentials from environment variables
credentials_json_string = os.environ.get("FIREBASE")
if not credentials_json_string:
raise ValueError("The FIREBASE environment variable is not set.")
credentials_json = json.loads(credentials_json_string)
firebase_db_url = os.environ.get("Firebase_DB")
firebase_storage_bucket = os.environ.get("Firebase_Storage")
if not firebase_db_url or not firebase_storage_bucket:
raise ValueError("Firebase_DB and Firebase_Storage environment variables must be set.")
cred = credentials.Certificate(credentials_json)
firebase_admin.initialize_app(cred, {
'databaseURL': firebase_db_url,
'storageBucket': firebase_storage_bucket
})
print("Firebase Admin SDK initialized successfully.")
except Exception as e:
print(f"FATAL: Error initializing Firebase: {e}")
# In a real app, you might want to prevent the app from starting if Firebase fails
# exit(1)
# Initialize Firebase services
bucket = storage.bucket()
db_ref = db.reference()
# -----------------------------------------------------------------------------
# 2. HELPER FUNCTIONS
# -----------------------------------------------------------------------------
def is_valid_email(email):
"""Simple regex for basic email validation."""
regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(regex, email) is not None
# -----------------------------------------------------------------------------
# 3. AUTHENTICATION & USER MANAGEMENT
# -----------------------------------------------------------------------------
# (Your other authentication endpoints would go here)
# -----------------------------------------------------------------------------
# 4. WAITLIST ENDPOINT
# -----------------------------------------------------------------------------
@app.route('/join-waitlist', methods=['POST'])
def join_waitlist():
"""
Endpoint to add a user's email to the waitlist.
Expects a JSON payload: {"email": "user@example.com"}
"""
try:
# 1. Get and Validate Input
data = request.get_json()
if not data:
return jsonify({"status": "error", "message": "Invalid request. JSON payload expected."}), 400
email = data.get('email')
if not email:
return jsonify({"status": "error", "message": "Email is required."}), 400
if not is_valid_email(email):
return jsonify({"status": "error", "message": "Invalid email format."}), 400
email = email.lower() # Standardize email to lowercase
# 2. Check for Duplicates
waitlist_ref = db_ref.child('sozo_waitlist')
# Query Firebase to see if an entry with this email already exists
existing_user = waitlist_ref.order_by_child('email').equal_to(email).get()
if existing_user:
return jsonify({"status": "success", "message": "You are already on the waitlist!"}), 200
# 3. Add to Firebase Realtime Database
new_entry_ref = waitlist_ref.push() # push() creates a unique key
new_entry_ref.set({
'email': email,
'timestamp': datetime.utcnow().isoformat() + 'Z' # ISO 8601 format
})
return jsonify({"status": "success", "message": "Thank you for joining the waitlist!"}), 201
except Exception as e:
print(f"ERROR in /join-waitlist: {e}")
traceback.print_exc()
return jsonify({"status": "error", "message": "An internal server error occurred."}), 500
# -----------------------------------------------------------------------------
# 7. MAIN EXECUTION
# -----------------------------------------------------------------------------
if __name__ == '__main__':
# Use Gunicorn or another production-ready server instead of app.run in production
app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))