gstaff commited on
Commit
1ba22b4
β€’
1 Parent(s): 9d67c47

Add function type annotations.

Browse files
Files changed (2) hide show
  1. app.py +25 -25
  2. templates.py +22 -15
app.py CHANGED
@@ -6,9 +6,9 @@ import warnings
6
  import gradio as gr
7
  import requests
8
  import torch
9
- from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
10
 
11
- from templates import starting_app_code, update_iframe_js, copy_snippet_js, download_code_js, load_js
12
 
13
  # Filter the UserWarning raised by the audio component.
14
  warnings.filterwarnings("ignore", message='Trying to convert audio automatically from int32 to 16-bit int format')
@@ -30,7 +30,7 @@ API_URL = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-b
30
  headers = {"Authorization": f"Bearer {HF_TOKEN}"}
31
 
32
 
33
- def init_speech_to_text_model():
34
  device = "cuda:0" if torch.cuda.is_available() else "cpu"
35
  torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
36
 
@@ -56,19 +56,16 @@ whisper_pipe = init_speech_to_text_model()
56
  code_pattern = re.compile(r'```python\n(.*?)```', re.DOTALL)
57
 
58
 
59
- def query(payload):
60
  response = requests.post(API_URL, headers=headers, json=payload)
61
  return response.json()
62
 
63
 
64
- def generate_text(code, prompt):
65
  logger.info(f"Calling API with prompt:\n{prompt}")
66
  prompt = f"```python\n{code}```\nGiven the code above return only updated code for the following request:\n{prompt}\n<|assistant|>"
67
  params = {"max_new_tokens": 512}
68
- output = query({
69
- "inputs": prompt,
70
- "parameters": params,
71
- })
72
  if 'error' in output:
73
  logger.warning(f'Language model call failed: {output["error"]}')
74
  raise gr.Warning(f'Language model call failed: {output["error"]}')
@@ -82,7 +79,7 @@ def generate_text(code, prompt):
82
  return assistant_reply, new_code, None
83
 
84
 
85
- def transcribe(audio):
86
  result = whisper_pipe(audio)
87
  return result["text"], None
88
 
@@ -100,21 +97,22 @@ with gr.Blocks() as demo:
100
  with gr.Row():
101
  with gr.Column():
102
  gr.Markdown("## 1. Run your app in the browser!")
103
- html = gr.HTML(value='<div id="stliteDemoDiv"></div>')
104
  gr.Markdown("## 2. Customize using voice requests!")
105
  with gr.Row():
106
  with gr.Column():
107
  with gr.Group():
108
  in_audio = gr.Audio(label="Record a voice request", source='microphone', type='filepath')
109
  in_prompt = gr.Textbox(label="Or type a text request and press Enter",
110
- placeholder="Need an idea? Try one of these:\n- Add a button\n- Change the greeting from hello to hey there")
111
  out_text = gr.TextArea(label="Chat Assistant Response")
112
  clear_btn = gr.ClearButton([in_prompt, in_audio, out_text])
113
  with gr.Column():
114
  code_area = gr.Code(label="App Code - You can also edit directly and then click Update App",
115
- language='python', value=starting_app_code('stlite'))
116
  update_btn = gr.Button("Update App", variant="primary")
117
- code_update_params = {'fn': None, 'inputs': code_area, 'outputs': None, '_js': update_iframe_js('stlite')}
 
118
  gen_text_params = {'fn': generate_text, 'inputs': [code_area, in_prompt],
119
  'outputs': [out_text, code_area]}
120
  transcribe_params = {'fn': transcribe, 'inputs': [in_audio], 'outputs': [in_prompt, in_audio]}
@@ -125,9 +123,9 @@ with gr.Blocks() as demo:
125
  with gr.Column():
126
  gr.Markdown("## 3. Export your app to share!")
127
  copy_snippet_btn = gr.Button("Copy app snippet to paste in another page")
128
- copy_snippet_btn.click(copy_notify, code_area, None, _js=copy_snippet_js('stlite'))
129
  download_btn = gr.Button("Download app as a standalone file")
130
- download_btn.click(None, code_area, None, _js=download_code_js('stlite'))
131
  with gr.Row():
132
  with gr.Column():
133
  gr.Markdown("## Current limitations")
@@ -138,7 +136,7 @@ with gr.Blocks() as demo:
138
  with gr.Row():
139
  with gr.Column():
140
  gr.Markdown("## 1. Run your app in the browser!")
141
- html = gr.HTML(value='<div id="gradioDemoDiv"></div>')
142
  gr.Markdown("## 2. Customize using voice requests!")
143
  with gr.Row():
144
  with gr.Column():
@@ -150,11 +148,12 @@ with gr.Blocks() as demo:
150
  clear = gr.ClearButton([in_prompt, in_audio, out_text])
151
  with gr.Column():
152
  code_area = gr.Code(label="App Code - You can also edit directly and then click Update App",
153
- language='python', value=starting_app_code('gradio-lite'))
154
  update_btn = gr.Button("Update App", variant="primary")
155
  code_update_params = {'fn': None, 'inputs': code_area, 'outputs': None,
156
- '_js': update_iframe_js('gradio-lite')}
157
- gen_text_params = {'fn': generate_text, 'inputs': [code_area, in_prompt], 'outputs': [out_text, code_area]}
 
158
  transcribe_params = {'fn': transcribe, 'inputs': [in_audio], 'outputs': [in_prompt, in_audio]}
159
  update_btn.click(**code_update_params)
160
  in_prompt.submit(**gen_text_params).then(**code_update_params)
@@ -163,9 +162,9 @@ with gr.Blocks() as demo:
163
  with gr.Column():
164
  gr.Markdown("## 3. Export your app to share!")
165
  copy_snippet_btn = gr.Button("Copy app snippet to paste in another page")
166
- copy_snippet_btn.click(copy_notify, code_area, None, _js=copy_snippet_js('gradio-lite'))
167
  download_btn = gr.Button("Download app as a standalone file")
168
- download_btn.click(None, code_area, None, _js=download_code_js('gradio-lite'))
169
  with gr.Row():
170
  with gr.Column():
171
  gr.Markdown("## Current limitations")
@@ -173,9 +172,10 @@ with gr.Blocks() as demo:
173
  gr.Markdown(
174
  "- Only gradio-lite apps using the python standard libraries and gradio are supported\n- The chat hasn't been tuned on gradio library data; it may make mistakes\n- The app needs to fully reload each time it is changed")
175
 
176
- stlite_tab.select(lambda: "stlite", None, selectedTab).then(None, None, None, _js=load_js('stlite'))
177
- gradio_lite_tab.select(lambda: "gradio-lite", None, selectedTab).then(None, None, None, _js=load_js('gradio-lite'))
178
- demo.load(None, None, None, _js=load_js('stlite'))
 
179
  demo.css = "footer {visibility: hidden}"
180
 
181
  if __name__ == "__main__":
 
6
  import gradio as gr
7
  import requests
8
  import torch
9
+ from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline, Pipeline
10
 
11
+ from templates import starting_app_code, update_iframe_js, copy_snippet_js, download_code_js, load_js, DemoType
12
 
13
  # Filter the UserWarning raised by the audio component.
14
  warnings.filterwarnings("ignore", message='Trying to convert audio automatically from int32 to 16-bit int format')
 
30
  headers = {"Authorization": f"Bearer {HF_TOKEN}"}
31
 
32
 
33
+ def init_speech_to_text_model() -> Pipeline:
34
  device = "cuda:0" if torch.cuda.is_available() else "cpu"
35
  torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
36
 
 
56
  code_pattern = re.compile(r'```python\n(.*?)```', re.DOTALL)
57
 
58
 
59
+ def query(payload: dict):
60
  response = requests.post(API_URL, headers=headers, json=payload)
61
  return response.json()
62
 
63
 
64
+ def generate_text(code: str, prompt: str) -> (str, str, str):
65
  logger.info(f"Calling API with prompt:\n{prompt}")
66
  prompt = f"```python\n{code}```\nGiven the code above return only updated code for the following request:\n{prompt}\n<|assistant|>"
67
  params = {"max_new_tokens": 512}
68
+ output = query({"inputs": prompt, "parameters": params})
 
 
 
69
  if 'error' in output:
70
  logger.warning(f'Language model call failed: {output["error"]}')
71
  raise gr.Warning(f'Language model call failed: {output["error"]}')
 
79
  return assistant_reply, new_code, None
80
 
81
 
82
+ def transcribe(audio: str) -> (str, str):
83
  result = whisper_pipe(audio)
84
  return result["text"], None
85
 
 
97
  with gr.Row():
98
  with gr.Column():
99
  gr.Markdown("## 1. Run your app in the browser!")
100
+ gr.HTML(value='<div id="stliteDemoDiv"></div>')
101
  gr.Markdown("## 2. Customize using voice requests!")
102
  with gr.Row():
103
  with gr.Column():
104
  with gr.Group():
105
  in_audio = gr.Audio(label="Record a voice request", source='microphone', type='filepath')
106
  in_prompt = gr.Textbox(label="Or type a text request and press Enter",
107
+ placeholder="Need an idea? Try one of these:\n- Add a button to reverse the name\n- Change the greeting to Spanish\n- Make the button primary")
108
  out_text = gr.TextArea(label="Chat Assistant Response")
109
  clear_btn = gr.ClearButton([in_prompt, in_audio, out_text])
110
  with gr.Column():
111
  code_area = gr.Code(label="App Code - You can also edit directly and then click Update App",
112
+ language='python', value=starting_app_code(DemoType.STREAMLIT))
113
  update_btn = gr.Button("Update App", variant="primary")
114
+ code_update_params = {'fn': None, 'inputs': code_area, 'outputs': None,
115
+ '_js': update_iframe_js(DemoType.STREAMLIT)}
116
  gen_text_params = {'fn': generate_text, 'inputs': [code_area, in_prompt],
117
  'outputs': [out_text, code_area]}
118
  transcribe_params = {'fn': transcribe, 'inputs': [in_audio], 'outputs': [in_prompt, in_audio]}
 
123
  with gr.Column():
124
  gr.Markdown("## 3. Export your app to share!")
125
  copy_snippet_btn = gr.Button("Copy app snippet to paste in another page")
126
+ copy_snippet_btn.click(copy_notify, code_area, None, _js=copy_snippet_js(DemoType.STREAMLIT))
127
  download_btn = gr.Button("Download app as a standalone file")
128
+ download_btn.click(None, code_area, None, _js=download_code_js(DemoType.STREAMLIT))
129
  with gr.Row():
130
  with gr.Column():
131
  gr.Markdown("## Current limitations")
 
136
  with gr.Row():
137
  with gr.Column():
138
  gr.Markdown("## 1. Run your app in the browser!")
139
+ gr.HTML(value='<div id="gradioDemoDiv"></div>')
140
  gr.Markdown("## 2. Customize using voice requests!")
141
  with gr.Row():
142
  with gr.Column():
 
148
  clear = gr.ClearButton([in_prompt, in_audio, out_text])
149
  with gr.Column():
150
  code_area = gr.Code(label="App Code - You can also edit directly and then click Update App",
151
+ language='python', value=starting_app_code(DemoType.GRADIO))
152
  update_btn = gr.Button("Update App", variant="primary")
153
  code_update_params = {'fn': None, 'inputs': code_area, 'outputs': None,
154
+ '_js': update_iframe_js(DemoType.GRADIO)}
155
+ gen_text_params = {'fn': generate_text, 'inputs': [code_area, in_prompt],
156
+ 'outputs': [out_text, code_area]}
157
  transcribe_params = {'fn': transcribe, 'inputs': [in_audio], 'outputs': [in_prompt, in_audio]}
158
  update_btn.click(**code_update_params)
159
  in_prompt.submit(**gen_text_params).then(**code_update_params)
 
162
  with gr.Column():
163
  gr.Markdown("## 3. Export your app to share!")
164
  copy_snippet_btn = gr.Button("Copy app snippet to paste in another page")
165
+ copy_snippet_btn.click(copy_notify, code_area, None, _js=copy_snippet_js(DemoType.GRADIO))
166
  download_btn = gr.Button("Download app as a standalone file")
167
+ download_btn.click(None, code_area, None, _js=download_code_js(DemoType.GRADIO))
168
  with gr.Row():
169
  with gr.Column():
170
  gr.Markdown("## Current limitations")
 
172
  gr.Markdown(
173
  "- Only gradio-lite apps using the python standard libraries and gradio are supported\n- The chat hasn't been tuned on gradio library data; it may make mistakes\n- The app needs to fully reload each time it is changed")
174
 
175
+ stlite_tab.select(lambda: "stlite", None, selectedTab).then(None, None, None, _js=load_js(DemoType.STREAMLIT))
176
+ gradio_lite_tab.select(lambda: "gradio-lite", None, selectedTab).then(None, None, None,
177
+ _js=load_js(DemoType.GRADIO))
178
+ demo.load(None, None, None, _js=load_js(DemoType.STREAMLIT))
179
  demo.css = "footer {visibility: hidden}"
180
 
181
  if __name__ == "__main__":
templates.py CHANGED
@@ -1,20 +1,27 @@
 
1
  from pathlib import Path
2
 
 
 
 
 
 
 
3
  gradio_lite_html_template = Path('templates/gradio-lite/gradio-lite-template.html').read_text()
4
  stlite_html_template = Path('templates/stlite/stlite-template.html').read_text()
5
  stlite_snippet_template = Path('templates/stlite/stlite-snippet-template.html').read_text()
6
 
7
 
8
- def starting_app_code(demo_type):
9
- if demo_type == 'gradio-lite':
10
  return Path('templates/gradio-lite/gradio_lite_starting_code.py').read_text()
11
- elif demo_type == 'stlite':
12
  return Path('templates/stlite/stlite_starting_code.py').read_text().replace('`', r'\`')
13
  raise NotImplementedError(f'{demo_type} is not a supported demo type')
14
 
15
 
16
- def load_js(demo_type):
17
- if demo_type == 'gradio-lite':
18
  return f"""() => {{
19
  if (window.gradioLiteLoaded) {{
20
  return
@@ -32,7 +39,7 @@ def load_js(demo_type):
32
  frame.contentWindow.document.close();
33
  window.gradioLiteLoaded = true;
34
  }}"""
35
- elif demo_type == 'stlite':
36
  return f"""() => {{
37
  if (window.stliteLoaded) {{
38
  return
@@ -54,8 +61,8 @@ def load_js(demo_type):
54
  raise NotImplementedError(f'{demo_type} is not a supported demo type')
55
 
56
 
57
- def update_iframe_js(demo_type):
58
- if demo_type == 'gradio-lite':
59
  # TODO: Works but is inefficient because the iframe has to be reloaded each time
60
  return f"""(code) => {{
61
  const pattern = /# APP CODE START(.*?)# APP CODE END/gs;
@@ -77,7 +84,7 @@ def update_iframe_js(demo_type):
77
  frame.contentWindow.document.write(completedTemplate);
78
  frame.contentWindow.document.close();
79
  }}"""
80
- elif demo_type == 'stlite':
81
  return f"""async (code) => {{
82
  async function update() {{
83
  const appController = document.getElementById('demo-iframe').contentWindow.window.appController;
@@ -90,8 +97,8 @@ def update_iframe_js(demo_type):
90
  raise NotImplementedError(f'{demo_type} is not a supported demo type')
91
 
92
 
93
- def copy_snippet_js(demo_type):
94
- if demo_type == 'gradio-lite':
95
  return f"""async (code) => {{
96
  const pattern = /# APP CODE START(.*?)# APP CODE END/gs;
97
  const template = `<div id="KiteWindApp">\n<script type="module" crossorigin src="https://cdn.jsdelivr.net/npm/@gradio/lite/dist/lite.js"></script>
@@ -103,7 +110,7 @@ def copy_snippet_js(demo_type):
103
  const snippet = completedTemplate;
104
  await navigator.clipboard.writeText(snippet);
105
  }}"""
106
- elif demo_type == 'stlite':
107
  return f"""async (code) => {{
108
  const escapedCode = code.replace('`', String.fromCharCode(92) + '`');
109
  const template = `{stlite_html_template}`;
@@ -116,8 +123,8 @@ def copy_snippet_js(demo_type):
116
  raise NotImplementedError(f'{demo_type} is not a supported demo type')
117
 
118
 
119
- def download_code_js(demo_type):
120
- if demo_type == 'gradio-lite':
121
  return f"""(code) => {{
122
  const pattern = /# APP CODE START(.*?)# APP CODE END/gs;
123
  const template = `{gradio_lite_html_template}`;
@@ -141,7 +148,7 @@ def download_code_js(demo_type):
141
  // Clean up by revoking the URL
142
  URL.revokeObjectURL(url);
143
  }}"""
144
- elif demo_type == 'stlite':
145
  return f"""(code) => {{
146
  const escapedCode = code.replace('`', String.fromCharCode(92) + '`');
147
  // Step 1: Generate the HTML content
 
1
+ from enum import Enum
2
  from pathlib import Path
3
 
4
+
5
+ class DemoType(Enum):
6
+ GRADIO = 1
7
+ STREAMLIT = 2
8
+
9
+
10
  gradio_lite_html_template = Path('templates/gradio-lite/gradio-lite-template.html').read_text()
11
  stlite_html_template = Path('templates/stlite/stlite-template.html').read_text()
12
  stlite_snippet_template = Path('templates/stlite/stlite-snippet-template.html').read_text()
13
 
14
 
15
+ def starting_app_code(demo_type: DemoType) -> str:
16
+ if demo_type == DemoType.GRADIO:
17
  return Path('templates/gradio-lite/gradio_lite_starting_code.py').read_text()
18
+ elif demo_type == DemoType.STREAMLIT:
19
  return Path('templates/stlite/stlite_starting_code.py').read_text().replace('`', r'\`')
20
  raise NotImplementedError(f'{demo_type} is not a supported demo type')
21
 
22
 
23
+ def load_js(demo_type: DemoType) -> str:
24
+ if demo_type == DemoType.GRADIO:
25
  return f"""() => {{
26
  if (window.gradioLiteLoaded) {{
27
  return
 
39
  frame.contentWindow.document.close();
40
  window.gradioLiteLoaded = true;
41
  }}"""
42
+ elif demo_type == DemoType.STREAMLIT:
43
  return f"""() => {{
44
  if (window.stliteLoaded) {{
45
  return
 
61
  raise NotImplementedError(f'{demo_type} is not a supported demo type')
62
 
63
 
64
+ def update_iframe_js(demo_type: DemoType) -> str:
65
+ if demo_type == DemoType.GRADIO:
66
  # TODO: Works but is inefficient because the iframe has to be reloaded each time
67
  return f"""(code) => {{
68
  const pattern = /# APP CODE START(.*?)# APP CODE END/gs;
 
84
  frame.contentWindow.document.write(completedTemplate);
85
  frame.contentWindow.document.close();
86
  }}"""
87
+ elif demo_type == DemoType.STREAMLIT:
88
  return f"""async (code) => {{
89
  async function update() {{
90
  const appController = document.getElementById('demo-iframe').contentWindow.window.appController;
 
97
  raise NotImplementedError(f'{demo_type} is not a supported demo type')
98
 
99
 
100
+ def copy_snippet_js(demo_type: DemoType) -> str:
101
+ if demo_type == DemoType.GRADIO:
102
  return f"""async (code) => {{
103
  const pattern = /# APP CODE START(.*?)# APP CODE END/gs;
104
  const template = `<div id="KiteWindApp">\n<script type="module" crossorigin src="https://cdn.jsdelivr.net/npm/@gradio/lite/dist/lite.js"></script>
 
110
  const snippet = completedTemplate;
111
  await navigator.clipboard.writeText(snippet);
112
  }}"""
113
+ elif demo_type == DemoType.STREAMLIT:
114
  return f"""async (code) => {{
115
  const escapedCode = code.replace('`', String.fromCharCode(92) + '`');
116
  const template = `{stlite_html_template}`;
 
123
  raise NotImplementedError(f'{demo_type} is not a supported demo type')
124
 
125
 
126
+ def download_code_js(demo_type: DemoType) -> str:
127
+ if demo_type == demo_type.GRADIO:
128
  return f"""(code) => {{
129
  const pattern = /# APP CODE START(.*?)# APP CODE END/gs;
130
  const template = `{gradio_lite_html_template}`;
 
148
  // Clean up by revoking the URL
149
  URL.revokeObjectURL(url);
150
  }}"""
151
+ elif demo_type == demo_type.STREAMLIT:
152
  return f"""(code) => {{
153
  const escapedCode = code.replace('`', String.fromCharCode(92) + '`');
154
  // Step 1: Generate the HTML content