ui_gradio_extensions.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. return head
  29. def reload_javascript():
  30. js = javascript_html()
  31. css = css_html()
  32. def template_response(*args, **kwargs):
  33. res = shared.GradioTemplateResponseOriginal(*args, **kwargs)
  34. res.body = res.body.replace(b'</head>', f'{js}</head>'.encode("utf8"))
  35. res.body = res.body.replace(b'</body>', f'{css}</body>'.encode("utf8"))
  36. res.init_headers()
  37. return res
  38. gr.routes.templates.TemplateResponse = template_response
  39. if not hasattr(shared, 'GradioTemplateResponseOriginal'):
  40. shared.GradioTemplateResponseOriginal = gr.routes.templates.TemplateResponse