@app.route('/api/words', methods=['GET'])
def get_words():
"""
output2.json dosyasındaki tüm kelimeleri döndürür.
"""
try:
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} dosyası bulunamadı."}), 404
except json.JSONDecodeError:
return jsonify({"error": f"{OUTPUT_JSON} dosyası hatalı veya boş."}), 400
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/approve', methods=['POST'])
def approve_word():
"""
Belirli bir kelimeyi onaylar: output2.json'dan çıkarır ve outputapproved.json'a ekler.
Ayrıca, görseli arka planda Firebase'e yükler.
"""
def upload_image_to_firebase(word, image_path):
try:
# Resim dosyasını bul
local_image_path = os.path.join(BASE_DIR, image_path.lstrip('/'))
code
Assistant
# Firestore Storage'da dictionaryimages klasörüne yükleme
blob = bucket.blob(f"dictionaryimages/{secure_filename(os.path.basename(local_image_path))}")
blob.upload_from_filename(local_image_path)
# Yüklenen dosyanın herkese açık URL'sini al
blob.make_public()
firebase_image_url = blob.public_url
# Firestore'daki dictionary/<word> belgesini güncelle
doc_ref = db.collection('dictionary').document(word)
doc_ref.update({"image": firebase_image_url})
app.logger.info(f"'{word}' kelimesi için resim başarıyla Firebase'e yüklendi: {firebase_image_url}")
# Eğer isterseniz, outputapproved.json'dan image linkini kaldırabilirsiniz
# Ancak bu örnekte yapmadım
except Exception as e:
app.logger.error(f"'{word}' kelimesi için resim yüklenirken hata oluştu: {e}")
try:
app.logger.info(f"Received request data: {request.data}") # Gelen ham veriyi logla
app.logger.info(f"Request JSON: {request.json}") # Gelen JSON verisini logla
data = request.get_json()
if not data:
app.logger.error("Geçersiz JSON verisi.")
return jsonify({"error": "Geçersiz JSON verisi."}), 400
word = data.get('word')
if not word:
app.logger.error("Kelime belirtilmedi.")
return jsonify({"error": "Kelime belirtilmedi."}), 400
# output2.json'dan kelimeyi çıkar
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}' kelimesi {OUTPUT_JSON} dosyasında bulunamadı.")
return jsonify({"error": f"'{word}' kelimesi {OUTPUT_JSON} dosyasında bulunamadı."}), 404
word_data = data_json.pop(word)
# outputapproved.json'a ekle
with open(OUTPUT_APPROVED_JSON, 'r', encoding='utf-8') as f:
approved_data = json.load(f)
# In case outputapproved.json was empty but existed
if not isinstance(approved_data, dict):
approved_data = {}
approved_data[word] = word_data
with open(OUTPUT_APPROVED_JSON, 'w', encoding='utf-8') as f:
json.dump(approved_data, f, ensure_ascii=False, indent=4)
# output2.json'u güncelle
with open(OUTPUT_JSON, 'w', encoding='utf-8') as f:
json.dump(data_json, f, ensure_ascii=False, indent=4)
app.logger.info(f"'{word}' kelimesi başarıyla onaylandı.")
# Görseli arka planda Firebase'e yükleme
image_path = word_data.get('image')
if image_path:
threading.Thread(target=upload_image_to_firebase, args=(word, image_path)).start()
else:
app.logger.warning(f"'{word}' kelimesi için resim yolu bulunamadı.")
return jsonify({"message": f"'{word}' kelimesi onaylandı."}), 200
except json.JSONDecodeError as jde:
app.logger.error(f"JSON decode error: {jde}")
return jsonify({"error": "Geçersiz JSON formatı."}), 400
except Exception as e:
app.logger.error(f"Error in /api/approve: {e}") # Hata mesajını logla
return jsonify({"error": str(e)}), 500
@app.route('/api/delete', methods=['POST'])
def delete_word():
"""
Belirli bir kelimeyi output2.json dosyasından siler.
"""
try:
app.logger.info(f"Received request data: {request.data}") # Gelen ham veriyi logla
app.logger.info(f"Request JSON: {request.json}") # Gelen JSON verisini logla
code
data = request.get_json()
if not data:
app.logger.error("Geçersiz JSON verisi.")
return jsonify({"error": "Geçersiz JSON verisi."}), 400
word = data.get('word')
if not word:
app.logger.error("Kelime belirtilmedi.")
return jsonify({"error": "Kelime belirtilmedi."}), 400
# output2.json'dan kelimeyi çıkar
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}' kelimesi {OUTPUT_JSON} dosyasında bulunamadı.")
return jsonify({"error": f"'{word}' kelimesi {OUTPUT_JSON} dosyasında bulunamadı."}), 404
data_json.pop(word)
# output2.json'u güncelle
with open(OUTPUT_JSON, 'w', encoding='utf-8') as f:
json.dump(data_json, f, ensure_ascii=False, indent=4)
app.logger.info(f"'{word}' kelimesi başarıyla silindi.")
return jsonify({"message": f"'{word}' kelimesi silindi."}), 200
except json.JSONDecodeError as jde:
app.logger.error(f"JSON decode error: {jde}")
return jsonify({"error": "Geçersiz 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():
"""
output2.json dosyasındaki tüm Pollinations.ai görüntü URL'lerini indirir,
approvedimages klasörüne kaydeder ve output2.json dosyasındaki linkleri günceller.
"""
def download_images():
try:
with open(OUTPUT_JSON, 'r', encoding='utf-8') as f:
data_json = json.load(f)
code
if not data_json:
app.logger.info("output2.json boş.")
return
for word, details in data_json.items():
image_url = details.get('image')
if not image_url:
app.logger.warning(f"'{word}' kelimesi için resim URL'si yok.")
continue
# Eğer image_path zaten yerel ise atla
if image_url.startswith('/approvedimages/'):
app.logger.info(f"'{word}' kelimesi için resim zaten indirildi: {image_url}")
continue
if not (image_url.startswith('http://') or image_url.startswith('https://')):
app.logger.warning(f"'{word}' kelimesi için geçersiz resim URL formatı: {image_url}")
continue
try:
response = requests.get(image_url, timeout=20)
response.raise_for_status()
except requests.RequestException as e:
app.logger.error(f"'{word}' kelimesi için resim indirilemedi: {e}")
continue
# Dosya uzantısını belirle
parsed_url = urlparse(image_url)
_, ext = os.path.splitext(parsed_url.path)
if ext.lower() not in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']:
ext = '.jpg' # Varsayılan uzantı
# UUID ile benzersiz dosya adı oluştur
unique_id = uuid.uuid4().hex
filename = f"{unique_id}{ext}"
# Dosya yolunu belirle
filepath = os.path.join(APPROVED_IMAGES_DIR, filename)
# Resmi kaydet
with open(filepath, 'wb') as img_file:
img_file.write(response.content)
# JSON'daki image yolunu güncelle
data_json[word]['image'] = f"/approvedimages/{filename}"
app.logger.info(f"'{word}' kelimesi için resim indirildi ve kaydedildi: {filename}")
# output2.json'u güncelle
with open(OUTPUT_JSON, 'w', encoding='utf-8') as f:
json.dump(data_json, f, ensure_ascii=False, indent=4)
app.logger.info("Tüm Pollinations.ai resimleri indirildi ve output2.json güncellendi.")
except Exception as e:
app.logger.error(f"download_images fonksiyonunda hata oluştu: {e}")
# İndirme işlemini arka planda başlat
threading.Thread(target=download_images).start()
return jsonify({"message": "Resim indirme işlemi arka planda başlatıldı."}), 200
@app.route('/api/download', methods=['POST'])
def download_approved_images():
"""
outputapproved.json dosyasındaki resimleri indirir.
- Eğer resim URL'si http:// veya https:// ile başlıyorsa indir ve /approvedimages/ dizinine kaydet.
- Eğer resim zaten /approvedimages/ dizinindeyse, indirmez.
"""
try:
# outputapproved.json dosyasının olup olmadığını kontrol et
if not os.path.exists(OUTPUT_APPROVED_JSON):
return jsonify({"error": f"{OUTPUT_APPROVED_JSON} dosyası bulunamadı."}), 404
code
# approved_data'yı yükle
with open(OUTPUT_APPROVED_JSON, 'r', encoding='utf-8') as f:
approved_data = json.load(f)
if not approved_data:
return jsonify({"error": "Onaylanmış resim bulunamadı."}), 400
updated = False # Herhangi bir güncelleme yapılıp yapılmadığını kontrol etmek için
for word, details in approved_data.items():
image_path = details.get('image')
if not image_path:
app.logger.warning(f"'{word}' için resim URL bulunamadı.")
continue
# Resmin zaten yerel olup olmadığını kontrol et
if image_path.startswith('/approvedimages/'):
app.logger.info(f"'{word}' için resim zaten yerel: {image_path}")
continue
elif image_path.startswith('http://') or image_path.startswith('https://'):
# Resmi indir
try:
response = requests.get(image_path, timeout=10)
response.raise_for_status()
except requests.RequestException as e:
app.logger.error(f"Resim indirilemedi '{image_path}': {e}")
continue
# Dosya uzantısını belirle
parsed_url = urlparse(image_path)
_, ext = os.path.splitext(parsed_url.path)
if ext.lower() not in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']:
ext = '.jpg' # Varsayılan uzantı
# UUID ile benzersiz dosya adı oluştur
unique_id = uuid.uuid4().hex
filename = f"{unique_id}{ext}"
# Dosya yolunu belirle
filepath = os.path.join(APPROVED_IMAGES_DIR, filename)
# Resmi kaydet
with open(filepath, 'wb') as img_file:
img_file.write(response.content)
# JSON'daki image yolunu güncelle
approved_data[word]['image'] = f"/approvedimages/{filename}"
updated = True
app.logger.info(f"'{word}' kelimesi için resim indirildi ve kaydedildi: {filename}")
else:
app.logger.warning(f"'{word}' için geçersiz resim URL formatı: {image_path}")
continue
if updated:
# Güncellenmiş veriyi kaydet
with open(OUTPUT_APPROVED_JSON, 'w', encoding='utf-8') as f:
json.dump(approved_data, f, ensure_ascii=False, indent=4)
app.logger.info("Güncellenmiş resimler başarıyla indirildi ve kaydedildi.")
return jsonify({"message": "Güncellenmiş resimler indirildi ve kaydedildi."}), 200
else:
app.logger.info("İndirilmesi gereken yeni resim bulunamadı.")
return jsonify({"message": "İndirilmesi gereken yeni resim bulunamadı."}), 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():
"""
outputapproved.json dosyasındaki resimleri Firebase Storage'e yükler,
Firestore'daki ilgili belgeleri günceller ve resimleri outputapproved.json'dan çıkarır.
"""
try:
# outputapproved.json dosyasını yükle
if not os.path.exists(OUTPUT_APPROVED_JSON):
return jsonify({"error": f"{OUTPUT_APPROVED_JSON} dosyası bulunamadı."}), 404
code
with open(OUTPUT_APPROVED_JSON, 'r', encoding='utf-8') as f:
approved_data = json.load(f)
if not approved_data:
return jsonify({"error": "Onaylanmış resim bulunamadı."}), 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"'{word}' için resim URL bulunamadı.")
continue
# Resmin yerel olup olmadığını kontrol et
if not image_path.startswith('/approvedimages/'):
app.logger.warning(f"'{word}' için resim yerel klasörden değil: {image_path}. Atlanıyor.")
continue
# Resim dosyasını bul
local_image_path = os.path.join(BASE_DIR, image_path.lstrip('/'))
if not os.path.exists(local_image_path):
app.logger.error(f"Yerel resim dosyası bulunamadı: {local_image_path}")
failed_uploads.append({"word": word, "error": "Resim dosyası bulunamadı."})
continue
try:
# Firestore Storage'da dictionaryimages klasörüne yükleme
blob = bucket.blob(f"dictionaryimages/{secure_filename(os.path.basename(local_image_path))}")
blob.upload_from_filename(local_image_path)
# Yüklenen dosyanın herkese açık URL'sini al
blob.make_public()
firebase_image_url = blob.public_url
# Firestore'daki dictionary/<word> belgesini güncelle
doc_ref = db.collection('dictionary').document(word)
doc_ref.update({"image": firebase_image_url})
# outputapproved.json'dan kaldırmak için işaretle
success_uploads.append(word)
app.logger.info(f"'{word}' kelimesi için resim başarıyla yüklendi: {firebase_image_url}")
except Exception as e:
app.logger.error(f"'{word}' kelimesi için resim yüklenirken hata oluştu: {e}")
failed_uploads.append({"word": word, "error": str(e)})
# Başarıyla yüklenen kelimeleri outputapproved.json'dan çıkar
for word in success_uploads:
approved_data.pop(word, None)
# outputapproved.json'u güncelle
with open(OUTPUT_APPROVED_JSON, 'w', encoding='utf-8') as f:
json.dump(approved_data, f, ensure_ascii=False, indent=4)
response = {
"message": "İşlem tamamlandı.",
"success_uploads": success_uploads,
"failed_uploads": failed_uploads
}
return jsonify(response), 200
except Exception as e:
app.logger.error(f"/api/upload_to_firebase endpoint'inde hata oluştu: {e}")
return jsonify({"error": str(e)}), 500
burada pollination.ai görselleri indirildiği anda output2.json dosyasına o indirilen resim linki yansısın istiyorum. anında güncellenecek indirilen resmin yolu yazılacak.
To achieve real-time updates to the output2.json file each time a Pollinations.ai image is downloaded, you'll need to modify the download_images function within the download_all_pollinations_images endpoint. Specifically, after each image is successfully downloaded and its path is updated in the data_json dictionary, you should immediately write the updated data_json back to output2.json.
However, since multiple threads might access and modify output2.json concurrently (e.g., other endpoints like /api/approve, /api/delete, etc.), it's crucial to ensure thread safety during file read/write operations. To handle this, we'll introduce a threading lock that ensures only one thread can read or write to output2.json at a time.
Below are the steps and the modified code to implement this functionality:
1. Introduce a Threading Lock
First, create a global threading lock that will be used to synchronize access to output2.json and outputapproved.json.
python
# Add this at the top of your script, preferably after your imports
file_lock = threading.Lock()
2. Modify the download_images Function
Update the download_images function to acquire the lock before reading and writing to output2.json. After downloading each image and updating its path, immediately write the updated data_json back to the file within the locked context.
Here's the updated download_images function:
python
def download_images():
try:
with file_lock: # Acquire the lock before reading the file
with open(OUTPUT_JSON, 'r', encoding='utf-8') as f:
data_json = json.load(f)
if not data_json:
app.logger.info("output2.json boş.")
return
for word, details in data_json.items():
image_url = details.get('image')
if not image_url:
app.logger.warning(f"'{word}' kelimesi için resim URL'si yok.")
continue
# Eğer image_path zaten yerel ise atla
if image_url.startswith('/approvedimages/'):
app.logger.info(f"'{word}' kelimesi için resim zaten indirildi: {image_url}")
continue
if not (image_url.startswith('http://') or image_url.startswith('https://')):
app.logger.warning(f"'{word}' kelimesi için geçersiz resim URL formatı: {image_url}")
continue
try:
response = requests.get(image_url, timeout=20)
response.raise_for_status()
except requests.RequestException as e:
app.logger.error(f"'{word}' kelimesi için resim indirilemedi: {e}")
continue
# Dosya uzantısını belirle
parsed_url = urlparse(image_url)
_, ext = os.path.splitext(parsed_url.path)
if ext.lower() not in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']:
ext = '.jpg' # Varsayılan uzantı
# UUID ile benzersiz dosya adı oluştur
unique_id = uuid.uuid4().hex
filename = f"{unique_id}{ext}"
# Dosya yolunu belirle
filepath = os.path.join(APPROVED_IMAGES_DIR, filename)
# Resmi kaydet
with open(filepath, 'wb') as img_file:
img_file.write(response.content)
# JSON'daki image yolunu güncelle
with file_lock: # Acquire the lock before writing to the file
data_json[word]['image'] = f"/approvedimages/{filename}"
with open(OUTPUT_JSON, 'w', encoding='utf-8') as f:
json.dump(data_json, f, ensure_ascii=False, indent=4)
app.logger.info(f"'{word}' kelimesi için resim indirildi ve kaydedildi: {filename}")
app.logger.info("Tüm Pollinations.ai resimleri indirildi ve output2.json güncellendi.")
except Exception as e:
app.logger.error(f"download_images fonksiyonunda hata oluştu: {e}")
3. Complete Updated Code Snippet
Here's the complete updated download_all_pollinations_images endpoint with the necessary modifications:
python
4. Applying the Lock to Other Endpoints
It's essential to ensure that all endpoints that read from or write to output2.json and outputapproved.json use the same lock to prevent race conditions. Here's how you can modify other relevant endpoints:
Example for /api/approve Endpoint
python
Note: Apply similar lock mechanisms (file_lock.acquire() and file_lock.release(), or using with file_lock: context managers) to other endpoints that interact with output2.json and outputapproved.json to ensure thread safety.
5. Additional Recommendations
Logging Enhancements: To better monitor the real-time updates, consider enhancing your logging statements to include timestamps or other relevant information.
Error Handling: Ensure that all file operations are wrapped in try-except blocks to gracefully handle unexpected errors, especially when dealing with file I/O.
Performance Considerations: While frequent writes to JSON files are manageable for small datasets, consider migrating to a database like Firestore or SQLite for better scalability and performance if your dataset grows.
Atomic File Writes: To prevent file corruption in rare cases where the application might crash during a write operation, consider writing to a temporary file first and then renaming it to output2.json. Python's tempfile module can be helpful for this purpose.
Here's how you can implement atomic writes using a temporary file:
Then, replace the json.dump lines with atomic_write:
python
with file_lock:
data_json[word]['image'] = f"/approvedimages/{filename}"
atomic_write(OUTPUT_JSON, data_json)
This approach ensures that output2.json is always in a valid state, even if an error occurs during the write process.
6. Final Thoughts
Implementing the above changes will ensure that output2.json is updated in real-time as each image is downloaded and processed. The introduction of a threading lock guarantees that simultaneous read and write operations do not corrupt the JSON files, maintaining data integrity across different endpoints and threads.
If you encounter any issues or have further questions, feel free to ask!
import os
import json
import uuid
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
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "*"}})
# Proje dizinini belirleme
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# Dosya yollarını güncelleme
DATA_DIR = os.path.join(BASE_DIR, 'data')
OUTPUT_JSON = os.path.join(DATA_DIR, 'output2.json') # 'data' klasörü içinde
OUTPUT_APPROVED_JSON = os.path.join(DATA_DIR, 'outputapproved.json')
APPROVED_IMAGES_DIR = os.path.join(BASE_DIR, 'approvedimages')
# Onaylı resimler için klasör oluştur
if not os.path.exists(APPROVED_IMAGES_DIR):
os.makedirs(APPROVED_IMAGES_DIR)
# output2.json ve outputapproved.json dosyalarını oluştur (eğer yoksa)
if not os.path.exists(OUTPUT_JSON):
with open(OUTPUT_JSON, 'w', encoding='utf-8') as f:
json.dump({}, f)
if not os.path.exists(OUTPUT_APPROVED_JSON):
with open(OUTPUT_APPROVED_JSON, 'w', encoding='utf-8') as f:
json.dump({}, f)
# Firebase Admin SDK'yı başlatma
FIREBASE_CREDENTIALS = 'cre.json' # Servis hesabı anahtar dosyanızın yolu
if not os.path.exists(FIREBASE_CREDENTIALS):
app.logger.critical(f"Firebase servis hesabı anahtarı bulunamadı: {FIREBASE_CREDENTIALS}")
exit(1)
cred = credentials.Certificate(FIREBASE_CREDENTIALS)
firebase_admin.initialize_app(cred, {
'storageBucket': 'readarabic-dec46.appspot.com' # Firestore Storage Bucket adınız
})
db = firestore.client()
bucket = storage.bucket()
# Create a global threading lock
file_lock = threading.Lock()
@app.route('/api/words', methods=['GET'])
def get_words():
"""
output2.json dosyasındaki tüm kelimeleri döndürür.
"""
try:
with file_lock: # Acquire the lock before reading the file
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} dosyası bulunamadı."}), 404
except json.JSONDecodeError:
return jsonify({"error": f"{OUTPUT_JSON} dosyası hatalı veya boş."}), 400
except Exception as e:
return jsonify({"error": str(e)}), 500
# ... [Other endpoints remain unchanged] ...
@app.route('/api/download_all_pollinations_images', methods=['POST'])
def download_all_pollinations_images():
"""
output2.json dosyasındaki tüm Pollinations.ai görüntü URL'lerini indirir,
approvedimages klasörüne kaydeder ve output2.json dosyasındaki linkleri günceller.
"""
def download_images():
try:
with file_lock: # Acquire the lock before reading the file
with open(OUTPUT_JSON, 'r', encoding='utf-8') as f:
data_json = json.load(f)
if not data_json:
app.logger.info("output2.json boş.")
return
for word, details in data_json.items():
image_url = details.get('image')
if not image_url:
app.logger.warning(f"'{word}' kelimesi için resim URL'si yok.")
continue
# Eğer image_path zaten yerel ise atla
if image_url.startswith('/approvedimages/'):
app.logger.info(f"'{word}' kelimesi için resim zaten indirildi: {image_url}")
continue
if not (image_url.startswith('http://') or image_url.startswith('https://')):
app.logger.warning(f"'{word}' kelimesi için geçersiz resim URL formatı: {image_url}")
continue
try:
response = requests.get(image_url, timeout=20)
response.raise_for_status()
except requests.RequestException as e:
app.logger.error(f"'{word}' kelimesi için resim indirilemedi: {e}")
continue
# Dosya uzantısını belirle
parsed_url = urlparse(image_url)
_, ext = os.path.splitext(parsed_url.path)
if ext.lower() not in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']:
ext = '.jpg' # Varsayılan uzantı
# UUID ile benzersiz dosya adı oluştur
unique_id = uuid.uuid4().hex
filename = f"{unique_id}{ext}"
# Dosya yolunu belirle
filepath = os.path.join(APPROVED_IMAGES_DIR, filename)
# Resmi kaydet
with open(filepath, 'wb') as img_file:
img_file.write(response.content)
# JSON'daki image yolunu güncelle
with file_lock: # Acquire the lock before writing to the file
data_json[word]['image'] = f"/approvedimages/{filename}"
with open(OUTPUT_JSON, 'w', encoding='utf-8') as f:
json.dump(data_json, f, ensure_ascii=False, indent=4)
app.logger.info(f"'{word}' kelimesi için resim indirildi ve kaydedildi: {filename}")
app.logger.info("Tüm Pollinations.ai resimleri indirildi ve output2.json güncellendi.")
except Exception as e:
app.logger.error(f"download_images fonksiyonunda hata oluştu: {e}")
# İndirme işlemini arka planda başlat
threading.Thread(target=download_images).start()
return jsonify({"message": "Resim indirme işlemi arka planda başlatıldı."}), 200
@app.route('/api/approve', methods=['POST'])
def approve_word():
"""
Belirli bir kelimeyi onaylar: output2.json'dan çıkarır ve outputapproved.json'a ekler.
Ayrıca, görseli arka planda Firebase'e yükler.
"""
def upload_image_to_firebase(word, image_path):
try:
# Resim dosyasını bul
local_image_path = os.path.join(BASE_DIR, image_path.lstrip('/'))
# Firestore Storage'da dictionaryimages klasörüne yükleme
blob = bucket.blob(f"dictionaryimages/{secure_filename(os.path.basename(local_image_path))}")
blob.upload_from_filename(local_image_path)
# Yüklenen dosyanın herkese açık URL'sini al
blob.make_public()
firebase_image_url = blob.public_url
# Firestore'daki dictionary/<word> belgesini güncelle
doc_ref = db.collection('dictionary').document(word)
doc_ref.update({"image": firebase_image_url})
app.logger.info(f"'{word}' kelimesi için resim başarıyla Firebase'e yüklendi: {firebase_image_url}")
# Eğer isterseniz, outputapproved.json'dan image linkini kaldırabilirsiniz
# Ancak bu örnekte yapmadım
except Exception as e:
app.logger.error(f"'{word}' kelimesi için resim yüklenirken hata oluştu: {e}")
try:
app.logger.info(f"Received request data: {request.data}") # Gelen ham veriyi logla
app.logger.info(f"Request JSON: {request.json}") # Gelen JSON verisini logla
data = request.get_json()
if not data:
app.logger.error("Geçersiz JSON verisi.")
return jsonify({"error": "Geçersiz JSON verisi."}), 400
word = data.get('word')
if not word:
app.logger.error("Kelime belirtilmedi.")
return jsonify({"error": "Kelime belirtilmedi."}), 400
with file_lock: # Acquire the lock before reading and writing the file
# output2.json'dan kelimeyi çıkar
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}' kelimesi {OUTPUT_JSON} dosyasında bulunamadı.")
return jsonify({"error": f"'{word}' kelimesi {OUTPUT_JSON} dosyasında bulunamadı."}), 404
word_data = data_json.pop(word)
# outputapproved.json'a ekle
with open(OUTPUT_APPROVED_JSON, 'r', encoding='utf-8') as f:
approved_data = json.load(f)
# In case outputapproved.json was empty but existed
if not isinstance(approved_data, dict):
approved_data = {}
approved_data[word] = word_data
with open(OUTPUT_APPROVED_JSON, 'w', encoding='utf-8') as f:
json.dump(approved_data, f, ensure_ascii=False, indent=4)
# output2.json'u güncelle
with open(OUTPUT_JSON, 'w', encoding='utf-8') as f:
json.dump(data_json, f, ensure_ascii=False, indent=4)
app.logger.info(f"'{word}' kelimesi başarıyla onaylandı.")
# Görseli arka planda Firebase'e yükleme
image_path = word_data.get('image')
if image_path:
threading.Thread(target=upload_image_to_firebase, args=(word, image_path)).start()
else:
app.logger.warning(f"'{word}' kelimesi için resim yolu bulunamadı.")
return jsonify({"message": f"'{word}' kelimesi onaylandı."}), 200
except json.JSONDecodeError as jde:
app.logger.error(f"JSON decode error: {jde}")
return jsonify({"error": "Geçersiz JSON formatı."}), 400
except Exception as e:
app.logger.error(f"Error in /api/approve: {e}") # Hata mesajını logla
return jsonify({"error": str(e)}), 500