File size: 2,391 Bytes
130d7c1 |
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 |
import os
import cloudinary
import cloudinary.uploader
from pymongo import MongoClient
from dotenv import load_dotenv
from datetime import datetime
# Load environment variables from .env file
load_dotenv()
# --- Cloudinary Configuration ---
# Check if Cloudinary credentials are available
CLOUDINARY_AVAILABLE = all([
os.getenv("CLOUDINARY_CLOUD_NAME"),
os.getenv("CLOUDINARY_API_KEY"),
os.getenv("CLOUDINARY_API_SECRET")
])
if CLOUDINARY_AVAILABLE:
cloudinary.config(
cloud_name=os.getenv("CLOUDINARY_CLOUD_NAME"),
api_key=os.getenv("CLOUDINARY_API_KEY"),
api_secret=os.getenv("CLOUDINARY_API_SECRET")
)
# --- MongoDB Configuration ---
MONGO_URI = os.getenv("MONGO_URI")
MONGO_AVAILABLE = MONGO_URI is not None
if MONGO_AVAILABLE:
client = MongoClient(MONGO_URI)
db = client.get_database("face_shape_db")
analyses_collection = db.get_collection("analyses")
else:
client = None
db = None
analyses_collection = None
def upload_image_to_cloudinary(image_file):
"""Uploads an image file to Cloudinary and returns the secure URL."""
if not CLOUDINARY_AVAILABLE:
print("Cloudinary not configured, returning placeholder URL")
return "https://via.placeholder.com/400x400/cccccc/666666?text=Image+Upload+Disabled"
try:
upload_result = cloudinary.uploader.upload(image_file)
return upload_result.get("secure_url")
except Exception as e:
print(f"Error uploading to Cloudinary: {e}")
return "https://via.placeholder.com/400x400/cccccc/666666?text=Upload+Failed"
def save_analysis_to_db(image_url, face_shape, measurements):
"""Saves the analysis results to MongoDB."""
if not MONGO_AVAILABLE:
print("MongoDB not configured, returning mock ID")
return "mock_analysis_id_" + str(datetime.utcnow().timestamp())
try:
analysis_data = {
"image_url": image_url,
"face_shape": face_shape,
"measurements": measurements,
"created_at": datetime.utcnow()
}
result = analyses_collection.insert_one(analysis_data)
return str(result.inserted_id)
except Exception as e:
print(f"Error saving to MongoDB: {e}")
return "mock_analysis_id_" + str(datetime.utcnow().timestamp()) |