rayochoajr commited on
Commit
69bbb68
·
1 Parent(s): 6c3f7b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -432
app.py CHANGED
@@ -1,433 +1,38 @@
1
  import gradio as gr
2
- import random
3
- from random import choice
4
- import requests
5
- import base64
6
- import io
7
- import re
8
- import plotly.graph_objects as go
9
- import numpy as np
10
- from PIL import Image, ImageDraw
11
- import random
12
- import re
13
- import os
14
- import shutil
15
- import gdown
16
- import pandas as pd
17
- import plotly.express as px
18
- import streamlit as st
19
-
20
-
21
- # Try to import plotly, if not installed, install it
22
- try:
23
- import plotly
24
- except ImportError:
25
- os.system('pip install plotly')
26
-
27
- # Define your inputs outside of the gr.Row() block
28
- # These are the inputs that will be used to generate the radar chart
29
- input_parameters = gr.Textbox(placeholder="Enter parameters, separated by commas", label="Parameters")
30
- randomize_values = gr.Checkbox(label="Randomize Values", value=True)
31
- randomize_titles = gr.Checkbox(label="Randomize Titles", value=True)
32
- randomize_param_count = gr.Checkbox(label="Randomize Parameter Count")
33
- chart_title = gr.Textbox(value="Radar Chart", label="Chart Title")
34
- param_count = gr.Slider(minimum=3, maximum=10, step=1, label="Parameter Count")
35
- param1 = gr.Slider(minimum=0, maximum=1.5, step=0.25, label="Parameter 1", value=.75)
36
- param2 = gr.Slider(minimum=0, maximum=1.5, step=0.25, label="Parameter 2", value=.75)
37
- param3 = gr.Slider(minimum=0, maximum=1.5, step=0.25, label="Parameter 3", value=.75)
38
- param4 = gr.Slider(minimum=0, maximum=1.5, step=0.25, label="Parameter 4", value=.75)
39
- param5 = gr.Slider(minimum=0, maximum=1.5, step=0.25, label="Parameter 5", value=.75)
40
- param6 = gr.Slider(minimum=0, maximum=1.5, step=0.25, label="Parameter 6", value=.75)
41
- param7 = gr.Slider(minimum=0, maximum=1.5, step=0.25, label="Parameter 7", value=.75)
42
- param8 = gr.Slider(minimum=0, maximum=1.5, step=0.25, label="Parameter 8", value=.75)
43
- param9 = gr.Slider(minimum=0, maximum=1.5, step=0.25, label="Parameter 9", value=.75)
44
- param10 = gr.Slider(minimum=0, maximum=1.5, step=0.25, label="Parameter 10", value=.75)
45
- prompt_input = gr.Textbox(lines=2, placeholder="Imagine something...", label="Prompt", value="__cars__")
46
- steps_input = gr.Slider(minimum=15, maximum=50, step=15, value=5, label="Steps")
47
- reset_seed_input = gr.Checkbox(label="Randomize Composition")
48
- increment_seed_input = gr.Checkbox(label="New Composition")
49
- img_output = gr.Image(label="Generated Image")
50
- radar_output = gr.Plot(label="Radar Chart")
51
- slider_labels_output = gr.Textbox(label="Prompt: Slider Labels")
52
- title1 = gr.Textbox(value='Minimalism', label="Title 1")
53
- title2 = gr.Textbox(value='Bauhaus', label="Title 2")
54
- title3 = gr.Textbox(value='Organic Design', label="Title 3")
55
- title4 = gr.Textbox(value='Brutalism', label="Title 4")
56
- title5 = gr.Textbox(value='Mid-century Modern', label="Title 5")
57
- title6 = gr.Textbox(value='Retro-Vintage', label="Title 6")
58
- title7 = gr.Textbox(value='Futurism', label="Title 7")
59
- title8 = gr.Textbox(value='Tesselated', label="Title 8")
60
- title9 = gr.Textbox(value='Streamlined', label="Title 9")
61
- title10 = gr.Textbox(value='Timeless', label="Title 10")
62
-
63
- # Define other inputs and outputs
64
- # These are the inputs and outputs that will be used to generate the image
65
- prompt_input = gr.Textbox(lines=2, placeholder="Imagine something...", label="Prompt", value="__cars__")
66
- steps_input = gr.Slider(minimum=15, maximum=50, step=5, value=15, label="Steps")
67
- img_output = gr.Image(label="Generated Image")
68
- prompt = "__cars__"
69
- slider_labels = "concept art sketch"
70
- full_prompt = f"{prompt} {slider_labels}"
71
- prompt_input1 = title1
72
- prompt_input2 = title2
73
- prompt_input3 = title3
74
-
75
-
76
- # Global variables
77
- url = "http://73.255.78.150:7909/sdapi/v1/txt2img"
78
- session_seed = 1
79
- # Set a global variable for steps_input
80
- steps_input = 25
81
- last_session_seed = 2
82
- ALL_TITLES = [
83
- 'Minimalism', 'Bauhaus', 'Organic Design', 'Brutalism', 'Mid-century Modern',
84
- 'Retro-Vintage', 'Futurism', 'Tesselated', 'Streamlined', 'Timeless',
85
- 'Industrial Chic', 'Art Deco', 'Elegant', 'Biomorphic Design', 'High Contrast',
86
- 'Deconstructivism', 'Zen Design', 'Pop Art', 'Cyberpunk', 'Sustainable Design',
87
- 'Angular', 'Textured', 'Symmetric', 'Utilitarian', 'Dynamic Energy Flow',
88
- 'Less Extreme', 'Moderately Avant-Garde', 'Highly Avant-Garde'
89
- ]
90
- ALL_VALUES = [
91
- 1.5, 1.2, 0.8, 1.0, 0.5, 1.0, 0.3, 0.5, 1.1, 0.7,
92
- 0.9, 1.3, 0.2, 1.3, 0.9, 1.1, 0.7, 0.6, 0.8, 0.4,
93
- 0.2, 0.1, 1.2, 0.0, 0.4
94
- ]
95
- base_payload = {
96
- "steps": 25,
97
- "seed": 1,
98
- "width": 768,
99
- "height": 512,
100
- }
101
-
102
- # Function to change the global variable 'prompt'
103
- def change_prompt(new_prompt):
104
- global prompt # declare that we're using the global variable
105
- prompt = new_prompt # overwrite the global variable
106
-
107
- change_prompt("__trains__")
108
- print(prompt) # will output "__trains__"
109
-
110
- def generate_image(prompt_input, steps, reset_seed, increment_seed):
111
- global session_seed
112
- global last_session_seed
113
- global slider_labels
114
- global prompt # declare that we're using the global variable
115
- prompt = prompt_input # overwrite the global variable with the new input
116
- if reset_seed:
117
- if session_seed != -1:
118
- last_session_seed = session_seed
119
- session_seed = -1
120
- elif not reset_seed and last_session_seed is not None:
121
- session_seed = last_session_seed
122
- elif session_seed is None:
123
- session_seed = random.randint(0, 10000)
124
- if increment_seed and session_seed != -1:
125
- session_seed += 1
126
-
127
-
128
-
129
-
130
- # Function definitions
131
- def generate_figure(r_values, theta_values, chart_title):
132
- fig = go.Figure(data=go.Scatterpolar(
133
- r=r_values, theta=theta_values, mode='lines+markers',
134
- marker=dict(size=10), fill='toself')
135
- )
136
- fig.update_layout(
137
- polar=dict(radialaxis=dict(visible=True, range=[-1.5, 1.75])),
138
- showlegend=False, title=chart_title
139
- )
140
- return fig
141
-
142
- # Global variables to store the initial values
143
- initial_values = [("Textured", 0.75), ("Deconstructivism", 0.75), ("Utilitarian", 0.75)]
144
-
145
- # Global variables to store the temporary arrays
146
- temp_parameters = [title for title, value in initial_values]
147
- temp_array = [value for title, value in initial_values]
148
- temp_r_values = [value for title, value in initial_values]
149
-
150
- def display_radar_chart(input_parameters, randomize_values, randomize_titles, randomize_param_count, chart_title, param_count, *params):
151
- global slider_labels # Ensure this variable is available in your scope
152
- global temp_parameters, temp_r_values # Declare the global variables
153
-
154
- print(f"Input Parameters: {input_parameters}")
155
- print(f"Randomize Values: {randomize_values}")
156
- print(f"Randomize Titles: {randomize_titles}")
157
- print(f"Randomize Parameter Count: {randomize_param_count}")
158
- print(f"Chart Title: {chart_title}")
159
- print(f"Parameter Count: {param_count}")
160
-
161
- if randomize_param_count:
162
- param_count = random.randint(3, 10)
163
-
164
- # Create a temporary array from comma-separated input_parameters
165
- if input_parameters:
166
- temp_parameters = re.split(r'\s*,\s*', input_parameters.strip())
167
- if len(temp_parameters) > param_count:
168
- temp_parameters = temp_parameters[:param_count]
169
- elif randomize_titles:
170
- temp_parameters = random.sample(ALL_TITLES, param_count)
171
- else:
172
- temp_parameters = []
173
-
174
- # Fill in missing parameters based on param_count
175
- if len(temp_parameters) < param_count:
176
- remaining_count = param_count - len(temp_parameters)
177
- additional_params = random.sample(set(ALL_TITLES) - set(temp_parameters), remaining_count)
178
- temp_parameters.extend(additional_params)
179
-
180
- # Create a temporary array for values
181
- if randomize_values:
182
- temp_r_values = random.sample(ALL_VALUES, len(temp_parameters))
183
- else:
184
- temp_r_values = list(params[:len(temp_parameters)])
185
-
186
- chart_figure = generate_figure(temp_r_values, temp_parameters, chart_title)
187
- slider_labels = ", ".join([f"({temp_parameters[i]}: {temp_r_values[i]:.2f})" for i in range(len(temp_r_values))])
188
-
189
- # Generate the radar chart
190
- fig = generate_figure(temp_r_values, temp_parameters, chart_title)
191
- return fig, slider_labels
192
-
193
- def set_initial_state():
194
- # Set default values for the form
195
- input_parameters = ""
196
- randomize_values = True
197
- randomize_titles = True
198
- randomize_param_count = False
199
- chart_title = "Radar Chart"
200
- param_count = 5
201
- title1 = 'Minimalism'
202
- param1 = 0.75
203
- title2 = 'Bauhaus'
204
- param2 = 0.75
205
- title3 = 'Organic Design'
206
- param3 = 0.75
207
- title4 = 'Brutalism'
208
- param4 = 0.75
209
- title5 = 'Mid-century Modern'
210
- param5 = 0.75
211
- title6 = 'Retro-Vintage'
212
- param6 = 0.75
213
- title7 = 'Futurism'
214
- param7 = 0.75
215
- title8 = 'Tesselated'
216
- param8 = 0.75
217
- title9 = 'Streamlined'
218
- param9 = 0.75
219
- title10 = 'Timeless'
220
- param10 = 0.75
221
-
222
-
223
-
224
- # Call display_radar_chart with default values
225
- return display_radar_chart(input_parameters, randomize_values, randomize_titles, randomize_param_count, chart_title, param_count, title1, param1, title2, param2, title3, param3, title4, param4, title5, param5, title6, param6, title7, param7, title8, param8, title9, param9, title10, param10)
226
-
227
- # Call set_initial_state when the app is first loaded
228
- set_initial_state()
229
-
230
- def generate_image(prompt_input, steps_input, reset_seed_input, increment_seed_input):
231
- global session_seed, last_session_seed, slider_labels
232
- print(f"Prompt Input: {prompt_input}")
233
- print(f"Steps Input: {steps_input}")
234
- print(f"Reset Seed Input: {reset_seed_input}")
235
- print(f"Increment Seed Input: {increment_seed_input}")
236
-
237
- if reset_seed_input:
238
- session_seed = random.randint(1, 10000)
239
- elif increment_seed_input and last_session_seed is not None:
240
- session_seed = last_session_seed + 1
241
- last_session_seed = session_seed
242
- # Update the base_payload with the new values
243
- full_prompt = f"{prompt_input} inspired by {slider_labels}"
244
- base_payload.update({
245
- "prompt": full_prompt,
246
- "steps": 25,
247
- "seed": session_seed,
248
- "negative_prompt": "",
249
- "prompt_styles": ["RayOPunk"],
250
- "sampler_index": "DPM++ 2M Karras",
251
- "restore_faces": False,
252
- "tiling": False,
253
- "n_iter": 1,
254
- "batch_size": 1,
255
- "cfg_scale": 7.0,
256
- "subseed": -1,
257
- "subseed_strength": 0.0,
258
- "seed_resize_from_h": -1,
259
- "seed_resize_from_w": -1,
260
- "seed_enable_extras": False,
261
- "height": 768,
262
- "width": 1024,
263
- "enable_hr": False,
264
- "denoising_strength": 0.0,
265
- "hr_scale": 2.0,
266
- "hr_upscaler": "Latent",
267
- "hr_second_pass_steps": 0,
268
- "hr_resize_x": 0,
269
- "hr_resize_y": 0,
270
- "hr_sampler_index": "",
271
- "hr_prompt": "",
272
- "hr_negative_prompt": "",
273
- "override_settings_texts": ""
274
- })
275
- # Make the API call
276
- response = requests.post(url, json=base_payload)
277
-
278
- # Handle the response
279
- response_data = response.json()
280
- try:
281
- # Decode the base64 image
282
- img_data = base64.b64decode(response_data['images'][0])
283
- img = Image.open(io.BytesIO(img_data))
284
- except KeyError:
285
- # Handle error in response
286
- error_message = response_data.get('error', 'Unknown error')
287
- error_image = Image.new('RGB', (512, 512), color=(73, 109, 137))
288
- d = ImageDraw.Draw(error_image)
289
- d.text((10, 10), f"Error: {error_message}", fill=(255, 255, 0))
290
- img = error_image
291
-
292
- return img
293
-
294
- def update_titles(title1, title2, title3, title4, title5, title6, title7, title8, title9, title10):
295
- global slider_labels
296
- slider_labels = ', '.join([title1, title2, title3, title4, title5, title6, title7, title8, title9, title10])
297
- return slider_labels
298
-
299
- def radar_chart_fn(input_parameters, randomize_values, randomize_titles, randomize_param_count, chart_title, param_count, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, title1, title2, title3, title4, title5, title6, title7, title8, title9, title10):
300
- # Generate the radar chart
301
- radar_chart, slider_labels = display_radar_chart(input_parameters, randomize_values, randomize_titles, randomize_param_count, chart_title, param_count, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, title1, title2, title3, title4, title5, title6, title7, title8, title9, title10)
302
- return radar_chart, slider_labels
303
-
304
- last_radar_chart = None
305
- last_slider_labels = None
306
- last_img = None
307
-
308
- def radar_chart_fn(input_parameters, randomize_values, randomize_titles, randomize_param_count, chart_title, param_count, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, title1, title2, title3, title4, title5, title6, title7, title8, title9, title10):
309
- global last_radar_chart, last_slider_labels
310
- # Generate the radar chart
311
- last_radar_chart, last_slider_labels = display_radar_chart(input_parameters, randomize_values, randomize_titles, randomize_param_count, chart_title, param_count, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, title1, title2, title3, title4, title5, title6, title7, title8, title9, title10)
312
- return last_radar_chart, last_slider_labels
313
-
314
- def image_fn(prompt_input, steps_input, reset_seed_input, increment_seed_input):
315
- global last_img
316
- # Generate the image
317
- last_img = generate_image(prompt_input, steps_input, reset_seed_input, increment_seed_input)
318
- return last_img
319
-
320
- def output_radar_chart_fn():
321
- # Return the last generated radar chart
322
- return last_radar_chart, last_slider_labels
323
-
324
- def output_image_fn():
325
- # Return the last generated image
326
- return last_img
327
-
328
- # Create the Gradio Interface for Radar Chart
329
- with gr.Blocks() as app:
330
- gr.Markdown("# Radar Chart")
331
-
332
- radar_interface = gr.Interface(
333
- fn=radar_chart_fn,
334
- inputs=[input_parameters, randomize_values, randomize_titles, randomize_param_count, chart_title, param_count, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, title1, title2, title3, title4, title5, title6, title7, title8, title9, title10],
335
- outputs=[radar_output, slider_labels_output])
336
-
337
-
338
- def image_fn(prompt_input, steps_input, reset_seed_input, increment_seed_input):
339
- # Generate the image
340
- img = generate_image(prompt_input, steps_input, reset_seed_input, increment_seed_input)
341
- return img
342
-
343
- def generate_and_display_image(prompt_input, title, param, steps_input):
344
- full_prompt = f"{prompt_input} inspired by ({title}:{param})"
345
- img = generate_image(full_prompt, steps_input, reset_seed_input=False, increment_seed_input=False)
346
- return img
347
-
348
-
349
- def radar_chart_fn(input_parameters, randomize_values, randomize_titles, randomize_param_count, chart_title, param_count, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, title1, title2, title3, title4, title5, title6, title7, title8, title9, title10):
350
- global last_radar_chart, last_slider_labels
351
- # Generate the radar chart
352
- last_radar_chart, last_slider_labels = display_radar_chart(input_parameters, randomize_values, randomize_titles, randomize_param_count, chart_title, param_count, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, title1, title2, title3, title4, title5, title6, title7, title8, title9, title10)
353
- set_textbox_values(last_slider_labels)
354
- return last_radar_chart, last_slider_labels
355
-
356
- def output_radar_chart_fn():
357
- # Return the last generated radar chart
358
- set_textbox_values(last_slider_labels)
359
- return last_radar_chart, last_slider_labels
360
-
361
- with gr.Blocks() as app:
362
- with gr.Accordion("Inputs and Outputs", collapsed=True):
363
- radar_interface = gr.Interface(
364
- fn=radar_chart_fn,
365
- inputs=[input_parameters, randomize_values, randomize_titles, randomize_param_count, chart_title, param_count, param1, param2, param3],
366
- outputs=[radar_output, slider_labels_output])
367
- prompt_input = gr.Textbox(lines=2, placeholder="Imagine something...", label="Prompt", value="__cars__")
368
- reset_seed_input = gr.Checkbox(label="Randomize Composition")
369
- increment_seed_input = gr.Checkbox(label="New Composition")
370
- img_output = gr.Image(label="Generated Image")
371
- iface = gr.Interface(
372
- fn=image_fn,
373
- inputs=[prompt_input, reset_seed_input, increment_seed_input],
374
- outputs=[img_output],
375
- live=False
376
- )
377
- with gr.Row():
378
- with gr.Column(scale=2):
379
- output_image_interface = gr.Interface(
380
- fn=output_image_fn,
381
- inputs=[],
382
- outputs=[img_output],
383
- live=True
384
- )
385
- with gr.Column(scale=1):
386
- output_radar_interface = gr.Interface(
387
- fn=output_radar_chart_fn,
388
- inputs=[],
389
- outputs=[radar_output, slider_labels_output])
390
-
391
- def set_textbox_values(slider_labels_output):
392
- # Validate the input
393
- if not slider_labels_output:
394
- return
395
-
396
- # Split and parse the slider_labels_output
397
- slider_data = slider_labels_output.split(', ')
398
-
399
- for i, data in enumerate(slider_data):
400
- try:
401
- title, value = data.split(':')
402
- globals()[f'title{i+1}'].value = title.strip()
403
- globals()[f'param{i+1}'].value = float(value.strip())
404
- except ValueError:
405
- print(f"Could not parse data for slider {i+1}")
406
-
407
- # Example usage:
408
- slider_labels_output = "title1: 0.5, title2: 0.8, title3: 0.2"
409
- set_textbox_values(slider_labels_output)
410
-
411
-
412
- # Call this function to update the textboxes and sliders before creating them
413
- set_textbox_values(last_slider_labels)
414
- # Assuming slider_labels_output is a string like "(title1: value1), (title2: value2), ..."
415
- slider_labels_output = "(title1: 0.75), (title2: 0.5), (title3: 1.25)"
416
- # Split the string into individual labels
417
- labels = slider_labels_output.split(", ")
418
-
419
- # Extract the values from each label and convert them to floats
420
- initial_values = [float(label.split(": ")[1].strip(")")) for label in slider_labels_output.split(", ")]
421
-
422
- with gr.Row():
423
- for i in range(1, len(initial_values) + 1):
424
- with gr.Column(scale=1):
425
- param = gr.Slider(minimum=0, maximum=1.5, step=0.25, label=f"Parameter {i}", value=temp_array[i-1])
426
- title = gr.Textbox(value=temp_parameters[i-1], label=f"Inspiration Word {i}")
427
- img = gr.Interface(fn=generate_and_display_image, inputs=[prompt_input, title, param], outputs="image")
428
-
429
- # Add the slider_labels_output textbox to a new row
430
- with gr.Row():
431
- slider_labels_output = gr.Textbox(value=slider_labels_output, label="Slider Labels")
432
- # Launch the app
433
- app.launch(share=True)
 
1
  import gradio as gr
2
+ import threading
3
+ import subprocess
4
+ import time # Import time module
5
+
6
+ # Initial Gradio app code
7
+ code = """import gradio as gr
8
+
9
+ def greet(name):
10
+ return f"Hello {name}!"
11
+
12
+ iface = gr.Interface(fn=greet, inputs="text", outputs="text")
13
+ iface.launch(share=True)
14
+ """
15
+
16
+ port = 7860 # Initial port
17
+
18
+ def run_code(new_code, port):
19
+ with open("app.py", "w") as file:
20
+ file.write(new_code)
21
+ subprocess.run(["python", "app.py", f"--port={port + 1}"]) # Specify port
22
+
23
+ def update_code(submitted_code):
24
+ global code, port
25
+ code = submitted_code
26
+ port += 1 # Increment port for each new Gradio interface
27
+ threading.Thread(target=run_code, args=(code, port)).start()
28
+ time.sleep(5) # Add a delay of 5 seconds
29
+ return f'<iframe src="http://localhost:{port}/" width="100%" height="400"></iframe>'
30
+
31
+ def main_ui():
32
+ code_input = gr.Textbox(lines=20, label="Code Editor", value=code) # Corrected the import for Textbox
33
+ iframe_output = gr.HTML() # Created HTML component for iframe output
34
+ iface = gr.Interface(fn=update_code, inputs=code_input, outputs=iframe_output, live=False, share=True) # Included share=True
35
+ iface.launch()
36
+
37
+ if __name__ == "__main__":
38
+ main_ui()