dn6 HF staff commited on
Commit
0216c0d
β€’
1 Parent(s): 4222b0d

refactor to use gradio state

Browse files
Files changed (1) hide show
  1. app.py +167 -103
app.py CHANGED
@@ -1,123 +1,187 @@
1
- import comet_ml
2
  import uuid
 
 
3
  import gradio as gr
 
 
 
 
 
4
 
 
 
5
 
6
  DESCRIPTION = """Glad to see you here πŸ˜„.
7
  You can use this Space to log predictions to [Comet](https://www.comet.ml/site) from Spaces that use Text to Image Diffusion Models.
8
 
9
- Keep track of all your prompts and generated images so that you can easily find the good ones!
10
 
11
- Set your Comet credentials in the Comet Settings tab, and select the Space you want to log predictions
12
- from in the Diffusion Model tab
13
- """
14
 
 
 
15
 
16
- class MyProject:
17
- def __init__(self):
18
- self.experiment = None
19
 
20
- def start_experiment(
21
- self, comet_api_key: str, comet_workspace: str, comet_project_name: str
22
- ):
23
- if not comet_api_key:
24
- return """
 
 
 
 
 
 
 
25
  Please add your API key in order to log your predictions to a Comet Experiment.
26
  If you don't have a Comet account yet, you can sign up using the link below:
27
 
28
- [Sign Up for Comet](https://www.comet.ml/signup)
29
- """
 
30
 
31
- else:
32
- try:
33
- self.experiment = comet_ml.Experiment(
34
- api_key=comet_api_key,
35
- workspace=comet_workspace,
36
- project_name=comet_project_name,
37
- )
38
- self.experiment.add_tags(["spaces"])
39
-
40
- return f"Started {self.experiment.name}. Happy logging!😊"
41
-
42
- except Exception as e:
43
- return e
44
-
45
- def end_experiment(self):
46
- if self.experiment is not None:
47
- self.experiment.end()
48
- return f"Ended {self.experiment.name}"
49
-
50
- def get_experiment_status(self):
51
- return f"Running {self.experiment.name}"
52
-
53
- def start_comet_interface(self):
54
- demo = gr.Blocks()
55
- with demo:
56
- # credentials
57
- comet_api_key = gr.Textbox(label="Comet API Key")
58
- comet_workspace = gr.Textbox(label="Comet Workspace")
59
- comet_project_name = gr.Textbox(label="Comet Project Name")
60
-
61
- with gr.Row():
62
- start_experiment = gr.Button("Start Experiment", variant="primary")
63
- status = gr.Button("Experiment Status")
64
- end_experiment = gr.Button("End Experiment", variant="secondary")
65
-
66
- output = gr.Markdown(label="Status")
67
-
68
- start_experiment.click(
69
- self.start_experiment,
70
- inputs=[
71
- comet_api_key,
72
- comet_workspace,
73
- comet_project_name,
74
- ],
75
- outputs=output,
76
- )
77
- status.click(self.get_experiment_status, inputs=None, outputs=None)
78
- end_experiment.click(self.end_experiment, inputs=None, outputs=output)
79
-
80
- return demo
81
-
82
- def predict(
83
- self,
84
- model,
85
- prompt,
86
- ):
87
- io = gr.Interface.load(model)
88
- image = io(prompt)
89
-
90
- if self.experiment is not None:
91
- image_id = uuid.uuid4().hex
92
- self.experiment.log_image(image, name=image_id)
93
- self.experiment.log_text(
94
- prompt, metadata={"image_id": image_id, "model": model}
95
- )
96
-
97
- return image
98
-
99
- def load_interface(self):
100
- model = gr.Textbox(label="Model", value="spaces/valhalla/glide-text2im")
101
- prompt = gr.Textbox(label="Prompt")
102
-
103
- outputs = gr.Image(label="Image")
104
-
105
- interface = gr.Interface(
106
- self.predict,
107
- inputs=[model, prompt],
108
- outputs=outputs,
109
- examples=[["spaces/valhalla/glide-text2im", "An oil painting of a corgi"]],
110
- description=DESCRIPTION,
111
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
- return interface
114
 
115
- def launch(self):
116
- interface = gr.TabbedInterface(
117
- [self.start_comet_interface(), self.load_interface()],
118
- tab_names=["Comet Settings", "Diffusion Model"],
119
- )
120
- interface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
 
123
- MyProject().launch()
 
1
+ import json
2
  import uuid
3
+
4
+ import comet_ml
5
  import gradio as gr
6
+ import pandas as pd
7
+ from PIL import Image
8
+ from transformers import CLIPModel, CLIPProcessor
9
+
10
+ CLIP_MODEL_PATH = "openai/clip-vit-base-patch32"
11
 
12
+ clip_model = CLIPModel.from_pretrained(CLIP_MODEL_PATH)
13
+ clip_processor = CLIPProcessor.from_pretrained(CLIP_MODEL_PATH)
14
 
15
  DESCRIPTION = """Glad to see you here πŸ˜„.
16
  You can use this Space to log predictions to [Comet](https://www.comet.ml/site) from Spaces that use Text to Image Diffusion Models.
17
 
18
+ Keep track of all your prompts and generated images so that you remember the good ones!
19
 
20
+ Set your Comet credentials in the Comet Settings tab and create an Experiment for logging data.
21
+ If you want to continue logging to the same Experiment over multiple sessions, add in the
 
22
 
23
+ Then use the path to a Space to generate from in the Diffusion Model tab
24
+ """
25
 
 
 
 
26
 
27
+ def create_experiment(
28
+ comet_api_key,
29
+ comet_workspace,
30
+ comet_project_name,
31
+ comet_experiment_name,
32
+ experiment,
33
+ ):
34
+ if not comet_api_key:
35
+ experiment = None
36
+ return (
37
+ experiment,
38
+ """
39
  Please add your API key in order to log your predictions to a Comet Experiment.
40
  If you don't have a Comet account yet, you can sign up using the link below:
41
 
42
+ https://www.comet.ml/signup
43
+ """,
44
+ )
45
 
46
+ try:
47
+ api_experiment = comet_ml.APIExperiment(
48
+ api_key=comet_api_key,
49
+ workspace=comet_workspace,
50
+ project_name=comet_project_name,
51
+ experiment_name=comet_experiment_name,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  )
53
+ experiment = {
54
+ "api_key": comet_api_key,
55
+ "workspace": comet_workspace,
56
+ "project_name": comet_project_name,
57
+ "previous_experiment": api_experiment.id,
58
+ }
59
+
60
+ return experiment, f"Started {api_experiment.name}. Happy logging!😊"
61
+
62
+ except Exception as e:
63
+ return None, e
64
+
65
+
66
+ def get_experiment(kwargs) -> comet_ml.APIExperiment:
67
+ try:
68
+ return comet_ml.APIExperiment(**kwargs)
69
+ except Exception as e:
70
+ return None
71
+
72
+
73
+ def get_experiment_status(experiment_state):
74
+ experiment = get_experiment(experiment_state)
75
+ if experiment is not None:
76
+ name = experiment.name
77
+ return experiment_state, f"Currently logging to: {name}"
78
+
79
+ return experiment_state, f"No Experiments found"
80
+
81
+
82
+ def predict(
83
+ model,
84
+ prompt,
85
+ experiment_state,
86
+ ):
87
+ io = gr.Interface.load(model)
88
+ image = io(prompt)
89
+ pil_image = Image.open(image)
90
+
91
+ inputs = clip_processor(
92
+ text=[prompt],
93
+ images=pil_image,
94
+ return_tensors="pt",
95
+ padding=True,
96
+ )
97
+ outputs = clip_model(**inputs)
98
+ clip_score = outputs.logits_per_image.item() / 100.0
99
+
100
+ experiment = get_experiment(experiment_state)
101
+ if experiment is not None:
102
+ image_id = uuid.uuid4().hex
103
+ experiment.log_image(image, image_id)
104
+
105
+ asset = pd.DataFrame.from_records(
106
+ [
107
+ {
108
+ "prompt": prompt,
109
+ "model": model,
110
+ "clip_model": CLIP_MODEL_PATH,
111
+ "clip_score": round(clip_score, 3),
112
+ }
113
+ ]
114
+ )
115
+ experiment.log_table(f"{image_id}.json", asset, orient="records")
116
 
117
+ return image, experiment_state
118
 
119
+
120
+ def start_interface():
121
+ demo = gr.Blocks()
122
+ with demo:
123
+ description = gr.Markdown(DESCRIPTION)
124
+ with gr.Tabs():
125
+ with gr.TabItem(label="Comet Settings"):
126
+ # credentials
127
+ comet_api_key = gr.Textbox(
128
+ label="Comet API Key",
129
+ placeholder="This is required if you'd like to create an Experiment",
130
+ )
131
+ comet_workspace = gr.Textbox(label="Comet Workspace")
132
+ comet_project_name = gr.Textbox(label="Comet Project Name")
133
+ comet_experiment_name = gr.Textbox(
134
+ label="Comet Experiment Name",
135
+ placeholder=(
136
+ "Set this if you'd like"
137
+ "to continue logging to an existing Experiment",
138
+ ),
139
+ )
140
+
141
+ with gr.Row():
142
+ start = gr.Button("Create Experiment", variant="primary")
143
+ status = gr.Button("Experiment Status")
144
+
145
+ output = gr.Markdown(label="Status")
146
+ experiment_state = gr.Variable(label="Experiment State")
147
+
148
+ start.click(
149
+ create_experiment,
150
+ inputs=[
151
+ comet_api_key,
152
+ comet_workspace,
153
+ comet_project_name,
154
+ comet_experiment_name,
155
+ experiment_state,
156
+ ],
157
+ outputs=[experiment_state, output],
158
+ )
159
+
160
+ status.click(
161
+ get_experiment_status,
162
+ inputs=[experiment_state],
163
+ outputs=[experiment_state, output],
164
+ )
165
+
166
+ with gr.TabItem(label="Diffusion Model"):
167
+ diff_description = gr.Markdown(
168
+ """The Model must be a path to any Space that accepts"
169
+ only text as input and produces an image as an output
170
+ """
171
+ )
172
+ model = gr.Textbox(label="Model", value="spaces/valhalla/glide-text2im")
173
+ prompt = gr.Textbox(label="Prompt")
174
+
175
+ outputs = gr.Image(label="Image")
176
+
177
+ submit = gr.Button("Submit", variant="primary")
178
+ submit.click(
179
+ predict,
180
+ inputs=[model, prompt, experiment_state],
181
+ outputs=[outputs, experiment_state],
182
+ )
183
+
184
+ demo.launch()
185
 
186
 
187
+ start_interface()