Spaces:
Running
Running
Updated UI and behavior.
Browse files- app/config.py +1 -0
- app/gradio_meta_prompt.py +81 -48
- app/gradio_meta_prompt_utils.py +4 -3
- guidelines/gradio.md +113 -235
app/config.py
CHANGED
@@ -19,6 +19,7 @@ class PromptGroup(BaseModel):
|
|
19 |
|
20 |
class MetaPromptConfig(BaseConfig):
|
21 |
llms: Optional[dict[str, LLMConfig]]
|
|
|
22 |
aggressive_exploration: Optional[bool] = False
|
23 |
examples_path: Optional[str]
|
24 |
server_name: Optional[str] = None
|
|
|
19 |
|
20 |
class MetaPromptConfig(BaseConfig):
|
21 |
llms: Optional[dict[str, LLMConfig]]
|
22 |
+
default_llm_temperature: Optional[float] = 0.1
|
23 |
aggressive_exploration: Optional[bool] = False
|
24 |
examples_path: Optional[str]
|
25 |
server_name: Optional[str] = None
|
app/gradio_meta_prompt.py
CHANGED
@@ -43,7 +43,16 @@ with gr.Blocks(title='Meta Prompt') as demo:
|
|
43 |
interactive=False,
|
44 |
wrap=True
|
45 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
|
|
|
|
|
47 |
selected_example_input = gr.Textbox(
|
48 |
label="Selected Example Input",
|
49 |
lines=2,
|
@@ -57,13 +66,7 @@ with gr.Blocks(title='Meta Prompt') as demo:
|
|
57 |
value="",
|
58 |
)
|
59 |
|
60 |
-
with gr.Column(scale=1):
|
61 |
-
with gr.Accordion("Import/Export JSON", open=False):
|
62 |
-
json_file_object = gr.File(
|
63 |
-
label="Import/Export JSON", file_types=[".json"], type="filepath"
|
64 |
-
)
|
65 |
-
export_button = gr.Button("Export to JSON")
|
66 |
-
|
67 |
selected_group_mode = gr.State(None) # None, "update", "append"
|
68 |
selected_group_index = gr.State(None) # None, int
|
69 |
selected_group_input = gr.State("")
|
@@ -98,18 +101,22 @@ with gr.Blocks(title='Meta Prompt') as demo:
|
|
98 |
selected_row_index = gr.Number(
|
99 |
label="Selected Row Index", value=index, precision=0, interactive=False
|
100 |
)
|
101 |
-
delete_row_button = gr.Button(
|
102 |
-
"Delete Selected Row", variant="secondary"
|
103 |
-
)
|
104 |
-
with gr.Row():
|
105 |
update_row_button = gr.Button(
|
106 |
"Update Selected Row", variant="secondary"
|
107 |
)
|
108 |
-
|
|
|
|
|
|
|
109 |
|
110 |
-
|
111 |
-
fn=
|
112 |
-
inputs=[
|
|
|
|
|
|
|
|
|
|
|
113 |
outputs=[
|
114 |
input_dataframe,
|
115 |
selected_group_mode,
|
@@ -119,14 +126,9 @@ with gr.Blocks(title='Meta Prompt') as demo:
|
|
119 |
],
|
120 |
)
|
121 |
|
122 |
-
|
123 |
-
fn=
|
124 |
-
inputs=[
|
125 |
-
selected_example_input,
|
126 |
-
selected_example_output,
|
127 |
-
selected_row_index,
|
128 |
-
input_dataframe,
|
129 |
-
],
|
130 |
outputs=[
|
131 |
input_dataframe,
|
132 |
selected_group_mode,
|
@@ -135,12 +137,13 @@ with gr.Blocks(title='Meta Prompt') as demo:
|
|
135 |
selected_group_output,
|
136 |
],
|
137 |
)
|
|
|
138 |
elif mode == "append":
|
139 |
with gr.Row():
|
140 |
append_example_button = gr.Button(
|
141 |
"Append to Input Examples", variant="secondary"
|
142 |
)
|
143 |
-
close_button = gr.Button("Close", variant="secondary")
|
144 |
|
145 |
append_example_button.click(
|
146 |
fn=append_example_to_input_dataframe,
|
@@ -158,18 +161,18 @@ with gr.Blocks(title='Meta Prompt') as demo:
|
|
158 |
],
|
159 |
)
|
160 |
|
161 |
-
close_button.click(
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
)
|
166 |
|
167 |
with gr.Tabs() as tabs:
|
168 |
|
169 |
with gr.Tab("Scope"):
|
170 |
|
171 |
with gr.Row():
|
172 |
-
|
173 |
scope_clear_button = gr.ClearButton(
|
174 |
[
|
175 |
input_dataframe
|
@@ -303,16 +306,23 @@ with gr.Blocks(title='Meta Prompt') as demo:
|
|
303 |
value="Generate",
|
304 |
variant="secondary"
|
305 |
)
|
|
|
|
|
|
|
|
|
306 |
|
307 |
with gr.Group():
|
308 |
acceptance_criteria_input = gr.Textbox(
|
309 |
label="Acceptance Criteria (Compared with Expected Output [EO])",
|
310 |
show_copy_button=True
|
311 |
)
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
|
|
|
|
|
|
316 |
|
317 |
recursion_limit_input = gr.Number(
|
318 |
label="Recursion Limit",
|
@@ -443,10 +453,10 @@ with gr.Blocks(title='Meta Prompt') as demo:
|
|
443 |
with gr.Row():
|
444 |
evaluate_system_message_button = gr.Button(
|
445 |
value="Evaluate", variant="secondary")
|
446 |
-
copy_to_initial_system_message_button = gr.Button(
|
447 |
-
value="Copy to Initial System Message", variant="secondary")
|
448 |
output_output = gr.Textbox(
|
449 |
label="Output", show_copy_button=True)
|
|
|
|
|
450 |
analysis_output = gr.Textbox(
|
451 |
label="Analysis", show_copy_button=True)
|
452 |
flag_button = gr.Button(
|
@@ -463,10 +473,10 @@ with gr.Blocks(title='Meta Prompt') as demo:
|
|
463 |
examples = gr.Examples(config.examples_path, inputs=[
|
464 |
selected_example_input,
|
465 |
selected_example_output,
|
466 |
-
acceptance_criteria_input,
|
467 |
-
initial_system_message_input,
|
468 |
-
recursion_limit_input,
|
469 |
-
simple_model_name_input
|
470 |
])
|
471 |
|
472 |
prompt_model_tab_state = gr.State(value='Simple')
|
@@ -498,9 +508,22 @@ with gr.Blocks(title='Meta Prompt') as demo:
|
|
498 |
|
499 |
config_state = gr.State(value=config)
|
500 |
|
|
|
501 |
prompt_inputs_ready_state = gr.State(value=False)
|
502 |
|
503 |
# set up event handlers for the scope tab
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
504 |
|
505 |
json_file_object.change(
|
506 |
fn=import_json_data,
|
@@ -514,7 +537,7 @@ with gr.Blocks(title='Meta Prompt') as demo:
|
|
514 |
outputs=[json_file_object],
|
515 |
)
|
516 |
|
517 |
-
|
518 |
fn=process_json_data,
|
519 |
inputs=[
|
520 |
config_state,
|
@@ -662,7 +685,7 @@ with gr.Blocks(title='Meta Prompt') as demo:
|
|
662 |
fn=apply_suggestions,
|
663 |
inputs=[config_state, description_output, suggestions_output,
|
664 |
input_dataframe, scope_model_name, temperature],
|
665 |
-
outputs=[description_output],
|
666 |
)
|
667 |
|
668 |
# set up event handlers for the prompt tab
|
@@ -771,7 +794,7 @@ with gr.Blocks(title='Meta Prompt') as demo:
|
|
771 |
model_name_states["acceptance_criteria"],
|
772 |
model_temperature_states["acceptance_criteria"],
|
773 |
prompt_template_group],
|
774 |
-
outputs=[
|
775 |
)
|
776 |
generate_initial_system_message_button.click(
|
777 |
generate_initial_system_message,
|
@@ -804,16 +827,26 @@ with gr.Blocks(title='Meta Prompt') as demo:
|
|
804 |
],
|
805 |
outputs=[output_output]
|
806 |
)
|
807 |
-
|
|
|
|
|
|
|
|
|
|
|
808 |
lambda x: x,
|
809 |
inputs=[system_message_output],
|
810 |
outputs=[initial_system_message_input]
|
811 |
)
|
|
|
|
|
|
|
|
|
|
|
812 |
|
813 |
prompt_clear_button.add([selected_example_input, selected_example_output,
|
814 |
acceptance_criteria_input, initial_system_message_input,
|
815 |
system_message_output, output_output,
|
816 |
-
analysis_output, logs_chatbot])
|
817 |
|
818 |
prompt_submit_button.click(
|
819 |
process_message_with_models,
|
@@ -846,7 +879,7 @@ with gr.Blocks(title='Meta Prompt') as demo:
|
|
846 |
system_message_output,
|
847 |
output_output,
|
848 |
analysis_output,
|
849 |
-
|
850 |
logs_chatbot
|
851 |
]
|
852 |
)
|
@@ -854,8 +887,8 @@ with gr.Blocks(title='Meta Prompt') as demo:
|
|
854 |
flagging_inputs = [
|
855 |
selected_example_input,
|
856 |
selected_example_output,
|
857 |
-
acceptance_criteria_input,
|
858 |
-
initial_system_message_input
|
859 |
]
|
860 |
|
861 |
# Configure flagging
|
|
|
43 |
interactive=False,
|
44 |
wrap=True
|
45 |
)
|
46 |
+
with gr.Column(scale=1, min_width=100):
|
47 |
+
with gr.Group():
|
48 |
+
json_file_object = gr.File(
|
49 |
+
label="Import/Export JSON", file_types=[".json"], type="filepath",
|
50 |
+
min_width=80
|
51 |
+
)
|
52 |
+
export_button = gr.Button("Export to JSON")
|
53 |
|
54 |
+
with gr.Row():
|
55 |
+
with gr.Column(scale=3):
|
56 |
selected_example_input = gr.Textbox(
|
57 |
label="Selected Example Input",
|
58 |
lines=2,
|
|
|
66 |
value="",
|
67 |
)
|
68 |
|
69 |
+
with gr.Column(scale=1, min_width=100):
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
selected_group_mode = gr.State(None) # None, "update", "append"
|
71 |
selected_group_index = gr.State(None) # None, int
|
72 |
selected_group_input = gr.State("")
|
|
|
101 |
selected_row_index = gr.Number(
|
102 |
label="Selected Row Index", value=index, precision=0, interactive=False
|
103 |
)
|
|
|
|
|
|
|
|
|
104 |
update_row_button = gr.Button(
|
105 |
"Update Selected Row", variant="secondary"
|
106 |
)
|
107 |
+
delete_row_button = gr.Button(
|
108 |
+
"Delete Selected Row", variant="secondary"
|
109 |
+
)
|
110 |
+
# close_button = gr.Button("Close", variant="secondary")
|
111 |
|
112 |
+
update_row_button.click(
|
113 |
+
fn=update_selected_dataframe_row,
|
114 |
+
inputs=[
|
115 |
+
selected_example_input,
|
116 |
+
selected_example_output,
|
117 |
+
selected_row_index,
|
118 |
+
input_dataframe,
|
119 |
+
],
|
120 |
outputs=[
|
121 |
input_dataframe,
|
122 |
selected_group_mode,
|
|
|
126 |
],
|
127 |
)
|
128 |
|
129 |
+
delete_row_button.click(
|
130 |
+
fn=delete_selected_dataframe_row,
|
131 |
+
inputs=[selected_row_index, input_dataframe],
|
|
|
|
|
|
|
|
|
|
|
132 |
outputs=[
|
133 |
input_dataframe,
|
134 |
selected_group_mode,
|
|
|
137 |
selected_group_output,
|
138 |
],
|
139 |
)
|
140 |
+
|
141 |
elif mode == "append":
|
142 |
with gr.Row():
|
143 |
append_example_button = gr.Button(
|
144 |
"Append to Input Examples", variant="secondary"
|
145 |
)
|
146 |
+
# close_button = gr.Button("Close", variant="secondary")
|
147 |
|
148 |
append_example_button.click(
|
149 |
fn=append_example_to_input_dataframe,
|
|
|
161 |
],
|
162 |
)
|
163 |
|
164 |
+
# close_button.click(
|
165 |
+
# fn=lambda: None,
|
166 |
+
# inputs=[],
|
167 |
+
# outputs=[selected_group_mode],
|
168 |
+
# )
|
169 |
|
170 |
with gr.Tabs() as tabs:
|
171 |
|
172 |
with gr.Tab("Scope"):
|
173 |
|
174 |
with gr.Row():
|
175 |
+
scope_submit_button = gr.Button("Generate", variant="primary", interactive=False)
|
176 |
scope_clear_button = gr.ClearButton(
|
177 |
[
|
178 |
input_dataframe
|
|
|
306 |
value="Generate",
|
307 |
variant="secondary"
|
308 |
)
|
309 |
+
pull_task_description_output_button = gr.Button(
|
310 |
+
value="→ Pull Output", variant="secondary")
|
311 |
+
pull_system_message_output_button = gr.Button(
|
312 |
+
value="Pull Output ←", variant="secondary")
|
313 |
|
314 |
with gr.Group():
|
315 |
acceptance_criteria_input = gr.Textbox(
|
316 |
label="Acceptance Criteria (Compared with Expected Output [EO])",
|
317 |
show_copy_button=True
|
318 |
)
|
319 |
+
with gr.Row():
|
320 |
+
generate_acceptance_criteria_button = gr.Button(
|
321 |
+
value="Generate",
|
322 |
+
variant="secondary"
|
323 |
+
)
|
324 |
+
pull_acceptance_criteria_output_button = gr.Button(
|
325 |
+
value="Pull Output ←", variant="secondary")
|
326 |
|
327 |
recursion_limit_input = gr.Number(
|
328 |
label="Recursion Limit",
|
|
|
453 |
with gr.Row():
|
454 |
evaluate_system_message_button = gr.Button(
|
455 |
value="Evaluate", variant="secondary")
|
|
|
|
|
456 |
output_output = gr.Textbox(
|
457 |
label="Output", show_copy_button=True)
|
458 |
+
acceptance_criteria_output = gr.Textbox(
|
459 |
+
label="Acceptance Criteria", show_copy_button=True)
|
460 |
analysis_output = gr.Textbox(
|
461 |
label="Analysis", show_copy_button=True)
|
462 |
flag_button = gr.Button(
|
|
|
473 |
examples = gr.Examples(config.examples_path, inputs=[
|
474 |
selected_example_input,
|
475 |
selected_example_output,
|
476 |
+
# acceptance_criteria_input,
|
477 |
+
# initial_system_message_input,
|
478 |
+
# recursion_limit_input,
|
479 |
+
# simple_model_name_input
|
480 |
])
|
481 |
|
482 |
prompt_model_tab_state = gr.State(value='Simple')
|
|
|
508 |
|
509 |
config_state = gr.State(value=config)
|
510 |
|
511 |
+
scope_inputs_ready_state = gr.State(value=False)
|
512 |
prompt_inputs_ready_state = gr.State(value=False)
|
513 |
|
514 |
# set up event handlers for the scope tab
|
515 |
+
input_dataframe.change(
|
516 |
+
fn=lambda x: len(x) > 0, # input_dataframe has at least 1 data row
|
517 |
+
inputs=[input_dataframe],
|
518 |
+
outputs=[scope_inputs_ready_state],
|
519 |
+
)
|
520 |
+
|
521 |
+
scope_inputs_ready_state.change(
|
522 |
+
fn=lambda x: [gr.update(interactive=x)] * 5,
|
523 |
+
inputs=[scope_inputs_ready_state],
|
524 |
+
outputs=[scope_submit_button, generate_description_button,
|
525 |
+
generate_examples_directly_button, analyze_input_button, generate_briefs_button],
|
526 |
+
)
|
527 |
|
528 |
json_file_object.change(
|
529 |
fn=import_json_data,
|
|
|
537 |
outputs=[json_file_object],
|
538 |
)
|
539 |
|
540 |
+
scope_submit_button.click(
|
541 |
fn=process_json_data,
|
542 |
inputs=[
|
543 |
config_state,
|
|
|
685 |
fn=apply_suggestions,
|
686 |
inputs=[config_state, description_output, suggestions_output,
|
687 |
input_dataframe, scope_model_name, temperature],
|
688 |
+
outputs=[description_output, suggestions_output],
|
689 |
)
|
690 |
|
691 |
# set up event handlers for the prompt tab
|
|
|
794 |
model_name_states["acceptance_criteria"],
|
795 |
model_temperature_states["acceptance_criteria"],
|
796 |
prompt_template_group],
|
797 |
+
outputs=[acceptance_criteria_output, logs_chatbot]
|
798 |
)
|
799 |
generate_initial_system_message_button.click(
|
800 |
generate_initial_system_message,
|
|
|
827 |
],
|
828 |
outputs=[output_output]
|
829 |
)
|
830 |
+
pull_task_description_output_button.click(
|
831 |
+
lambda x: x,
|
832 |
+
inputs=[description_output],
|
833 |
+
outputs=[initial_system_message_input]
|
834 |
+
)
|
835 |
+
pull_system_message_output_button.click(
|
836 |
lambda x: x,
|
837 |
inputs=[system_message_output],
|
838 |
outputs=[initial_system_message_input]
|
839 |
)
|
840 |
+
pull_acceptance_criteria_output_button.click(
|
841 |
+
lambda x: x,
|
842 |
+
inputs=[acceptance_criteria_output],
|
843 |
+
outputs=[acceptance_criteria_input]
|
844 |
+
)
|
845 |
|
846 |
prompt_clear_button.add([selected_example_input, selected_example_output,
|
847 |
acceptance_criteria_input, initial_system_message_input,
|
848 |
system_message_output, output_output,
|
849 |
+
acceptance_criteria_output, analysis_output, logs_chatbot])
|
850 |
|
851 |
prompt_submit_button.click(
|
852 |
process_message_with_models,
|
|
|
879 |
system_message_output,
|
880 |
output_output,
|
881 |
analysis_output,
|
882 |
+
acceptance_criteria_output,
|
883 |
logs_chatbot
|
884 |
]
|
885 |
)
|
|
|
887 |
flagging_inputs = [
|
888 |
selected_example_input,
|
889 |
selected_example_output,
|
890 |
+
# acceptance_criteria_input,
|
891 |
+
# initial_system_message_input
|
892 |
]
|
893 |
|
894 |
# Configure flagging
|
app/gradio_meta_prompt_utils.py
CHANGED
@@ -632,9 +632,10 @@ def generate_examples_using_briefs(
|
|
632 |
description, new_example_briefs, input_json, generating_batch_size
|
633 |
)
|
634 |
examples = [
|
635 |
-
[example["input"], example["output"]]
|
636 |
for example in result["examples"]
|
637 |
]
|
|
|
638 |
return examples
|
639 |
except Exception as e:
|
640 |
raise gr.Error(f"An error occurred: {str(e)}")
|
@@ -651,7 +652,7 @@ def generate_examples_from_description(
|
|
651 |
description, input_json, generating_batch_size
|
652 |
)
|
653 |
examples = [
|
654 |
-
[example["input"], example["output"]] for example in result["examples"]
|
655 |
]
|
656 |
return examples
|
657 |
except Exception as e:
|
@@ -761,6 +762,6 @@ def apply_suggestions(config, description, suggestions, examples, model_name, te
|
|
761 |
model = initialize_llm(config, model_name, {'temperature': temperature, 'max_retries': 3})
|
762 |
generator = TaskDescriptionGenerator(model)
|
763 |
result = generator.update_description(input_json, description, suggestions)
|
764 |
-
return result["description"]
|
765 |
except Exception as e:
|
766 |
raise gr.Error(f"An error occurred: {str(e)}")
|
|
|
632 |
description, new_example_briefs, input_json, generating_batch_size
|
633 |
)
|
634 |
examples = [
|
635 |
+
[str(example["input"]), str(example["output"])]
|
636 |
for example in result["examples"]
|
637 |
]
|
638 |
+
|
639 |
return examples
|
640 |
except Exception as e:
|
641 |
raise gr.Error(f"An error occurred: {str(e)}")
|
|
|
652 |
description, input_json, generating_batch_size
|
653 |
)
|
654 |
examples = [
|
655 |
+
[str(example["input"]), str(example["output"])] for example in result["examples"]
|
656 |
]
|
657 |
return examples
|
658 |
except Exception as e:
|
|
|
762 |
model = initialize_llm(config, model_name, {'temperature': temperature, 'max_retries': 3})
|
763 |
generator = TaskDescriptionGenerator(model)
|
764 |
result = generator.update_description(input_json, description, suggestions)
|
765 |
+
return result["description"], gr.update(choices=result["suggestions"], value=[])
|
766 |
except Exception as e:
|
767 |
raise gr.Error(f"An error occurred: {str(e)}")
|
guidelines/gradio.md
CHANGED
@@ -1,255 +1,133 @@
|
|
1 |
# Gradio Framework Guideline
|
2 |
|
3 |
-
##
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
-
|
8 |
-
-
|
9 |
-
-
|
10 |
-
-
|
11 |
-
-
|
12 |
-
|
13 |
-
|
14 |
-
To install Gradio, you can use pip, the Python package installer. Open a terminal and run the following command:
|
15 |
-
|
16 |
-
```
|
17 |
-
pip install gradio
|
18 |
-
```
|
19 |
-
|
20 |
-
To set up a new project using Gradio, create a new Python file and import the gradio library:
|
21 |
-
|
22 |
-
```python
|
23 |
-
import gradio as gr
|
24 |
-
```
|
25 |
-
|
26 |
-
## 3. Core Concepts
|
27 |
-
Gradio revolves around the concept of creating "interfaces" for your functions or machine learning models. An interface is a web page that allows users to interact with your code by providing inputs and receiving outputs.
|
28 |
-
|
29 |
-
The core components of a Gradio interface are:
|
30 |
-
- Input components: Widgets that allow users to provide input data, such as text boxes, file uploads, or dropdown menus.
|
31 |
-
- Output components: Elements that display the results of your function or model, such as text, images, or plots.
|
32 |
-
- Function or model: The Python function or machine learning model that takes the input data, processes it, and returns the output data.
|
33 |
-
|
34 |
-
## 4. Component Structure
|
35 |
-
Gradio provides various components that you can use to build your interface. Here are some commonly used components:
|
36 |
-
|
37 |
-
- `gr.Textbox`: A text input component that allows users to enter single-line or multi-line text.
|
38 |
-
- Example: `user_message_input = gr.Textbox(label="User Message", show_copy_button=True)`
|
39 |
-
- `gr.Number`: A numeric input component that allows users to enter numbers with specified precision, minimum, maximum, and step values.
|
40 |
-
- Example: `recursion_limit_input = gr.Number(label="Recursion Limit", value=config.recursion_limit, precision=0, minimum=1, maximum=config.recursion_limit_max, step=1)`
|
41 |
-
- `gr.Dropdown`: A dropdown component that allows users to select an option from a list of choices.
|
42 |
-
- Example: `simple_model_name_input = gr.Dropdown(label="Model Name", choices=config.llms.keys(), value=list(config.llms.keys())[0])`
|
43 |
-
- `gr.Checkbox`: A checkbox component that allows users to toggle a boolean value.
|
44 |
-
- Example: `aggressive_exploration = gr.Checkbox(label="Aggressive Exploration", value=config.aggressive_exploration)`
|
45 |
-
- `gr.Button`: A button component that triggers an event when clicked.
|
46 |
-
- Example: `simple_submit_button = gr.Button(value="Submit", variant="primary")`
|
47 |
-
- `gr.ClearButton`: A button component that clears the specified components when clicked.
|
48 |
-
- Example: `simple_clear_button = gr.ClearButton([user_message_input, expected_output_input, acceptance_criteria_input, initial_system_message_input], value='Clear All')`
|
49 |
-
- `gr.Chatbot`: A chatbot component that displays a conversation-like interface with bubbles for messages.
|
50 |
-
- Example: `logs_chatbot = gr.Chatbot(label='Messages', show_copy_button=True, layout='bubble', bubble_full_width=False, render_markdown=False)`
|
51 |
-
- `gr.Accordion`: A component that allows you to group other components within an accordion-style collapsible section.
|
52 |
- Example:
|
53 |
```python
|
54 |
-
|
55 |
-
|
|
|
56 |
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
1. Button Click Events:
|
62 |
-
- Use the `click()` method on a button component to specify the function to be called when the button is clicked.
|
63 |
-
- Example: `generate_acceptance_criteria_button.click(generate_acceptance_criteria, inputs=[...], outputs=[...])`
|
64 |
-
|
65 |
-
2. Tab Selection Events:
|
66 |
-
- Use the `select()` method on a tab component to specify the function to be called when the tab is selected.
|
67 |
-
- Example: `simple_llm_tab.select(on_model_tab_select)`
|
68 |
-
|
69 |
-
3. Flagging and Saving Data:
|
70 |
-
- Use the `FlagMethod` class to define a flagging callback that saves data when a flag button is clicked.
|
71 |
-
- Example: `flag_method = FlagMethod(flagging_callback, "Flag", "")`
|
72 |
-
- Attach the flagging callback to the flag button using the `click()` method.
|
73 |
-
- Example: `flag_button.click(flag_method, inputs=flagging_inputs, outputs=flag_button, preprocess=False, queue=False, show_api=False)`
|
74 |
-
|
75 |
-
4. Clearing Components:
|
76 |
-
- Use the `ClearButton` component to clear specified components when clicked.
|
77 |
-
- Example: `clear_logs_button = gr.ClearButton([logs_chatbot], value='Clear Logs')`
|
78 |
-
|
79 |
-
5. Loading Examples:
|
80 |
-
- Use the `gr.Examples` component to load examples from a file and populate the specified input components.
|
81 |
-
- Example: `examples = gr.Examples(config.examples_path, inputs=[...])`
|
82 |
-
|
83 |
-
## 6. State Management
|
84 |
-
Gradio provides a way to manage the state of your interface across multiple function calls. You can use the `gr.State()` component to store and pass data between functions.
|
85 |
-
|
86 |
-
Here's an example of using state management in Gradio:
|
87 |
-
|
88 |
-
```python
|
89 |
-
import gradio as gr
|
90 |
-
|
91 |
-
def update_count(count):
|
92 |
-
return count + 1
|
93 |
-
|
94 |
-
count_state = gr.State(0)
|
95 |
-
|
96 |
-
iface = gr.Interface(fn=update_count, inputs=count_state, outputs=count_state)
|
97 |
-
iface.launch()
|
98 |
-
```
|
99 |
-
|
100 |
-
In this example, we define an `update_count` function that takes a count as input and increments it by 1. We create a Gradio interface with a `gr.State()` component initialized with a value of 0. The `update_count` function is called each time the interface is used, updating the count state.
|
101 |
-
|
102 |
-
## 7. Routing
|
103 |
-
Gradio supports creating multi-page interfaces using the `gr.Blocks()` class. You can define multiple pages and navigate between them using buttons or links.
|
104 |
-
|
105 |
-
Here's an example of creating a multi-page interface with Gradio:
|
106 |
-
|
107 |
-
```python
|
108 |
-
import gradio as gr
|
109 |
-
|
110 |
-
with gr.Blocks() as demo:
|
111 |
-
with gr.Tab("Page 1"):
|
112 |
-
# Components for page 1
|
113 |
-
pass
|
114 |
-
with gr.Tab("Page 2"):
|
115 |
-
# Components for page 2
|
116 |
-
pass
|
117 |
-
|
118 |
-
demo.launch()
|
119 |
-
```
|
120 |
-
|
121 |
-
In this example, we create a Gradio interface using `gr.Blocks()` and define two tabs using `gr.Tab()`. Each tab represents a separate page in the interface, and you can add components specific to each page.
|
122 |
-
|
123 |
-
## 8. Data Fetching
|
124 |
-
Gradio allows you to fetch data from external sources, such as APIs or databases, and use it in your interface. You can use the `gr.inputs.Textbox()` component to accept user input and pass it to a function that fetches the data.
|
125 |
-
|
126 |
-
Here's an example of fetching data from an API using Gradio:
|
127 |
-
|
128 |
-
```python
|
129 |
-
import gradio as gr
|
130 |
-
import requests
|
131 |
-
|
132 |
-
def get_data(query):
|
133 |
-
response = requests.get(f"https://api.example.com/data?query={query}")
|
134 |
-
return response.json()
|
135 |
-
|
136 |
-
iface = gr.Interface(fn=get_data, inputs="text", outputs="json")
|
137 |
-
iface.launch()
|
138 |
-
```
|
139 |
-
|
140 |
-
In this example, we define a `get_data` function that takes a query as input, makes a GET request to an API endpoint, and returns the response data as JSON. We create a Gradio interface with a text input component and a JSON output component.
|
141 |
-
|
142 |
-
## 9. Styling
|
143 |
-
Gradio provides options to customize the styling of your interface. You can use CSS classes and inline styles to modify the appearance of components.
|
144 |
-
|
145 |
-
Here's an example of styling components in Gradio:
|
146 |
-
|
147 |
-
```python
|
148 |
-
import gradio as gr
|
149 |
-
|
150 |
-
iface = gr.Interface(
|
151 |
-
fn=lambda x: x,
|
152 |
-
inputs=gr.inputs.Textbox(lines=5, label="Enter text"),
|
153 |
-
outputs="text",
|
154 |
-
title="Text Analysis",
|
155 |
-
description="Enter text to analyze its sentiment.",
|
156 |
-
css=".gradio-container {background-color: #f0f0f0;}",
|
157 |
-
)
|
158 |
-
iface.launch()
|
159 |
-
```
|
160 |
-
|
161 |
-
In this example, we create a Gradio interface with a text input component and a text output component. We customize the styling by providing a CSS class `.gradio-container` to set the background color of the interface container.
|
162 |
-
|
163 |
-
## 10. Performance Optimization
|
164 |
-
To optimize the performance of your Gradio interface, you can consider the following techniques:
|
165 |
-
- Minimize the number of input and output components to reduce the amount of data transferred between the client and server.
|
166 |
-
- Use caching to store and reuse the results of expensive computations.
|
167 |
-
- Implement pagination or lazy loading for large datasets to load data incrementally.
|
168 |
-
- Utilize asynchronous processing for time-consuming tasks to keep the interface responsive.
|
169 |
-
|
170 |
-
Here's an example of using caching in Gradio:
|
171 |
-
|
172 |
-
```python
|
173 |
-
import gradio as gr
|
174 |
-
|
175 |
-
@gr.cache()
|
176 |
-
def expensive_computation(x):
|
177 |
-
# Perform expensive computation
|
178 |
-
return result
|
179 |
-
|
180 |
-
iface = gr.Interface(fn=expensive_computation, inputs="text", outputs="text")
|
181 |
-
iface.launch()
|
182 |
-
```
|
183 |
-
|
184 |
-
In this example, we define an `expensive_computation` function and decorate it with `@gr.cache()` to enable caching. Gradio will store the results of the function for each unique input and reuse them when the same input is provided again, avoiding redundant computations.
|
185 |
-
|
186 |
-
## 11. Testing
|
187 |
-
Gradio provides a way to write unit tests for your interfaces using the `gr.test()` function. You can define test cases with input data and expected output data to verify the correctness of your functions or models.
|
188 |
-
|
189 |
-
Here's an example of writing tests for a Gradio interface:
|
190 |
-
|
191 |
-
```python
|
192 |
-
import gradio as gr
|
193 |
-
|
194 |
-
def greet(name):
|
195 |
-
return f"Hello, {name}!"
|
196 |
-
|
197 |
-
iface = gr.Interface(fn=greet, inputs="text", outputs="text")
|
198 |
-
|
199 |
-
tests = [
|
200 |
-
{"input": "Alice", "output": "Hello, Alice!"},
|
201 |
-
{"input": "Bob", "output": "Hello, Bob!"},
|
202 |
-
]
|
203 |
-
|
204 |
-
gr.test iface, tests
|
205 |
-
```
|
206 |
-
|
207 |
-
In this example, we define a `greet` function and create a Gradio interface. We then define a list of test cases, each specifying an input value and the expected output value. Finally, we use `gr.test()` to run the tests and verify that the interface produces the expected outputs for the given inputs.
|
208 |
|
209 |
-
|
210 |
-
|
|
|
|
|
|
|
|
|
|
|
211 |
|
212 |
-
|
|
|
|
|
|
|
|
|
|
|
213 |
|
214 |
-
|
215 |
-
|
|
|
|
|
216 |
|
217 |
-
|
218 |
-
|
|
|
|
|
|
|
|
|
219 |
|
220 |
-
|
|
|
221 |
|
222 |
-
|
223 |
-
```
|
224 |
|
225 |
-
|
|
|
226 |
|
227 |
-
|
228 |
-
|
229 |
-
-
|
230 |
-
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
235 |
|
236 |
-
Common pitfalls to avoid:
|
237 |
- Overloading the interface with too many components or complex layouts, leading to a confusing user experience.
|
238 |
- Failing to handle edge cases or unexpected inputs, resulting in errors or incorrect outputs.
|
239 |
- Neglecting to secure your interface against potential security risks, such as unauthorized access or malicious inputs.
|
240 |
- Forgetting to optimize the performance of your interface, leading to slow response times or resource exhaustion.
|
241 |
-
|
242 |
-
## 14. Community and Resources
|
243 |
-
Gradio has a vibrant community and provides various resources to help you get started and learn more about the framework. Here are some useful links:
|
244 |
-
- Gradio Documentation: https://gradio.app/docs/
|
245 |
-
- Gradio GitHub Repository: https://github.com/gradio-app/gradio
|
246 |
-
- Gradio Examples: https://gradio.app/examples/
|
247 |
-
- Gradio Community Forum: https://discuss.huggingface.co/c/gradio/33
|
248 |
-
- Gradio Twitter: https://twitter.com/gradio
|
249 |
-
|
250 |
-
These resources provide documentation, examples, and a platform to engage with the Gradio community, ask questions, and share your projects.
|
251 |
-
|
252 |
-
Remember to refer to the Gradio documentation for the most up-to-date information and advanced usage scenarios.
|
253 |
-
|
254 |
-
Happy building with Gradio!
|
255 |
|
|
|
1 |
# Gradio Framework Guideline
|
2 |
|
3 |
+
## Best Practices
|
4 |
+
|
5 |
+
When using Gradio, consider the following best practices:
|
6 |
+
|
7 |
+
- Keep your interface simple and intuitive for users to understand and use.
|
8 |
+
- Provide clear instructions and examples to guide users on how to interact with your interface.
|
9 |
+
- Validate and sanitize user inputs to prevent unexpected behavior or security vulnerabilities.
|
10 |
+
- Handle errors gracefully and provide informative error messages to users.
|
11 |
+
- Optimize the performance of your interface by minimizing the number of components and using caching when appropriate.
|
12 |
+
- Test your interface thoroughly with various inputs and edge cases to ensure its robustness.
|
13 |
+
- Use `gr.File` for file uploads and downloads. The file to download should be prepared before being passed into `gr.File`.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
- Example:
|
15 |
```python
|
16 |
+
json_file = gr.File(
|
17 |
+
label="Import/Export JSON", file_types=[".json"], type="filepath"
|
18 |
+
)
|
19 |
```
|
20 |
+
- `gr.Dataframe` doesn't support deleting rows.
|
21 |
+
- Set `col_count` to `(x, 'fixed')` to make the column width fixed.
|
22 |
+
- Example:
|
23 |
+
```python
|
24 |
+
input_df = gr.DataFrame(
|
25 |
+
label="Input Examples",
|
26 |
+
headers=["Input", "Output"],
|
27 |
+
datatype=["str", "str"],
|
28 |
+
row_count=(1, "dynamic"),
|
29 |
+
col_count=(2, "fixed"),
|
30 |
+
)
|
31 |
+
```
|
32 |
+
- Use `gr.Accordion` to hide advanced or optional settings that are not required for basic usage.
|
33 |
+
- Example:
|
34 |
+
```python
|
35 |
+
with gr.Accordion("Advanced Settings", open=False):
|
36 |
+
gr.Slider(0, 100, 50, label="Slider")
|
37 |
+
```
|
38 |
+
- Use `gr.Tabs` and `gr.Tab` to organize related components into separate views.
|
39 |
+
- Example:
|
40 |
+
```python
|
41 |
+
with gr.Tabs() as llm_tabs:
|
42 |
+
with gr.Tab('Simple') as simple_llm_tab:
|
43 |
+
...
|
44 |
+
with gr.Tab('Advanced') as advanced_llm_tab:
|
45 |
+
...
|
46 |
+
```
|
47 |
+
- Use `gr.Examples` to provide sample inputs for users to test the interface.
|
48 |
+
- Example:
|
49 |
+
```python
|
50 |
+
gr.Examples(
|
51 |
+
examples=[
|
52 |
+
["Hello, world!", "Hello, world!"],
|
53 |
+
["Hello, world!", "Hello, world!"],
|
54 |
+
],
|
55 |
+
inputs=["text", "text"],
|
56 |
+
)
|
57 |
+
- Use `gr.Markdown` to display formatted text, including links and images.
|
58 |
+
- Use `gr.ClearButton` to allow users to clear specific components or the entire interface.
|
59 |
+
- Use the `@gr.render` decorator to create dynamic apps with a variable number of components and event listeners.
|
60 |
+
- Example:
|
61 |
+
```python
|
62 |
+
import gradio as gr
|
63 |
|
64 |
+
with gr.Blocks() as demo:
|
65 |
+
input_text = gr.Textbox(label="input")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
66 |
|
67 |
+
@gr.render(inputs=input_text)
|
68 |
+
def show_split(text):
|
69 |
+
if len(text) == 0:
|
70 |
+
gr.Markdown("## No Input Provided")
|
71 |
+
else:
|
72 |
+
for letter in text:
|
73 |
+
gr.Textbox(letter)
|
74 |
|
75 |
+
demo.launch()
|
76 |
+
```
|
77 |
+
- When using `@gr.render`, set the `key` argument for each component to preserve its value between re-renders.
|
78 |
+
- Example:
|
79 |
+
```python
|
80 |
+
import gradio as gr
|
81 |
|
82 |
+
with gr.Blocks() as demo:
|
83 |
+
text_count = gr.State(1)
|
84 |
+
add_btn = gr.Button("Add Box")
|
85 |
+
add_btn.click(lambda x: x + 1, text_count, text_count)
|
86 |
|
87 |
+
@gr.render(inputs=text_count)
|
88 |
+
def render_count(count):
|
89 |
+
boxes = []
|
90 |
+
for i in range(count):
|
91 |
+
box = gr.Textbox(key=i, label=f"Box {i}")
|
92 |
+
boxes.append(box)
|
93 |
|
94 |
+
def merge(*args):
|
95 |
+
return " ".join(args)
|
96 |
|
97 |
+
merge_btn.click(merge, boxes, output)
|
|
|
98 |
|
99 |
+
merge_btn = gr.Button("Merge")
|
100 |
+
output = gr.Textbox(label="Merged Output")
|
101 |
|
102 |
+
demo.launch()
|
103 |
+
```
|
104 |
+
- Update component attributes with `gr.update()` in the return statement of the event callback function.
|
105 |
+
- Example:
|
106 |
+
```python
|
107 |
+
def update_output(text):
|
108 |
+
return gr.update(value=text)
|
109 |
+
```
|
110 |
+
- Use `gr.State` to maintain the state of your interface between re-renders, and to synchronize the updating of multiple components.
|
111 |
+
- Example:
|
112 |
+
```python
|
113 |
+
import gradio as gr
|
114 |
+
|
115 |
+
def on_state_change(state: gr.State):
|
116 |
+
return gr.update(visible=state.value), gr.update(visible=state.value)
|
117 |
+
|
118 |
+
with gr.Blocks() as demo:
|
119 |
+
text1 = gr.Textbox(label="Text 1")
|
120 |
+
text2 = gr.Textbox(label="Text 2")
|
121 |
+
state = gr.State(value=True)
|
122 |
+
state.change(on_state_change, state, [text1, text2])
|
123 |
+
|
124 |
+
demo.launch()
|
125 |
+
```
|
126 |
+
## Common pitfalls to avoid
|
127 |
|
|
|
128 |
- Overloading the interface with too many components or complex layouts, leading to a confusing user experience.
|
129 |
- Failing to handle edge cases or unexpected inputs, resulting in errors or incorrect outputs.
|
130 |
- Neglecting to secure your interface against potential security risks, such as unauthorized access or malicious inputs.
|
131 |
- Forgetting to optimize the performance of your interface, leading to slow response times or resource exhaustion.
|
132 |
+
- When using `@gr.render`, not setting the `key` argument for components, causing their values to be lost between re-renders.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
133 |
|