Do not load code in gr.NO_RELOAD in the reload mode watch thread (#9886)

* add code

* add changeset

* no if __name__ reload twice

---------

Co-authored-by: gradio-pr-bot <gradio-pr-bot@users.noreply.github.com>
This commit is contained in:
Freddy Boulton 2024-11-04 16:50:52 -05:00 committed by GitHub
parent b6725cf6c1
commit fa5d4339d6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 28 additions and 2 deletions

View File

@ -0,0 +1,5 @@
---
"gradio": patch
---
fix:Do not load code in gr.NO_RELOAD in the reload mode watch thread

View File

@ -2,6 +2,7 @@ from __future__ import annotations
import os
import socket
import sys
import threading
import time
from functools import partial
@ -144,6 +145,7 @@ def start_server(
demo_name=GRADIO_WATCH_DEMO_NAME,
stop_event=threading.Event(),
demo_file=GRADIO_WATCH_DEMO_PATH,
watch_module=sys.modules["__main__"],
)
server = Server(config=config, reloader=reloader)
server.run_in_thread()

View File

@ -136,6 +136,7 @@ class SourceFileReloader(BaseReloader):
watch_dirs: list[str],
watch_module_name: str,
demo_file: str,
watch_module: ModuleType,
stop_event: threading.Event,
demo_name: str = "demo",
) -> None:
@ -146,6 +147,7 @@ class SourceFileReloader(BaseReloader):
self.stop_event = stop_event
self.demo_name = demo_name
self.demo_file = Path(demo_file)
self.watch_module = watch_module
@property
def running_app(self) -> App:
@ -195,9 +197,22 @@ def _remove_no_reload_codeblocks(file_path: str):
and expr.test.attr == "NO_RELOAD"
)
def _is_if_name_main(expr: ast.AST) -> bool:
"""Find the if __name__ == '__main__': block."""
return (
isinstance(expr, ast.If)
and isinstance(expr.test, ast.Compare)
and isinstance(expr.test.left, ast.Name)
and expr.test.left.id == "__name__"
and len(expr.test.ops) == 1
and isinstance(expr.test.ops[0], ast.Eq)
and isinstance(expr.test.comparators[0], ast.Constant)
and expr.test.comparators[0].s == "__main__"
)
# Find the positions of the code blocks to load
for node in ast.walk(tree):
if _is_gr_no_reload(node):
if _is_gr_no_reload(node) or _is_if_name_main(node):
assert isinstance(node, ast.If) # noqa: S101
node.body = [ast.Pass(lineno=node.lineno, col_offset=node.col_offset)]
@ -259,7 +274,11 @@ def watchfn(reloader: SourceFileReloader):
mtimes = {}
# Need to import the module in this thread so that the
# module is available in the namespace of this thread
module = importlib.import_module(reloader.watch_module_name)
module = reloader.watch_module
no_reload_source_code = _remove_no_reload_codeblocks(str(reloader.demo_file))
exec(no_reload_source_code, module.__dict__)
sys.modules[reloader.watch_module_name] = module
while reloader.should_watch():
changed = get_changes()
if changed: