Spaces:
Running
Running
File size: 2,002 Bytes
2978bba | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | #!/usr/bin/env python3
"""
scripts/data_watcher.py
Watches the data/ directories and auto-triggers detector training when new images arrive.
Requires: pip install watchdog requests
"""
import os
import time
import json
import requests
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
API_URL = os.environ.get('BASE_URL', 'http://localhost:5000')
SETTINGS_FILE = 'settings.json'
class NewImageHandler(FileSystemEventHandler):
def on_created(self, event):
if event.is_directory:
return
ext = os.path.splitext(event.src_path)[1].lower()
if ext in ('.jpg', '.jpeg', '.png'):
print(f"[Watcher] New image detected: {event.src_path}")
self.trigger_training()
def trigger_training(self):
# Load last training params
try:
with open(SETTINGS_FILE, 'r') as f:
params = json.load(f)
except Exception:
print("[Watcher] Could not read settings.json; skipping auto-retrain")
return
if not params.get('auto_retrain', False):
print("[Watcher] auto_retrain disabled in settings; skipping")
return
try:
resp = requests.post(f"{API_URL}/api/train/detector", json=params)
print(f"[Watcher] Auto-retrain triggered: {resp.status_code}, {resp.text}")
except Exception as e:
print(f"[Watcher] Error triggering retrain: {e}")
if __name__ == '__main__':
paths = [
'data/train/real',
'data/train/morph',
'data/val/real',
'data/val/morph'
]
event_handler = NewImageHandler()
observer = Observer()
for p in paths:
if os.path.isdir(p):
observer.schedule(event_handler, p, recursive=False)
print(f"[Watcher] Monitoring {p}" )
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join() |