ui_gradio_extensions.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import os
  2. import gradio as gr
  3. from modules import localization, shared, scripts, util
  4. from modules.paths import script_path, data_path
  5. def webpath(fn):
  6. return f'file={util.truncate_path(fn)}?{os.path.getmtime(fn)}'
  7. def javascript_html():
  8. # Ensure localization is in `window` before scripts
  9. head = f'<script type="text/javascript">{localization.localization_js(shared.opts.localization)}</script>\n'
  10. script_js = os.path.join(script_path, "script.js")
  11. head += f'<script type="text/javascript" src="{webpath(script_js)}"></script>\n'
  12. for script in scripts.list_scripts("javascript", ".js"):
  13. head += f'<script type="text/javascript" src="{webpath(script.path)}"></script>\n'
  14. for script in scripts.list_scripts("javascript", ".mjs"):
  15. head += f'<script type="module" src="{webpath(script.path)}"></script>\n'
  16. if shared.cmd_opts.theme:
  17. head += f'<script type="text/javascript">set_theme(\"{shared.cmd_opts.theme}\");</script>\n'
  18. return head
  19. def css_html():
  20. head = ""
  21. def stylesheet(fn):
  22. return f'<link rel="stylesheet" property="stylesheet" href="{webpath(fn)}">'
  23. for cssfile in scripts.list_files_with_name("style.css"):
  24. head += stylesheet(cssfile)
  25. user_css = os.path.join(data_path, "user.css")
  26. if os.path.exists(user_css):
  27. head += stylesheet(user_css)
  28. from modules.shared_gradio_themes import resolve_var
  29. light = resolve_var('background_fill_primary')
  30. dark = resolve_var('background_fill_primary_dark')
  31. head += f'<style>html {{ background-color: {light}; }} @media (prefers-color-scheme: dark) {{ html {{background-color: {dark}; }} }}</style>'
  32. return head
  33. def reload_javascript():
  34. js = javascript_html()
  35. css = css_html()
  36. def template_response(*args, **kwargs):
  37. res = shared.GradioTemplateResponseOriginal(*args, **kwargs)
  38. res.body = res.body.replace(b'</head>', f'{js}<meta name="referrer" content="no-referrer"/></head>'.encode("utf8"))
  39. res.body = res.body.replace(b'</body>', f'{css}</body>'.encode("utf8"))
  40. res.init_headers()
  41. return res
  42. gr.routes.templates.TemplateResponse = template_response
  43. if not hasattr(shared, 'GradioTemplateResponseOriginal'):
  44. shared.GradioTemplateResponseOriginal = gr.routes.templates.TemplateResponse