Download database.py from Mahir1426/face6: direct link, hf CLI and curl.
- Browser
- Download file 2.39 kB
-
https://huggingface.co/spaces/Mahir1426/face6/resolve/main/database.py
- Command line
-
hf download hf://spaces/Mahir1426/face6/database.py
-
curl -L -o database.py https://huggingface.co/spaces/Mahir1426/face6/resolve/main/database.py
2.39 kB
| 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()) |