This repository has been archived on 2026-05-31. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
imagerepo/image_import_worker.py
T
2025-08-05 10:21:49 -04:00

92 lines
3.9 KiB
Python

# image_import_worker.py
import time
import os
from app import create_app
from app.utils.image_importer import import_images_task
THUMBNAIL_FLAG = "/import/thumbnail.flag"
TRIGGER_FLAG = "/import/trigger.flag"
SOURCE_DIR = "/import"
DEST_DIR = "/images"
CHECK_INTERVAL = 10 # seconds
app = create_app()
from sqlalchemy.exc import OperationalError
import time
def monitor_and_import():
with app.app_context():
print("[Image Importer] Monitoring for trigger flag...")
while True:
if os.path.exists(TRIGGER_FLAG):
print("[Image Importer] Trigger flag found. Starting import...")
max_retries = 3
attempt = 0
while attempt < max_retries:
try:
result = import_images_task(SOURCE_DIR, DEST_DIR)
print(f"[Image Importer] {result}")
break # Exit retry loop if successful
except OperationalError as e:
attempt += 1
print(f"[Image Importer] Database error during import (attempt {attempt}): {e}")
if attempt >= max_retries:
print("[Image Importer] Max retries reached. Import failed.")
else:
sleep_time = 2 ** attempt
print(f"[Image Importer] Retrying in {sleep_time} seconds...")
time.sleep(sleep_time)
except Exception as e:
print(f"[Image Importer] Unexpected error during import: {e}")
break
finally:
try:
os.remove(TRIGGER_FLAG)
print("[Image Importer] Trigger flag cleared.")
except Exception as e:
print(f"[Image Importer] Failed to remove trigger flag: {e}")
# Thumbnail regeneration
if os.path.exists(THUMBNAIL_FLAG):
print("[Image Importer] Thumbnail regeneration triggered.")
max_retries = 3
attempt = 0
while attempt < max_retries:
try:
from app.models import ImageRecord
from app.utils.image_importer import generate_thumbnail
for img in ImageRecord.query.all():
try:
generate_thumbnail(img.filepath, overwrite=True)
print(f"[Thumbnail] Regenerated for {img.filename}")
except Exception as e:
print(f"[Thumbnail] Failed for {img.filename}: {e}")
break # Success
except OperationalError as e:
attempt += 1
print(f"[Image Importer] Database error during thumbnail regen (attempt {attempt}): {e}")
if attempt >= max_retries:
print("[Image Importer] Max retries reached. Thumbnail regeneration failed.")
else:
sleep_time = 2 ** attempt
print(f"[Image Importer] Retrying in {sleep_time} seconds...")
time.sleep(sleep_time)
except Exception as e:
print(f"[Image Importer] Unexpected error during thumbnail regen: {e}")
break
finally:
try:
os.remove(THUMBNAIL_FLAG)
print("[Image Importer] Thumbnail flag cleared.")
except Exception as e:
print(f"[Image Importer] Failed to remove thumbnail flag: {e}")
if __name__ == '__main__':
monitor_and_import()