ai_ocr / dev.py
utarn's picture
init
0168600
raw
history blame
2.16 kB
#!/usr/bin/env python3
"""
Development script for auto-reloading the Gradio app when files change.
"""
import sys
import subprocess
import time
import os
from pathlib import Path
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class ReloadHandler(FileSystemEventHandler):
def __init__(self, command):
self.command = command
self.process = None
self.restart()
def on_modified(self, event):
if event.is_directory:
return
# Only restart for Python files and specific app files
if event.src_path.endswith(('.py', '.md', '.toml')):
print(f"Detected change in {event.src_path}")
self.restart()
def restart(self):
# Terminate the existing process if it exists
if self.process:
print("Terminating existing process...")
self.process.terminate()
try:
self.process.wait(timeout=5)
except subprocess.TimeoutExpired:
self.process.kill()
# Start a new process
print("Starting Gradio app...")
self.process = subprocess.Popen(self.command, shell=True)
def main():
# Get the directory of this script
script_dir = Path(__file__).parent.absolute()
# Command to run the Gradio app
command = "uv run python app.py"
# Create the event handler and observer
event_handler = ReloadHandler(command)
observer = Observer()
observer.schedule(event_handler, script_dir, recursive=True)
print("Watching for file changes...")
print("Press Ctrl+C to stop.")
# Start the observer
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\nStopping...")
observer.stop()
if event_handler.process:
event_handler.process.terminate()
try:
event_handler.process.wait(timeout=5)
except subprocess.TimeoutExpired:
event_handler.process.kill()
observer.join()
if __name__ == "__main__":
main()