import os import json import uuid import tempfile from urllib.parse import urlparse from…
- User
import os import json import uuid import tempfile from urllib.parse import urlparse from flask import Flask, jsonify, request, send_from_directory from flask_cors import CORS from werkzeug.utils import secure_filename import requests import firebase_admin from firebase_admin import credentials, firestore, storage import threading import logging
app = Flask(name) CORS(app, resources={r"/api/": {"origins": ""}})
-------------------------------
Configuration and Initialization
-------------------------------
Project directory
BASE_DIR = os.path.dirname(os.path.abspath(file))
Data directories and file paths
DATA_DIR = os.path.join(BASE_DIR, 'data') OUTPUT_JSON = os.path.join(DATA_DIR, 'output2.json') # 'data' folder OUTPUT_APPROVED_JSON = os.path.join(DATA_DIR, 'outputapproved.json') APPROVED_IMAGES_DIR = os.path.join(BASE_DIR, 'approvedimages')
Create directories if they don't exist
os.makedirs(APPROVED_IMAGES_DIR, exist_ok=True) os.makedirs(DATA_DIR, exist_ok=True)
Initialize JSON files if they don't exist
for file_path in [OUTPUT_JSON, OUTPUT_APPROVED_JSON]: if not os.path.exists(file_path): with open(file_path, 'w', encoding='utf-8') as f: json.dump({}, f, ensure_ascii=False, indent=4)
Firebase Admin SDK Initialization
FIREBASE_CREDENTIALS = os.getenv('FIREBASE_CREDENTIALS', 'cre.json') # Path to your Firebase service account key FIREBASE_STORAGE_BUCKET = os.getenv('FIREBASE_STORAGE_BUCKET', 'readarabic-dec46.appspot.com') # Replace with your Firebase Storage Bucket name
if not os.path.exists(FIREBASE_CREDENTIALS): app.logger.critical(f"Firebase service account key not found: {FIREBASE_CREDENTIALS}") exit(1)
cred = credentials.Certificate(FIREBASE_CREDENTIALS) firebase_admin.initialize_app(cred, { 'storageBucket': FIREBASE_STORAGE_BUCKET })
db = firestore.client() bucket = storage.bucket()
Global threading lock for file operations
file_lock = threading.Lock()
-------------------------------
Logging Configuration
-------------------------------
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') logger = logging.getLogger(name)
-------------------------------
Utility Functions
-------------------------------
def atomic_write(file_path, data, encoding='utf-8'): """ Atomically write JSON data to a file. """ try: with tempfile.NamedTemporaryFile('w', delete=False, encoding=encoding, dir=os.path.dirname(file_path)) as tmp_file: json.dump(data, tmp_file, ensure_ascii=False, indent=4) temp_name = tmp_file.name os.replace(temp_name, file_path) logger.info(f"Atomically wrote to {file_path}") except Exception as e: app.logger.error(f"Atomic write failed for {file_path}: {e}") raise
- Assistant