Spaces:
Sleeping
Sleeping
File size: 1,039 Bytes
c45703e |
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 |
import gradio
class JavaScriptLoader:
def __init__(self, target):
#Copy the template response
self.original_template = gradio.routes.templates.TemplateResponse
#Prep the js files
self.load_js(target)
#reassign the template response to your method, so gradio calls your method instead
gradio.routes.templates.TemplateResponse = self.template_response
def load_js(self, target):
with open(target, 'r', encoding="utf-8") as file:
self.loaded_script = f"<script>\n{file.read()}\n</script>"
def template_response(self, *args, **kwargs):
"""Once gradio calls your method, you call the original, you modify it to include
your scripts and you return the modified version
"""
response = self.original_template(*args, **kwargs)
response.body = response.body.replace(
'</head>'.encode('utf-8'), (self.loaded_script + "\n</head>").encode("utf-8")
)
response.init_headers()
return response |