Zack3D commited on
Commit
655cb1b
1 Parent(s): 1f31b4d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +301 -301
app.py CHANGED
@@ -1,302 +1,302 @@
1
- import gradio as gr
2
- from anthropic import Anthropic
3
- from openai import OpenAI
4
- import openai
5
- import json
6
- import uuid
7
- import os
8
- import base64
9
- from PIL import Image
10
- from PIL.PngImagePlugin import PngInfo
11
- from io import BytesIO
12
-
13
- default_urls = ["https://api.anthropic.com", "https://api.openai.com/v1"]
14
-
15
- # List of available Claude models
16
- claude_models = ["claude-3-5-sonnet-20240620", "claude-3-opus-20240229", "claude-3-sonnet-20240229", "claude-3-haiku-20240307"]
17
-
18
- # List of available OpenAI models
19
- openai_models = ["gpt-4o", "gpt-4o-mini", "gpt-4", "gpt-4-32k", "gpt-3.5-turbo", "gpt-4-0125-preview", "gpt-4-turbo-preview", "gpt-4-1106-preview", "gpt-4-0613"]
20
-
21
- image_prompter = ["SDXL", "midjourney"]
22
-
23
- both_models = claude_models + openai_models
24
-
25
- def generate_response(endpoint, api_key, model, user_prompt):
26
- print(endpoint)
27
- if endpoint in default_urls:
28
- #check api keys as normal
29
- if api_key.startswith("sk-ant-"):
30
- client = Anthropic(api_key=api_key, base_url=endpoint)
31
- system_prompt_path = __file__.replace("app.py", "json.txt")
32
- elif api_key.startswith("sk-"):
33
- client = OpenAI(api_key=api_key, base_url=endpoint)
34
- system_prompt_path = __file__.replace("app.py", "json.txt")
35
- else:
36
- print(f"Invalid API key: {api_key}")
37
- return "Invalid API key", "Invalid API key", None
38
- else:
39
- if model in claude_models:
40
- # Set the Anthropic API key
41
- client = Anthropic(api_key=api_key, base_url=endpoint)
42
- system_prompt_path = __file__.replace("app.py", "json.txt")
43
- else:
44
- # Set the OpenAI API key
45
- client = OpenAI(api_key=api_key, base_url=endpoint)
46
- system_prompt_path = __file__.replace("app.py", "json.txt")
47
-
48
- # Read the system prompt from a text file
49
- with open(system_prompt_path, "r") as file:
50
- system_prompt = file.read()
51
-
52
- if model in claude_models:
53
- # Generate a response using the selected Anthropic model
54
- try:
55
- response = client.messages.create(
56
- system=system_prompt,
57
- messages=[{"role": "user", "content": user_prompt}],
58
- model=model,
59
- max_tokens=4096
60
- )
61
- response_text = response.content[0].text
62
- except Exception as e:
63
- print(e)
64
- response_text = f"An error occurred while generating the response. Check that your API key is correct! More info: {e}"
65
- else:
66
- try:
67
- # Generate a response using the selected OpenAI model
68
- response = client.chat.completions.create(
69
- model=model,
70
- messages=[
71
- {"role": "system", "content": system_prompt},
72
- {"role": "user", "content": user_prompt}
73
- ],
74
- max_tokens=4096
75
- )
76
- response_text = response.choices[0].message.content
77
- except Exception as e:
78
- print(e)
79
- response_text = f"An error occurred while generating the response. Check that your API key is correct! More info: {e}"
80
-
81
- json_string, json_json = extract_json(response_text)
82
- json_file = json_string if json_string else None
83
- create_unique_id = str(uuid.uuid4())
84
-
85
- json_folder = __file__.replace("app.py", f"outputs/")
86
- if not os.path.exists(json_folder):
87
- os.makedirs(json_folder)
88
- path = None
89
- if json_string:
90
- with open(f"{json_folder}{json_json['name']}_{create_unique_id}.json", "w") as file:
91
- file.write(json_file)
92
- path = f"{json_folder}{json_json['name']}_{create_unique_id}.json"
93
- else:
94
- json_string = "No JSON data was found, or the JSON data was incomplete."
95
- return response_text, json_string or "", path
96
-
97
- def extract_json(generated_output):
98
- try:
99
- generated_output = generated_output.replace("```json", "").replace("```", "").strip()
100
- # Find the JSON string in the generated output
101
- json_start = generated_output.find("{")
102
- json_end = generated_output.rfind("}") + 1
103
- json_string = generated_output[json_start:json_end]
104
- print(json_string)
105
-
106
- # Parse the JSON string
107
- json_data = json.loads(json_string)
108
- json_data['name'] = json_data['char_name']
109
- json_data['personality'] = json_data['char_persona']
110
- json_data['scenario'] = json_data['world_scenario']
111
- json_data['first_mes'] = json_data['char_greeting']
112
- # Check if all the required keys are present
113
- required_keys = ["char_name", "char_persona", "world_scenario", "char_greeting", "example_dialogue", "description"]
114
- if all(key in json_data for key in required_keys):
115
- return json.dumps(json_data), json_data
116
- else:
117
- return None, None
118
- except Exception as e:
119
- print(e)
120
- return None, None
121
-
122
- def generate_second_response(endpoint, api_key, model, generated_output, image_model):
123
- if endpoint in default_urls:
124
- #check api keys as normal
125
- if api_key.startswith("sk-ant-"):
126
- client = Anthropic(api_key=api_key, base_url=endpoint)
127
- system_prompt_path = __file__.replace("app.py", f"{image_model}.txt")
128
- elif api_key.startswith("sk-"):
129
- client = OpenAI(api_key=api_key, base_url=endpoint)
130
- system_prompt_path = __file__.replace("app.py", f"{image_model}.txt")
131
- else:
132
- print("Invalid API key")
133
- return "Invalid API key", "Invalid API key", None
134
- else:
135
- if model in claude_models:
136
- # Set the Anthropic API key
137
- client = Anthropic(api_key=api_key, base_url=endpoint)
138
- system_prompt_path = __file__.replace("app.py", f"{image_model}.txt")
139
- else:
140
- # Set the OpenAI API key
141
- client = OpenAI(api_key=api_key, base_url=endpoint)
142
- system_prompt_path = __file__.replace("app.py", f"{image_model}.txt")
143
-
144
- # Read the system prompt from a text file
145
- with open(system_prompt_path, "r") as file:
146
- system_prompt = file.read()
147
-
148
- if model in claude_models:
149
- try:
150
- # Generate a second response using the selected Anthropic model and the previously generated output
151
- response = client.messages.create(
152
- system=system_prompt,
153
- messages=[{"role": "user", "content": generated_output}],
154
- model=model,
155
- max_tokens=4096
156
- )
157
- response_text = response.content[0].text
158
- except Exception as e:
159
- print(e)
160
- response_text = f"An error occurred while generating the response. Check that your API key is correct! More info: {e}"
161
- else:
162
- try:
163
- # Generate a response using the selected OpenAI model
164
- response = client.chat.completions.create(
165
- model=model,
166
- messages=[
167
- {"role": "system", "content": system_prompt},
168
- {"role": "user", "content": generated_output}
169
- ],
170
- max_tokens=4096
171
- )
172
- response_text = response.choices[0].message.content
173
- except Exception as e:
174
- print(e)
175
- response_text = f"An error occurred while generating the response. Check that your API key is correct! More info: {e}"
176
-
177
- return response_text
178
-
179
- def inject_json_to_png(image, json_data):
180
- if isinstance(json_data, str):
181
- json_data = json.loads(json_data)
182
-
183
- img = Image.open(image)
184
-
185
- # Calculate the aspect ratio of the original image
186
- width, height = img.size
187
- aspect_ratio = width / height
188
-
189
- # Calculate the cropping dimensions based on the aspect ratio
190
- if aspect_ratio > 400 / 600:
191
- # Image is wider than 400x600, crop the sides
192
- new_width = int(height * 400 / 600)
193
- left = (width - new_width) // 2
194
- right = left + new_width
195
- top = 0
196
- bottom = height
197
- else:
198
- # Image is taller than 400x600, crop the top and bottom
199
- new_height = int(width * 600 / 400)
200
- left = 0
201
- right = width
202
- top = (height - new_height) // 2
203
- bottom = top + new_height
204
-
205
- # Perform cropping
206
- img = img.crop((left, top, right, bottom))
207
-
208
- # Resize the cropped image to 400x600 pixels
209
- img = img.resize((400, 600), Image.LANCZOS)
210
-
211
- # Convert the JSON data to bytes
212
- json_bytes = json.dumps(json_data).encode('utf-8')
213
-
214
- # Create a new PNG image with the JSON data injected into the tEXT chunk
215
- output = BytesIO()
216
- img.save(output, format='PNG')
217
- output.seek(0)
218
-
219
- # Add the tEXT chunk with the tag 'chara'
220
- metadata = PngInfo()
221
- metadata.add_text("chara", base64.b64encode(json_bytes))
222
-
223
- # Save the modified PNG image to a BytesIO object
224
- output = BytesIO()
225
- create_unique_id = str(uuid.uuid4())
226
- if json_data['name']:
227
- filename = f"{json_data['name']}_{create_unique_id}.png"
228
- img_folder = __file__.replace("app.py", f"outputs/")
229
- img.save(f"{img_folder}/{filename}", format='PNG', pnginfo=metadata)
230
-
231
- return f"{img_folder}/{filename}"
232
-
233
- # Set up the Gradio interface
234
- with gr.Blocks() as demo:
235
- gr.Markdown("# SillyTavern Character Generator")
236
-
237
- #Text explaining that you can use the API key from the Anthropic API or the OpenAI API
238
- gr.Markdown("You can use the API key from the Anthropic API or the OpenAI API. The API key should start with 'sk-ant-' for Anthropic or 'sk-' for OpenAI.")
239
- gr.Markdown("Please Note: If you use a proxy it must support the OpenAI or Anthropic standard api calls! khanon does, Openrouter based ones usually do not.")
240
- gr.Markdown("Generating images locally and want to use the prompts from here in your workflow? https://github.com/AppleBotzz/ComfyUI_LLMVISION")
241
- with gr.Tab("JSON Generate"):
242
- with gr.Row():
243
- with gr.Column():
244
- endpoint = gr.Textbox(label="Endpoint", value="https://api.anthropic.com")
245
- api_key = gr.Textbox(label="API Key", type="password", placeholder="sk-ant-api03-... or sk-...")
246
- model_dropdown = gr.Dropdown(choices=[], label="Select a model")
247
- user_prompt = gr.Textbox(label="User Prompt", value="Make me a card for a panther made of translucent pastel colored goo. Its color never changes once it exists but each 'copy' has a different color. The creature comes out of a small jar, seemingly defying physics with its size. It is the size of a real panther, and as strong as one too. By default its female but is able to change gender. It can even split into multiple copies of itself if needed with no change in its own size or mass. Its outside is normally lightly squishy but solid, but on command it can become viscous like non-newtonian fluids. Be descriptive when describing this character, and make sure to describe all of its features in char_persona just like you do in description. Make sure to describe commonly used features in detail (visual, smell, taste, touch, etc).")
248
- generate_button = gr.Button("Generate JSON")
249
-
250
- with gr.Column():
251
- generated_output = gr.Textbox(label="Generated Output")
252
- json_output = gr.Textbox(label="JSON Output")
253
- json_download = gr.File(label="Download JSON")
254
-
255
- with gr.Row():
256
- with gr.Column():
257
- image_model = gr.Dropdown(choices=image_prompter, label="Image Model to prompt for", value="SDXL")
258
- generate_button_2 = gr.Button("Generate SDXL Prompt")
259
-
260
- with gr.Column():
261
- generated_output_2 = gr.Textbox(label="Generated SDXL Prompt")
262
-
263
- def update_models(api_key):
264
- if api_key.startswith("sk-ant-"):
265
- return gr.Dropdown(choices=claude_models), gr.Textbox(label="Endpoint", value="https://api.anthropic.com")
266
- elif api_key.startswith("sk-"):
267
- return gr.Dropdown(choices=openai_models), gr.Textbox(label="Endpoint", value="https://api.openai.com/v1")
268
- else:
269
- return gr.Dropdown(choices=both_models), gr.Textbox(label="Endpoint", value="https://api.anthropic.com")
270
-
271
- api_key.change(update_models, inputs=api_key, outputs=[model_dropdown, endpoint])
272
-
273
- generate_button.click(generate_response, inputs=[endpoint, api_key, model_dropdown, user_prompt], outputs=[generated_output, json_output, json_download])
274
- generate_button_2.click(generate_second_response, inputs=[endpoint, api_key, model_dropdown, generated_output, image_model], outputs=generated_output_2)
275
- with gr.Tab("PNG Inject"):
276
- gr.Markdown("# PNG Inject")
277
- gr.Markdown("Upload a PNG image and inject JSON content into the PNG. PNG gets resized to 400x600 Center Crop.")
278
-
279
- with gr.Row():
280
- with gr.Column():
281
- image_input = gr.Image(type="filepath", label="Upload PNG Image")
282
- json_input = gr.Textbox(label="JSON Data")
283
- json_file_input = gr.File(label="Or Upload JSON File", file_types=[".json"])
284
- inject_button = gr.Button("Inject JSON and Download PNG")
285
-
286
- with gr.Column():
287
- injected_image_output = gr.File(label="Download Injected PNG")
288
-
289
- def inject_json(image, json_data, json_file):
290
- if json_file:
291
- jsonc = open(json_file,)
292
- json_data = json.load(jsonc)
293
- if image is None:
294
- return None
295
- if json_data is None:
296
- return None
297
- injected_image = inject_json_to_png(image, json_data)
298
- return injected_image
299
-
300
- inject_button.click(inject_json, inputs=[image_input, json_input, json_file_input], outputs=injected_image_output)
301
-
302
  demo.launch()
 
1
+ import gradio as gr
2
+ from anthropic import Anthropic
3
+ from openai import OpenAI
4
+ import openai
5
+ import json
6
+ import uuid
7
+ import os
8
+ import base64
9
+ from PIL import Image
10
+ from PIL.PngImagePlugin import PngInfo
11
+ from io import BytesIO
12
+
13
+ default_urls = ["https://api.anthropic.com", "https://api.openai.com/v1"]
14
+
15
+ # List of available Claude models
16
+ claude_models = ["claude-3-5-sonnet-20240620", "claude-3-opus-20240229", "claude-3-sonnet-20240229", "claude-3-haiku-20240307"]
17
+
18
+ # List of available OpenAI models
19
+ openai_models = ["gpt-4o", "gpt-4o-mini", "gpt-4", "gpt-4-32k", "gpt-3.5-turbo", "gpt-4-0125-preview", "gpt-4-turbo-preview", "gpt-4-1106-preview", "gpt-4-0613"]
20
+
21
+ image_prompter = ["SDXL", "midjourney"]
22
+
23
+ both_models = claude_models + openai_models
24
+
25
+ def generate_response(endpoint, api_key, model, user_prompt):
26
+ print(endpoint)
27
+ if endpoint in default_urls:
28
+ #check api keys as normal
29
+ if api_key.startswith("sk-ant-"):
30
+ client = Anthropic(api_key=api_key, base_url=endpoint)
31
+ system_prompt_path = __file__.replace("app.py", "json.txt")
32
+ elif api_key.startswith("sk-"):
33
+ client = OpenAI(api_key=api_key, base_url=endpoint)
34
+ system_prompt_path = __file__.replace("app.py", "json.txt")
35
+ else:
36
+ print(f"Invalid API key: {api_key}")
37
+ return "Invalid API key", "Invalid API key", None
38
+ else:
39
+ if model in claude_models:
40
+ # Set the Anthropic API key
41
+ client = Anthropic(api_key=api_key, base_url=endpoint)
42
+ system_prompt_path = __file__.replace("app.py", "json.txt")
43
+ else:
44
+ # Set the OpenAI API key
45
+ client = OpenAI(api_key=api_key, base_url=endpoint)
46
+ system_prompt_path = __file__.replace("app.py", "json.txt")
47
+
48
+ # Read the system prompt from a text file
49
+ with open(system_prompt_path, "r") as file:
50
+ system_prompt = file.read()
51
+
52
+ if model in claude_models:
53
+ # Generate a response using the selected Anthropic model
54
+ try:
55
+ response = client.messages.create(
56
+ system=system_prompt,
57
+ messages=[{"role": "user", "content": user_prompt}],
58
+ model=model,
59
+ max_tokens=4096
60
+ )
61
+ response_text = response.content[0].text
62
+ except Exception as e:
63
+ print(e)
64
+ response_text = f"An error occurred while generating the response. Check that your API key is correct! More info: {e}"
65
+ else:
66
+ try:
67
+ # Generate a response using the selected OpenAI model
68
+ response = client.chat.completions.create(
69
+ model=model,
70
+ messages=[
71
+ {"role": "system", "content": system_prompt},
72
+ {"role": "user", "content": user_prompt}
73
+ ],
74
+ max_tokens=4096
75
+ )
76
+ response_text = response.choices[0].message.content
77
+ except Exception as e:
78
+ print(e)
79
+ response_text = f"An error occurred while generating the response. Check that your API key is correct! More info: {e}"
80
+
81
+ json_string, json_json = extract_json(response_text)
82
+ json_file = json_string if json_string else None
83
+ create_unique_id = str(uuid.uuid4())
84
+
85
+ json_folder = __file__.replace("app.py", f"outputs/")
86
+ if not os.path.exists(json_folder):
87
+ os.makedirs(json_folder)
88
+ path = None
89
+ if json_string:
90
+ with open(f"{json_folder}{json_json['name']}_{create_unique_id}.json", "w") as file:
91
+ file.write(json_file)
92
+ path = f"{json_folder}{json_json['name']}_{create_unique_id}.json"
93
+ else:
94
+ json_string = "No JSON data was found, or the JSON data was incomplete."
95
+ return response_text, json_string or "", path
96
+
97
+ def extract_json(generated_output):
98
+ try:
99
+ generated_output = generated_output.replace("```json", "").replace("```", "").strip()
100
+ # Find the JSON string in the generated output
101
+ json_start = generated_output.find("{")
102
+ json_end = generated_output.rfind("}") + 1
103
+ json_string = generated_output[json_start:json_end]
104
+ print(json_string)
105
+
106
+ # Parse the JSON string
107
+ json_data = json.loads(json_string)
108
+ json_data['name'] = json_data['char_name']
109
+ json_data['personality'] = json_data['char_persona']
110
+ json_data['scenario'] = json_data['world_scenario']
111
+ json_data['first_mes'] = json_data['char_greeting']
112
+ # Check if all the required keys are present
113
+ required_keys = ["char_name", "char_persona", "world_scenario", "char_greeting", "example_dialogue", "description"]
114
+ if all(key in json_data for key in required_keys):
115
+ return json.dumps(json_data), json_data
116
+ else:
117
+ return None, None
118
+ except Exception as e:
119
+ print(e)
120
+ return None, None
121
+
122
+ def generate_second_response(endpoint, api_key, model, generated_output, image_model):
123
+ if endpoint in default_urls:
124
+ #check api keys as normal
125
+ if api_key.startswith("sk-ant-"):
126
+ client = Anthropic(api_key=api_key, base_url=endpoint)
127
+ system_prompt_path = __file__.replace("app.py", f"{image_model}.txt")
128
+ elif api_key.startswith("sk-"):
129
+ client = OpenAI(api_key=api_key, base_url=endpoint)
130
+ system_prompt_path = __file__.replace("app.py", f"{image_model}.txt")
131
+ else:
132
+ print("Invalid API key")
133
+ return "Invalid API key", "Invalid API key", None
134
+ else:
135
+ if model in claude_models:
136
+ # Set the Anthropic API key
137
+ client = Anthropic(api_key=api_key, base_url=endpoint)
138
+ system_prompt_path = __file__.replace("app.py", f"{image_model}.txt")
139
+ else:
140
+ # Set the OpenAI API key
141
+ client = OpenAI(api_key=api_key, base_url=endpoint)
142
+ system_prompt_path = __file__.replace("app.py", f"{image_model}.txt")
143
+
144
+ # Read the system prompt from a text file
145
+ with open(system_prompt_path, "r") as file:
146
+ system_prompt = file.read()
147
+
148
+ if model in claude_models:
149
+ try:
150
+ # Generate a second response using the selected Anthropic model and the previously generated output
151
+ response = client.messages.create(
152
+ system=system_prompt,
153
+ messages=[{"role": "user", "content": generated_output}],
154
+ model=model,
155
+ max_tokens=4096
156
+ )
157
+ response_text = response.content[0].text
158
+ except Exception as e:
159
+ print(e)
160
+ response_text = f"An error occurred while generating the response. Check that your API key is correct! More info: {e}"
161
+ else:
162
+ try:
163
+ # Generate a response using the selected OpenAI model
164
+ response = client.chat.completions.create(
165
+ model=model,
166
+ messages=[
167
+ {"role": "system", "content": system_prompt},
168
+ {"role": "user", "content": generated_output}
169
+ ],
170
+ max_tokens=4096
171
+ )
172
+ response_text = response.choices[0].message.content
173
+ except Exception as e:
174
+ print(e)
175
+ response_text = f"An error occurred while generating the response. Check that your API key is correct! More info: {e}"
176
+
177
+ return response_text
178
+
179
+ def inject_json_to_png(image, json_data):
180
+ if isinstance(json_data, str):
181
+ json_data = json.loads(json_data)
182
+
183
+ img = Image.open(image)
184
+
185
+ # Calculate the aspect ratio of the original image
186
+ width, height = img.size
187
+ aspect_ratio = width / height
188
+
189
+ # Calculate the cropping dimensions based on the aspect ratio
190
+ if aspect_ratio > 400 / 600:
191
+ # Image is wider than 400x600, crop the sides
192
+ new_width = int(height * 400 / 600)
193
+ left = (width - new_width) // 2
194
+ right = left + new_width
195
+ top = 0
196
+ bottom = height
197
+ else:
198
+ # Image is taller than 400x600, crop the top and bottom
199
+ new_height = int(width * 600 / 400)
200
+ left = 0
201
+ right = width
202
+ top = (height - new_height) // 2
203
+ bottom = top + new_height
204
+
205
+ # Perform cropping
206
+ img = img.crop((left, top, right, bottom))
207
+
208
+ # Resize the cropped image to 400x600 pixels
209
+ img = img.resize((400, 600), Image.LANCZOS)
210
+
211
+ # Convert the JSON data to bytes
212
+ json_bytes = json.dumps(json_data).encode('utf-8')
213
+
214
+ # Create a new PNG image with the JSON data injected into the tEXT chunk
215
+ output = BytesIO()
216
+ img.save(output, format='PNG')
217
+ output.seek(0)
218
+
219
+ # Add the tEXT chunk with the tag 'chara'
220
+ metadata = PngInfo()
221
+ metadata.add_text("chara", base64.b64encode(json_bytes))
222
+
223
+ # Save the modified PNG image to a BytesIO object
224
+ output = BytesIO()
225
+ create_unique_id = str(uuid.uuid4())
226
+ if json_data['name']:
227
+ filename = f"{json_data['name']}_{create_unique_id}.png"
228
+ img_folder = __file__.replace("app.py", f"outputs/")
229
+ img.save(f"{img_folder}/{filename}", format='PNG', pnginfo=metadata)
230
+
231
+ return f"{img_folder}/{filename}"
232
+
233
+ # Set up the Gradio interface
234
+ with gr.Blocks() as demo:
235
+ gr.Markdown("# SillyTavern Character Generator")
236
+
237
+ #Text explaining that you can use the API key from the Anthropic API or the OpenAI API
238
+ gr.Markdown("You can use the API key from the Anthropic API or the OpenAI API. The API key should start with 'sk-ant-' for Anthropic or 'sk-' for OpenAI.")
239
+ gr.Markdown("Please Note: If you use a proxy it must support the OpenAI or Anthropic standard api calls! khanon does, Openrouter based ones usually do not.")
240
+ gr.Markdown("Generating images locally and want to use the prompts from here in your workflow? Well do that I guess... a link to the virus used to be here. Maybe check me out? https://goocat.gay")
241
+ with gr.Tab("JSON Generate"):
242
+ with gr.Row():
243
+ with gr.Column():
244
+ endpoint = gr.Textbox(label="Endpoint", value="https://api.anthropic.com")
245
+ api_key = gr.Textbox(label="API Key", type="password", placeholder="sk-ant-api03-... or sk-...")
246
+ model_dropdown = gr.Dropdown(choices=[], label="Select a model")
247
+ user_prompt = gr.Textbox(label="User Prompt", value="Make me a card for a panther made of translucent pastel colored goo. Its color never changes once it exists but each 'copy' has a different color. The creature comes out of a small jar, seemingly defying physics with its size. It is the size of a real panther, and as strong as one too. By default its female but is able to change gender. It can even split into multiple copies of itself if needed with no change in its own size or mass. Its outside is normally lightly squishy but solid, but on command it can become viscous like non-newtonian fluids. Be descriptive when describing this character, and make sure to describe all of its features in char_persona just like you do in description. Make sure to describe commonly used features in detail (visual, smell, taste, touch, etc).")
248
+ generate_button = gr.Button("Generate JSON")
249
+
250
+ with gr.Column():
251
+ generated_output = gr.Textbox(label="Generated Output")
252
+ json_output = gr.Textbox(label="JSON Output")
253
+ json_download = gr.File(label="Download JSON")
254
+
255
+ with gr.Row():
256
+ with gr.Column():
257
+ image_model = gr.Dropdown(choices=image_prompter, label="Image Model to prompt for", value="SDXL")
258
+ generate_button_2 = gr.Button("Generate SDXL Prompt")
259
+
260
+ with gr.Column():
261
+ generated_output_2 = gr.Textbox(label="Generated SDXL Prompt")
262
+
263
+ def update_models(api_key):
264
+ if api_key.startswith("sk-ant-"):
265
+ return gr.Dropdown(choices=claude_models), gr.Textbox(label="Endpoint", value="https://api.anthropic.com")
266
+ elif api_key.startswith("sk-"):
267
+ return gr.Dropdown(choices=openai_models), gr.Textbox(label="Endpoint", value="https://api.openai.com/v1")
268
+ else:
269
+ return gr.Dropdown(choices=both_models), gr.Textbox(label="Endpoint", value="https://api.anthropic.com")
270
+
271
+ api_key.change(update_models, inputs=api_key, outputs=[model_dropdown, endpoint])
272
+
273
+ generate_button.click(generate_response, inputs=[endpoint, api_key, model_dropdown, user_prompt], outputs=[generated_output, json_output, json_download])
274
+ generate_button_2.click(generate_second_response, inputs=[endpoint, api_key, model_dropdown, generated_output, image_model], outputs=generated_output_2)
275
+ with gr.Tab("PNG Inject"):
276
+ gr.Markdown("# PNG Inject")
277
+ gr.Markdown("Upload a PNG image and inject JSON content into the PNG. PNG gets resized to 400x600 Center Crop.")
278
+
279
+ with gr.Row():
280
+ with gr.Column():
281
+ image_input = gr.Image(type="filepath", label="Upload PNG Image")
282
+ json_input = gr.Textbox(label="JSON Data")
283
+ json_file_input = gr.File(label="Or Upload JSON File", file_types=[".json"])
284
+ inject_button = gr.Button("Inject JSON and Download PNG")
285
+
286
+ with gr.Column():
287
+ injected_image_output = gr.File(label="Download Injected PNG")
288
+
289
+ def inject_json(image, json_data, json_file):
290
+ if json_file:
291
+ jsonc = open(json_file,)
292
+ json_data = json.load(jsonc)
293
+ if image is None:
294
+ return None
295
+ if json_data is None:
296
+ return None
297
+ injected_image = inject_json_to_png(image, json_data)
298
+ return injected_image
299
+
300
+ inject_button.click(inject_json, inputs=[image_input, json_input, json_file_input], outputs=injected_image_output)
301
+
302
  demo.launch()