To achieve the functionality where approving a word automatically uploads its associated image to Firebase Storage and updates the corresponding Firestore document with the Firebase image URL, we need to ensure that the backend (Flask application) handles this process seamlessly. Additionally, the frontend should provide appropriate user feedback and possibly reflect the updated image URLs if necessary.
Based on the code you provided, it appears that much of the required functionality is already implemented. However, I will guide you through refining and ensuring that the process works as intended. Below are the steps and recommendations to enhance your application:
1. Backend (Flask Application) Enhancements
a. Ensure Synchronous Upload During Approval
Currently, the approve_word function initiates the image upload in a separate thread. While this approach allows the API to respond immediately, it might lead to inconsistencies if the upload process fails after the word has been moved to the approved list. To maintain data integrity, it's advisable to perform the upload synchronously during approval. This way, if the upload fails, the word isn't prematurely marked as approved.
Modified approve_word Function:
@app.route('/api/approve', methods=['POST'])
def approve_word():
"""
Approves a specific word: removes it from output2.json and adds it to outputapproved.json.
Uploads the image to Firebase and updates the Firestore document.
"""
try:
app.logger.info(f"Received approve request data: {request.data}")
data = request.get_json()
if not data:
app.logger.error("Invalid JSON data.")
return jsonify({"error": "Invalid JSON data."}), 400
word = data.get('word')
if not word:
app.logger.error("Word not specified.")
return jsonify({"error": "Word not specified."}), 400
with file_lock:
# Load output2.json
with open(OUTPUT_JSON, 'r', encoding='utf-8') as f:
data_json = json.load(f)
if word not in data_json:
app.logger.error(f"'{word}' not found in {OUTPUT_JSON}.")
return jsonify({"error": f"'{word}' not found in {OUTPUT_JSON}."}), 404
word_data = data_json.pop(word)
# Load outputapproved.json
with open(OUTPUT_APPROVED_JSON, 'r', encoding='utf-8') as f:
approved_data = json.load(f)
if not isinstance(approved_data, dict):
approved_data = {}
# Add the word to approved_data
approved_data[word] = word_data
# Atomically write approved_data
atomic_write(OUTPUT_APPROVED_JSON, approved_data)
# Atomically write updated data_json
atomic_write(OUTPUT_JSON, data_json)
app.logger.info(f"'{word}' has been approved successfully.")
# Upload image to Firebase synchronously
image_path = word_data.get('image')
if image_path:
firebase_image_url = upload_image_to_firebase(word, image_path)
if firebase_image_url:
# Update the local approved_data with the Firebase image URL
with file_lock:
with open(OUTPUT_APPROVED_JSON, 'r', encoding='utf-8') as f:
approved_data = json.load(f)
approved_data[word]['image'] = firebase_image_url
atomic_write(OUTPUT_APPROVED_JSON, approved_data)
else:
# If upload failed, you might want to rollback the approval
app.logger.error(f"Failed to upload image for '{word}'. Rolling back approval.")
with file_lock:
# Remove the word from approved_data
approved_data.pop(word, None)
atomic_write(OUTPUT_APPROVED_JSON, approved_data)
# Re-add the word back to data_json
with open(OUTPUT_JSON, 'r', encoding='utf-8') as f:
data_json = json.load(f)
data_json[word] = word_data
atomic_write(OUTPUT_JSON, data_json)
return jsonify({"error": f"Failed to upload image for '{word}'."}), 500
else:
app.logger.warning(f"No image path found for '{word}'.")
return jsonify({"message": f"'{word}' has been approved and image uploaded."}), 200
except json.JSONDecodeError as jde:
app.logger.error(f"JSON decode error: {jde}")
return jsonify({"error": "Invalid JSON format."}), 400
except Exception as e:
app.logger.error(f"Error in /api/approve: {e}")
return jsonify({"error": str(e)}), 500
b. Refine the upload_image_to_firebase Function
Ensure that the upload_image_to_firebase function returns the Firebase image URL upon successful upload. This allows the approve_word function to update the local JSON file accordingly.
Modified upload_image_to_firebase Function:
def upload_image_to_firebase(word, image_path):
"""
Uploads the image to Firebase Storage and updates Firestore with the image URL.
Returns the Firebase image URL if successful, else None.
"""
try:
# Locate the image file
local_image_path = os.path.join(BASE_DIR, image_path.lstrip('/'))
if not os.path.exists(local_image_path):
app.logger.error(f"Local image file does not exist: {local_image_path}")
return None
# Upload to Firebase Storage under 'dictionaryimages' folder
blob = bucket.blob(f"dictionaryimages/{secure_filename(os.path.basename(local_image_path))}")
blob.upload_from_filename(local_image_path)
# Make the blob publicly accessible and get its URL
blob.make_public()
firebase_image_url = blob.public_url
# Update the Firestore document
doc_ref = db.collection('dictionary').document(word)
doc_ref.set({"image": firebase_image_url}, merge=True)
app.logger.info(f"Image for '{word}' successfully uploaded to Firebase: {firebase_image_url}")
return firebase_image_url
except Exception as e:
app.logger.error(f"Error uploading image for '{word}' to Firebase: {e}")
return None
Key Changes:
-
Synchronous Upload: The image upload is now performed synchronously within the approve_word function. This ensures that the approval process only succeeds if the image upload is successful.
-
Error Handling & Rollback: If the image upload fails, the word approval is rolled back by moving the word back to output2.json. This maintains data consistency.
-
Updating Local JSON with Firebase URL: After a successful upload, the local outputapproved.json is updated to replace the local image path with the Firebase image URL.
-
Firestore Update Using set with merge=True: This ensures that only the image field is updated or added without overwriting other fields in the document.
c. Remove Redundant Background Upload Endpoints
Since the image upload is now handled synchronously during approval, having separate endpoints like /api/upload_to_firebase becomes redundant. You can remove or deprecate these endpoints to streamline your API.
However, if you still want to provide a bulk upload option (e.g., for already approved words), you can keep them. Just ensure their functionality doesn't conflict with the new synchronous upload process.
2. Frontend (script.js) Enhancements
Given the backend changes, ensure that the frontend reflects the updated image URLs if necessary. Here's how you can adjust the frontend:
a. Reflect Firebase Image URLs in the UI
After approval, since the image URL is now updated to Firebase, ensure that any subsequent displays of the image use the new URL. This is already handled in the backend by updating the outputapproved.json with the Firebase URL.
However, to make sure the frontend fetches the latest image URL, you might need to reload the data or handle it appropriately.
Example Adjustment in displayWord Function:
function displayWord() {
if (currentIndex >= words.length) {
wordCard.innerHTML = "<p>Tüm kelimeler işlendi.</p>";
progress.textContent = "İşlem tamamlandı.";
return;
}
const [word, details] = words[currentIndex];
wordCard.innerHTML = ''; // Önceki içeriği temizle
const wordValue = document.createElement('div');
wordValue.className = 'word-value';
wordValue.textContent = `Kelime: ${word}`;
const img = document.createElement('img');
img.src = details.image;
img.alt = word;
img.onerror = () => { img.src = 'default_image.jpg'; }; // Resim yüklenemezse varsayılan resim
const meaning = document.createElement('div');
meaning.className = 'meaning';
// meaningEN'in bir dizi olup olmadığını kontrol edin
if (Array.isArray(details.meaningEN)) {
meaning.textContent = `Anlam: ${details.meaningEN.join(', ')}`;
} else if (typeof details.meaningEN === 'string') {
meaning.textContent = `Anlam: ${details.meaningEN}`;
} else {
meaning.textContent = `Anlam: Belirtilmedi.`;
}
wordCard.appendChild(wordValue);
wordCard.appendChild(img);
wordCard.appendChild(meaning);
// Güncel kelime sayısını göster
progress.textContent = `İşlenen Kelime: ${currentIndex + 1} / ${words.length}`;
}
Note: Since outputapproved.json is updated with the Firebase URL upon approval, when you fetch the approved words, they will contain the updated image URLs. Ensure that the /api/words endpoint returns the latest data reflecting these changes.
b. Handle Real-Time Updates (Optional)
If you want the frontend to reflect changes in real-time (e.g., immediately show the image from Firebase after approval without reloading), consider implementing WebSockets or periodically fetching the latest data. However, this is optional and depends on your application's requirements.
3. Additional Recommendations
a. Secure Firebase Storage Access
While making blobs public is straightforward, it's not always recommended for sensitive applications. Consider using Firebase Authentication and Security Rules to control access to your storage resources. This approach enhances security by restricting who can read or write to your storage.
b. Validate Image Formats and Sizes
To prevent unnecessary storage usage and potential abuse, validate the image formats and sizes before uploading them to Firebase. You can add checks in the approve_word function to ensure that only valid images are processed.
Example:
ALLOWED_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.bmp'}
MAX_IMAGE_SIZE = 5 * 1024 * 1024 # 5 MB
def is_allowed_file(filename):
_, ext = os.path.splitext(filename)
return ext.lower() in ALLOWED_EXTENSIONS
def upload_image_to_firebase(word, image_path):
# ... existing code ...
# Validate file extension
if not is_allowed_file local_image_path:
app.logger.error(f"Unsupported file extension for '{word}': {local_image_path}")
return None
# Validate file size
if os.path.getsize(local_image_path) > MAX_IMAGE_SIZE:
app.logger.error(f"Image size exceeds limit for '{word}': {local_image_path}")
return None
# ... continue with upload ...
c. Logging Enhancements
Improve logging to include more context, such as timestamps and structured logging. This practice aids in debugging and monitoring the application.
d. Environment Configuration
Avoid hardcoding sensitive information like Firebase credentials in your code. Use environment variables or configuration files with proper access controls.
Example Using Environment Variables:
-
Set Environment Variables:
export FIREBASE_CREDENTIALS='path/to/cre.json'
export FIREBASE_STORAGE_BUCKET='readarabic-dec46.appspot.com'
-
Modify Flask App Initialization:
FIREBASE_CREDENTIALS = os.getenv('FIREBASE_CREDENTIALS')
FIREBASE_STORAGE_BUCKET = os.getenv('FIREBASE_STORAGE_BUCKET')
if not FIREBASE_CREDENTIALS or not FIREBASE_STORAGE_BUCKET:
app.logger.critical("Firebase configuration is missing.")
exit(1)
cred = credentials.Certificate(FIREBASE_CREDENTIALS)
firebase_admin.initialize_app(cred, {
'storageBucket': FIREBASE_STORAGE_BUCKET
})
e. Rate Limiting and Security
Implement rate limiting to prevent abuse of your API endpoints. Additionally, consider securing your API with authentication mechanisms to restrict access to authorized users only.
4. Final Backend Code Snippet
Here is the refined backend code with the aforementioned enhancements:
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)
# 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)
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)
except Exception as e:
app.logger.error(f"Atomic write failed for {file_path}: {e}")
raise
ALLOWED_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.bmp'}
MAX_IMAGE_SIZE = 5 * 1024 * 1024 # 5 MB
def is_allowed_file(filename):
_, ext = os.path.splitext(filename)
return ext.lower() in ALLOWED_EXTENSIONS
def upload_image_to_firebase(word, image_path):
"""
Uploads the image to Firebase Storage and updates Firestore with the image URL.
Returns the Firebase image URL if successful, else None.
"""
try:
# Locate the image file
local_image_path = os.path.join(BASE_DIR, image_path.lstrip('/'))
if not os.path.exists(local_image_path):
app.logger.error(f"Local image file does not exist: {local_image_path}")
return None
# Validate file extension
if not is_allowed_file(local_image_path):
app.logger.error(f"Unsupported file extension for '{word}': {local_image_path}")
return None
# Validate file size
if os.path.getsize(local_image_path) > MAX_IMAGE_SIZE:
app.logger.error(f"Image size exceeds limit for '{word}': {local_image_path}")
return None
# Upload to Firebase Storage under 'dictionaryimages' folder
blob = bucket.blob(f"dictionaryimages/{secure_filename(os.path.basename(local_image_path))}")
blob.upload_from_filename(local_image_path)
# Make the blob publicly accessible and get its URL
blob.make_public()
firebase_image_url = blob.public_url
# Update the Firestore document
doc_ref = db.collection('dictionary').document(word)
doc_ref.set({"image": firebase_image_url}, merge=True)
app.logger.info(f"Image for '{word}' successfully uploaded to Firebase: {firebase_image_url}")
return firebase_image_url
except Exception as e:
app.logger.error(f"Error uploading image for '{word}' to Firebase: {e}")
return None
# -------------------------------
# API Endpoints
# -------------------------------
@app.route('/api/words', methods=['GET'])
def get_words():
"""
Returns all words from output2.json.
"""
try:
with file_lock:
with open(OUTPUT_JSON, 'r', encoding='utf-8') as f:
data = json.load(f)
return jsonify(data), 200
except FileNotFoundError:
return jsonify({"error": f"{OUTPUT_JSON} not found."}), 404
except json.JSONDecodeError:
return jsonify({"error": f"{OUTPUT_JSON} is invalid or empty."}), 400
except Exception as e:
app.logger.error(f"Error in /api/words: {e}")
return jsonify({"error": str(e)}), 500
@app.route('/api/approve', methods=['POST'])
def approve_word():
"""
Approves a specific word: removes it from output2.json and adds it to outputapproved.json.
Uploads the image to Firebase and updates the Firestore document.
"""
try:
app.logger.info(f"Received approve request data: {request.data}")
data = request.get_json()
if not data:
app.logger.error("Invalid JSON data.")
return jsonify({"error": "Invalid JSON data."}), 400
word = data.get('word')
if not word:
app.logger.error("Word not specified.")
return jsonify({"error": "Word not specified."}), 400
with file_lock:
# Load output2.json
with open(OUTPUT_JSON, 'r', encoding='utf-8') as f:
data_json = json.load(f)
if word not in data_json:
app.logger.error(f"'{word}' not found in {OUTPUT_JSON}.")
return jsonify({"error": f"'{word}' not found in {OUTPUT_JSON}."}), 404
word_data = data_json.pop(word)
# Load outputapproved.json
with open(OUTPUT_APPROVED_JSON, 'r', encoding='utf-8') as f:
approved_data = json.load(f)
if not isinstance(approved_data, dict):
approved_data = {}
# Add the word to approved_data
approved_data[word] = word_data
# Atomically write approved_data
atomic_write(OUTPUT_APPROVED_JSON, approved_data)
# Atomically write updated data_json
atomic_write(OUTPUT_JSON, data_json)
app.logger.info(f"'{word}' has been approved successfully.")
# Upload image to Firebase synchronously
image_path = word_data.get('image')
if image_path:
firebase_image_url = upload_image_to_firebase(word, image_path)
if firebase_image_url:
# Update the local approved_data with the Firebase image URL
with file_lock:
with open(OUTPUT_APPROVED_JSON, 'r', encoding='utf-8') as f:
approved_data = json.load(f)
approved_data[word]['image'] = firebase_image_url
atomic_write(OUTPUT_APPROVED_JSON, approved_data)
else:
# If upload failed, you might want to rollback the approval
app.logger.error(f"Failed to upload image for '{word}'. Rolling back approval.")
with file_lock:
# Remove the word from approved_data
approved_data.pop(word, None)
atomic_write(OUTPUT_APPROVED_JSON, approved_data)
# Re-add the word back to data_json
with open(OUTPUT_JSON, 'r', encoding='utf-8') as f:
data_json = json.load(f)
data_json[word] = word_data
atomic_write(OUTPUT_JSON, data_json)
return jsonify({"error": f"Failed to upload image for '{word}'."}), 500
else:
app.logger.warning(f"No image path found for '{word}'.")
return jsonify({"message": f"'{word}' has been approved and image uploaded."}), 200
except json.JSONDecodeError as jde:
app.logger.error(f"JSON decode error: {jde}")
return jsonify({"error": "Invalid JSON format."}), 400
except Exception as e:
app.logger.error(f"Error in /api/approve: {e}")
return jsonify({"error": str(e)}), 500
@app.route('/api/delete', methods=['POST'])
def delete_word():
"""
Deletes a specific word from output2.json.
"""
try:
app.logger.info(f"Received delete request data: {request.data}")
data = request.get_json()
if not data:
app.logger.error("Invalid JSON data.")
return jsonify({"error": "Invalid JSON data."}), 400
word = data.get('word')
if not word:
app.logger.error("Word not specified.")
return jsonify({"error": "Word not specified."}), 400
with file_lock:
# Load output2.json
with open(OUTPUT_JSON, 'r', encoding='utf-8') as f:
data_json = json.load(f)
if word not in data_json:
app.logger.error(f"'{word}' not found in {OUTPUT_JSON}.")
return jsonify({"error": f"'{word}' not found in {OUTPUT_JSON}."}), 404
data_json.pop(word)
# Atomically write updated data_json
atomic_write(OUTPUT_JSON, data_json)
app.logger.info(f"'{word}' has been deleted successfully.")
return jsonify({"message": f"'{word}' has been deleted."}), 200
except json.JSONDecodeError as jde:
app.logger.error(f"JSON decode error: {jde}")
return jsonify({"error": "Invalid JSON format."}), 400
except Exception as e:
app.logger.error(f"Error in /api/delete: {e}")
return jsonify({"error": str(e)}), 500
@app.route('/api/download_all_pollinations_images', methods=['POST'])
def download_all_pollinations_images():
"""
Downloads all Pollinations.ai image URLs from output2.json, saves them locally,
updates output2.json with the local paths.
"""
def download_images():
try:
with file_lock:
with open(OUTPUT_JSON, 'r', encoding='utf-8') as f:
data_json = json.load(f)
if not data_json:
app.logger.info("output2.json is empty.")
return
updated = False # Flag to check if any updates are made
for word, details in data_json.items():
image_url = details.get('image')
if not image_url:
app.logger.warning(f"No image URL for '{word}'.")
continue
# Skip if already downloaded
if image_url.startswith('/approvedimages/'):
app.logger.info(f"Image for '{word}' is already downloaded: {image_url}")
continue
if not (image_url.startswith('http://') or image_url.startswith('https://')):
app.logger.warning(f"Invalid image URL format for '{word}': {image_url}")
continue
try:
response = requests.get(image_url, timeout=20)
response.raise_for_status()
except requests.RequestException as e:
app.logger.error(f"Failed to download image for '{word}': {e}")
continue
# Determine file extension
parsed_url = urlparse(image_url)
_, ext = os.path.splitext(parsed_url.path)
if ext.lower() not in ALLOWED_EXTENSIONS:
ext = '.jpg' # Default extension
# Generate a unique filename
unique_id = uuid.uuid4().hex
filename = f"{unique_id}{ext}"
# Save the image locally
filepath = os.path.join(APPROVED_IMAGES_DIR, filename)
with open(filepath, 'wb') as img_file:
img_file.write(response.content)
# Update the image path in data_json
with file_lock:
data_json[word]['image'] = f"/approvedimages/{filename}"
atomic_write(OUTPUT_JSON, data_json)
updated = True
app.logger.info(f"Image for '{word}' downloaded and saved as: {filename}")
if updated:
app.logger.info("All Pollinations.ai images have been downloaded and output2.json updated.")
else:
app.logger.info("No new images were downloaded.")
except Exception as e:
app.logger.error(f"Error in download_images: {e}")
# Start the download process in a new thread
threading.Thread(target=download_images).start()
return jsonify({"message": "Image download started in the background."}), 200
@app.route('/api/download', methods=['POST'])
def download_approved_images():
"""
Downloads images from outputapproved.json.
- If the image URL starts with http:// or https://, download and save locally.
- If the image is already in the /approvedimages/ directory, skip downloading.
"""
try:
with file_lock:
if not os.path.exists(OUTPUT_APPROVED_JSON):
return jsonify({"error": f"{OUTPUT_APPROVED_JSON} not found."}), 404
with open(OUTPUT_APPROVED_JSON, 'r', encoding='utf-8') as f:
approved_data = json.load(f)
if not approved_data:
return jsonify({"error": "No approved images found."}), 400
updated = False # Flag to check if any updates are made
for word, details in approved_data.items():
image_path = details.get('image')
if not image_path:
app.logger.warning(f"No image URL for '{word}'.")
continue
# Skip if already downloaded
if image_path.startswith('/approvedimages/'):
app.logger.info(f"Image for '{word}' is already local: {image_path}")
continue
if image_path.startswith('http://') or image_path.startswith('https://'):
try:
response = requests.get(image_path, timeout=20)
response.raise_for_status()
except requests.RequestException as e:
app.logger.error(f"Failed to download image for '{word}': {e}")
continue
# Determine file extension
parsed_url = urlparse(image_path)
_, ext = os.path.splitext(parsed_url.path)
if ext.lower() not in ALLOWED_EXTENSIONS:
ext = '.jpg' # Default extension
# Generate a unique filename
unique_id = uuid.uuid4().hex
filename = f"{unique_id}{ext}"
# Save the image locally
filepath = os.path.join(APPROVED_IMAGES_DIR, filename)
with open(filepath, 'wb') as img_file:
img_file.write(response.content)
# Update the image path in approved_data
with file_lock:
approved_data[word]['image'] = f"/approvedimages/{filename}"
atomic_write(OUTPUT_APPROVED_JSON, approved_data)
updated = True
app.logger.info(f"Image for '{word}' downloaded and saved as: {filename}")
else:
app.logger.warning(f"Invalid image URL format for '{word}': {image_path}")
if updated:
app.logger.info("Approved images have been downloaded and outputapproved.json updated.")
return jsonify({"message": "Approved images downloaded and updated."}), 200
else:
app.logger.info("No new approved images were downloaded.")
return jsonify({"message": "No new approved images to download."}), 200
except Exception as e:
app.logger.error(f"Error in /api/download: {e}")
return jsonify({"error": str(e)}), 500
@app.route('/api/upload_to_firebase', methods=['POST'])
def upload_to_firebase_endpoint():
"""
Uploads images from outputapproved.json to Firebase Storage,
updates Firestore documents, and removes the image entries from outputapproved.json.
"""
try:
with file_lock:
if not os.path.exists(OUTPUT_APPROVED_JSON):
return jsonify({"error": f"{OUTPUT_APPROVED_JSON} not found."}), 404
with open(OUTPUT_APPROVED_JSON, 'r', encoding='utf-8') as f:
approved_data = json.load(f)
if not approved_data:
return jsonify({"error": "No approved images to upload."}), 400
success_uploads = []
failed_uploads = []
for word, details in approved_data.items():
image_path = details.get('image')
if not image_path:
app.logger.warning(f"No image path for '{word}'.")
continue
# Ensure the image is local
if not image_path.startswith('/approvedimages/'):
app.logger.warning(f"Image for '{word}' is not local: {image_path}")
continue
local_image_path = os.path.join(BASE_DIR, image_path.lstrip('/'))
if not os.path.exists(local_image_path):
app.logger.error(f"Local image file not found for '{word}': {local_image_path}")
failed_uploads.append({"word": word, "error": "Image file not found."})
continue
try:
# Upload to Firebase Storage under 'dictionaryimages' folder
blob = bucket.blob(f"dictionaryimages/{secure_filename(os.path.basename(local_image_path))}")
blob.upload_from_filename(local_image_path)
# Make the blob publicly accessible and get its URL
blob.make_public()
firebase_image_url = blob.public_url
# Update the Firestore document
doc_ref = db.collection('dictionary').document(word)
doc_ref.update({"image": firebase_image_url})
# Mark for removal from approved_data
success_uploads.append(word)
app.logger.info(f"Image for '{word}' uploaded to Firebase: {firebase_image_url}")
except Exception as e:
app.logger.error(f"Failed to upload image for '{word}' to Firebase: {e}")
failed_uploads.append({"word": word, "error": str(e)})
# Remove successfully uploaded words from approved_data
with file_lock:
for word in success_uploads:
approved_data.pop(word, None)
atomic_write(OUTPUT_APPROVED_JSON, approved_data)
response = {
"message": "Firebase upload process completed.",
"success_uploads": success_uploads,
"failed_uploads": failed_uploads
}
return jsonify(response), 200
except Exception as e:
app.logger.error(f"Error in /api/upload_to_firebase: {e}")
return jsonify({"error": str(e)}), 500
@app.route('/approvedimages/<filename>', methods=['GET'])
def serve_image(filename):
"""
Serves images from the approvedimages directory.
"""
try:
safe_filename = secure_filename(filename)
return send_from_directory(APPROVED_IMAGES_DIR, safe_filename, as_attachment=False)
except FileNotFoundError:
return jsonify({"error": "File not found."}), 404
except Exception as e:
app.logger.error(f"Error serving image '{filename}': {e}")
return jsonify({"error": "Internal server error."}), 500
@app.route('/', methods=['GET'])
def index():
"""
Serves the index.html file.
"""
return send_from_directory(BASE_DIR, 'index.html')
@app.route('/<path:path>', methods=['GET'])
def static_proxy(path):
"""
Serves static files (CSS, JS, etc.).
"""
try:
return send_from_directory(BASE_DIR, path)
except FileNotFoundError:
return jsonify({"error": "File not found."}), 404
except Exception as e:
app.logger.error(f"Error serving static file '{path}': {e}")
return jsonify({"error": "Internal server error."}), 500
# -------------------------------
# Main Entry Point
# -------------------------------
if __name__ == '__main__':
# It's recommended to set debug=False in production
app.run(host='0.0.0.0', port=5000, debug=True)
Key Highlights:
-
Synchronous Image Upload: Ensures that image uploads complete successfully before approving a word.
-
Enhanced Error Handling: Proper rollback mechanisms to maintain data integrity.
-
Security Enhancements: Validates image formats and sizes.
-
Environment Configuration: Uses environment variables for sensitive configurations.
5. Frontend (script.js) Final Recommendations
Ensure that the frontend handles the updated responses appropriately. Here's a brief overview of the necessary components:
a. Approve Word and Reflect Updates
When a word is approved, the backend now returns a message confirming both approval and image upload. You can adjust the frontend to inform the user accordingly.
Example Adjustment:
function approveWord(word) {
console.log(`Approving word: ${word}`); // Added log
fetch('/api/approve', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ word })
})
.then(response => {
if (!response.ok) {
return response.json().then(data => { throw new Error(data.error || 'İstek başarısız'); });
}
return response.json();
})
.then(data => {
if (data.message) {
console.log(data.message);
alert(data.message); // Inform the user about successful approval and upload
} else if (data.error) {
alert(`Hata: ${data.error}`);
}
nextWord();
})
.catch(error => {
console.error('Hata:', error);
alert('Kelime onaylanırken bir hata oluştu.');
nextWord();
});
}
b. Optional: Update Display with Firebase Image URL
If you want the approved words to display images directly from Firebase, ensure that the frontend fetches the latest image URLs. This is already handled if the /api/words endpoint returns updated data.
c. Handle Reloads Appropriately
After approving a word, if you choose to reload the page to fetch the latest data, ensure that it's done gracefully without disrupting the user experience.
6. Testing the Workflow
After implementing the above changes, perform thorough testing to ensure that:
-
Approval Process:
- When approving a word, it is moved from
output2.json to outputapproved.json.
- The associated image is uploaded to Firebase Storage.
- The Firestore document for the word is updated with the Firebase image URL.
- The local
outputapproved.json reflects the new Firebase image URL.
-
Error Handling:
- If the image upload fails, the word is not marked as approved, and appropriate error messages are logged and displayed.
-
Frontend Reflection:
- After approval, the frontend fetches and displays the updated image URL.
- User feedback is clear and indicative of the process status.
-
Security and Validation:
- Only valid image formats and sizes are processed.
- Unauthorized access to API endpoints is restricted (if authentication is implemented).
By following the above steps and implementing the recommended changes, your application should successfully handle the approval of words, automatic uploading of images to Firebase, and updating Firestore with the relevant image URLs. Additionally, the frontend will accurately reflect these changes, providing a seamless user experience.