File size: 2,163 Bytes
0168600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/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()