heaversm commited on
Commit
318ea3e
1 Parent(s): 2d201f5

claude - dead end - only can read images not generate

Browse files
Files changed (3) hide show
  1. README.md +4 -4
  2. app.py +31 -120
  3. requirements.txt +3 -1
README.md CHANGED
@@ -1,8 +1,8 @@
1
  ---
2
- title: PDR Stable Diffusion
3
- emoji: 👁️
4
- colorFrom: yellow
5
- colorTo: red
6
  sdk: gradio
7
  sdk_version: 4.18.0
8
  app_file: app.py
 
1
  ---
2
+ title: PDR Claude
3
+ emoji: 🎩
4
+ colorFrom: indigo
5
+ colorTo: violet
6
  sdk: gradio
7
  sdk_version: 4.18.0
8
  app_file: app.py
app.py CHANGED
@@ -13,7 +13,7 @@ from PIL import Image
13
 
14
  # gradio / hf / image gen stuff
15
  import gradio as gr
16
- import replicate
17
  from dotenv import load_dotenv
18
 
19
  # stats stuff
@@ -21,13 +21,10 @@ from pymongo.mongo_client import MongoClient
21
  from pymongo.server_api import ServerApi
22
  import time
23
 
24
- # countdown stuff
25
- from datetime import datetime, timedelta
26
-
27
 
28
  load_dotenv()
29
 
30
- REPLICATE_API_TOKEN = os.getenv("REPLICATE_API_TOKEN")
31
 
32
  pw_key = os.getenv("PW")
33
 
@@ -37,9 +34,12 @@ if pw_key == "<YOUR_PW>":
37
  if pw_key == "":
38
  sys.exit("Please Provide A Password in the Environment Variables")
39
 
40
- if REPLICATE_API_TOKEN == "":
41
  sys.exit("Please Provide Your API Key")
42
 
 
 
 
43
  # Connect to MongoDB
44
  uri = os.getenv("MONGO_URI")
45
  mongo_client = MongoClient(uri, server_api=ServerApi('1'))
@@ -69,9 +69,9 @@ def update_labels(show_labels):
69
  updated_gallery = [(path, label if show_labels else "") for path, label in zip(image_paths_global, image_labels_global)]
70
  return updated_gallery
71
 
72
- def generate_images_wrapper(prompts, pw, model, show_labels,size, guidance, steps, scheduler):
73
  global image_paths_global, image_labels_global
74
- image_paths, image_labels = generate_images(prompts, pw, model,size,guidance,steps,scheduler)
75
  image_paths_global = image_paths
76
 
77
  # store this as a global so we can handle toggle state
@@ -108,7 +108,7 @@ def download_all_images():
108
  image_labels_global = [] # Reset the global variable
109
  return zip_path
110
 
111
- def generate_images(prompts, pw, model,size,guidance,steps,scheduler):
112
  # Check for a valid password
113
 
114
  if pw != os.getenv("PW"):
@@ -121,6 +121,8 @@ def generate_images(prompts, pw, model,size,guidance,steps,scheduler):
121
  # Split the prompts string into individual prompts based on semicolon separation
122
  prompts_list = [prompt for prompt in prompts.split(';') if prompt]
123
 
 
 
124
  for i, entry in enumerate(prompts_list):
125
  entry_parts = entry.split('-', 1) # Split by the first dash found
126
  if len(entry_parts) == 2:
@@ -132,85 +134,21 @@ def generate_images(prompts, pw, model,size,guidance,steps,scheduler):
132
 
133
  users.append(user_initials) # Append user initials to the list
134
 
135
- try:
136
- #openai_client = OpenAI(api_key=openai_key)
137
- start_time = time.time()
138
-
139
- #make a prompt with the challenge and text
140
- prompt_w_challenge = f"{challenge}: {text}"
141
-
142
- # stable diffusion
143
- response = replicate.run(
144
- "stability-ai/stable-diffusion:ac732df83cea7fff18b8472768c88ad041fa750ff7682a21affe81863cbe77e4",
145
- input={
146
- "width": int(size), #must be multiples of 64
147
- "height": int(size),
148
- "prompt": prompt_w_challenge,
149
- "scheduler": scheduler, #controlling the steps of the diffusion process to balance between image quality, generation speed, and resource consumption - DDIM, K_EULER, DPMSolverMultistep, K_EULER_ANCESTRAL, PNDM, KLMS
150
- "num_outputs": 1, #images to generate
151
- "guidance_scale": int(guidance), #0-20, higher the number, more it sticks to the prompt
152
- "num_inference_steps": int(steps) #1-500 - higher the better, generally
153
  }
154
- )
155
- print(response)
156
-
157
- end_time = time.time()
158
- gen_time = end_time - start_time # total generation time
159
-
160
- #image_url = response.data[0].url
161
- image_url = response[0]
162
-
163
- # conditionally render the user to the label with the prompt
164
- image_label = f"{i}: {text}" if user_initials == "" else f"{i}: {user_initials}-{text}, "
165
-
166
- try:
167
- # Save the prompt, model, image URL, generation time and creation timestamp to the database
168
- mongo_collection.insert_one({"user": user_initials, "text": text, "model": model, "image_url": image_url, "gen_time": gen_time, "timestamp": time.time()})
169
- except Exception as e:
170
- print(e)
171
- raise gr.Error("An error occurred while saving the prompt to the database.")
172
-
173
- # Append the image URL and label to their respective lists
174
- image_paths.append(image_url)
175
- image_labels.append(image_label)
176
-
177
- except Exception as e:
178
- print(e)
179
- raise gr.Error(f"An error occurred while generating the image for: {entry}")
180
-
181
- return image_paths, image_labels # Return both image paths and labels
182
-
183
-
184
- #timer stuff
185
- timer_cancelled_global = False # when true, timer does not tick down
186
-
187
- def countdown(seconds):
188
- """
189
- This function takes the number of seconds as input and returns a string displaying the remaining time.
190
- """
191
- target_time = datetime.now() + timedelta(seconds=int(seconds))
192
- while target_time > datetime.now():
193
- remaining_time = target_time - datetime.now()
194
- remaining_seconds = int(remaining_time.total_seconds())
195
- yield f"{remaining_seconds:02d}"
196
- # Check if the countdown was cancelled
197
- if timer_cancelled_global:
198
- break
199
-
200
- def stop_countdown():
201
- """
202
- This function stops the countdown.
203
- """
204
- global timer_cancelled_global
205
- timer_cancelled_global = True
206
-
207
- def reset_countdown(slider):
208
- """
209
- This function resets the countdown.
210
- """
211
- global timer_cancelled_global
212
- timer_cancelled_global = False
213
- return 60
214
 
215
 
216
  #custom css
@@ -223,9 +161,9 @@ css = """
223
 
224
  with gr.Blocks(css=css) as demo:
225
 
226
- gr.Markdown("# <center>Prompt de Resistance Stable Diffusion</center>")
227
 
228
- pw = gr.Textbox(label="Password", type="password", placeholder="Enter the password to unlock the service")
229
 
230
  #instructions
231
  with gr.Accordion("Instructions & Tips",label="instructions",open=False):
@@ -239,32 +177,10 @@ with gr.Blocks(css=css) as demo:
239
  regenerate_btn = gr.Button("New Challenge")
240
 
241
 
242
- #countdown
243
- with gr.Accordion("Countdown",label="Countdown",open=False):
244
- with gr.Row():
245
- with gr.Column(scale=3):
246
- slider = gr.Slider(minimum=1, maximum=120, value=60,label="Countdown",info="Select duration in seconds")
247
- with gr.Column(scale=1):
248
- countdown_button = gr.Button("Start")
249
- stop_countdown_button = gr.Button("Stop")
250
- reset_countdown_button = gr.Button("Reset")
251
-
252
-
253
  #prompts
254
  with gr.Accordion("Prompts",label="Prompts",open=True):
255
- with gr.Row():
256
- with gr.Column(scale=3):
257
- text = gr.Textbox(label="What do you want to create?", placeholder="Enter your text and then click on the \"Image Generate\" button")
258
- with gr.Column(scale=1):
259
- model = gr.Dropdown(choices=["stable-diffusion"], label="Model", value="stable-diffusion")
260
- with gr.Row():
261
- with gr.Column():
262
- size = gr.Dropdown(choices=[512,768,1024], label="Size", value=768)
263
- scheduler = gr.Dropdown(choices=["DDIM", "K_EULER", "DPMSolverMultistep", "K_EULER_ANCESTRAL", "PNDM", "KLMS"], label="Scheduler", value="K_EULER", info="attempt to balance between image quality, generation speed, and resource consumption")
264
- with gr.Column():
265
- guidance = gr.Slider(minimum=0, maximum=20, value=7, step=1,label="Guidance",info="0-20, higher the number, more it sticks to the prompt")
266
- steps = gr.Slider(minimum=10, maximum=500, value=50, step=10,label="Steps",info="10-500 - higher = better quality, lower = faster")
267
- with gr.Row():
268
  btn = gr.Button("Generate Images")
269
 
270
  #output
@@ -280,15 +196,10 @@ with gr.Blocks(css=css) as demo:
280
  # generate new challenge
281
  regenerate_btn.click(fn=get_challenge, inputs=[], outputs=[challenge_display])
282
 
283
- #countdown
284
- countdown_button.click(fn=countdown, inputs=[slider], outputs=[slider])
285
- stop_countdown_button.click(fn=stop_countdown)
286
- reset_countdown_button.click(fn=reset_countdown,inputs=[slider],outputs=[slider])
287
-
288
  #submissions
289
  #trigger generation either through hitting enter in the text field, or clicking the button.
290
- btn.click(fn=generate_images_wrapper, inputs=[text, pw, model, show_labels, size, guidance, steps, scheduler ], outputs=output_images, api_name=False)
291
- text.submit(fn=generate_images_wrapper, inputs=[text, pw, model, show_labels, size, guidance, steps, scheduler], outputs=output_images, api_name="generate_image") # Generate an api endpoint in Gradio / HF
292
  show_labels.change(fn=update_labels, inputs=[show_labels], outputs=[output_images])
293
 
294
  #downloads
 
13
 
14
  # gradio / hf / image gen stuff
15
  import gradio as gr
16
+ import anthropic
17
  from dotenv import load_dotenv
18
 
19
  # stats stuff
 
21
  from pymongo.server_api import ServerApi
22
  import time
23
 
 
 
 
24
 
25
  load_dotenv()
26
 
27
+ ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
28
 
29
  pw_key = os.getenv("PW")
30
 
 
34
  if pw_key == "":
35
  sys.exit("Please Provide A Password in the Environment Variables")
36
 
37
+ if ANTHROPIC_API_KEY == "":
38
  sys.exit("Please Provide Your API Key")
39
 
40
+ client = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)
41
+ print(client)
42
+
43
  # Connect to MongoDB
44
  uri = os.getenv("MONGO_URI")
45
  mongo_client = MongoClient(uri, server_api=ServerApi('1'))
 
69
  updated_gallery = [(path, label if show_labels else "") for path, label in zip(image_paths_global, image_labels_global)]
70
  return updated_gallery
71
 
72
+ def generate_images_wrapper(prompts, pw, show_labels):
73
  global image_paths_global, image_labels_global
74
+ image_paths, image_labels = generate_images(prompts, pw)
75
  image_paths_global = image_paths
76
 
77
  # store this as a global so we can handle toggle state
 
108
  image_labels_global = [] # Reset the global variable
109
  return zip_path
110
 
111
+ def generate_images(prompts, pw):
112
  # Check for a valid password
113
 
114
  if pw != os.getenv("PW"):
 
121
  # Split the prompts string into individual prompts based on semicolon separation
122
  prompts_list = [prompt for prompt in prompts.split(';') if prompt]
123
 
124
+ model = "claude-3-opus-20240229"
125
+
126
  for i, entry in enumerate(prompts_list):
127
  entry_parts = entry.split('-', 1) # Split by the first dash found
128
  if len(entry_parts) == 2:
 
134
 
135
  users.append(user_initials) # Append user initials to the list
136
 
137
+ prompt_w_challenge = f"{challenge}: {text}"
138
+ print(prompt_w_challenge)
139
+
140
+ response = client.messages.create(
141
+ max_tokens=1024,
142
+ messages=[
143
+ {
144
+ "role": "user",
145
+ "content": f"Generate an image that depicts the following prompt: {prompt_w_challenge}"
 
 
 
 
 
 
 
 
 
146
  }
147
+ ],
148
+ model=model,
149
+ )
150
+ print(response.content)
151
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
 
153
 
154
  #custom css
 
161
 
162
  with gr.Blocks(css=css) as demo:
163
 
164
+ gr.Markdown("# <center>Prompt de Resistance Claude 3</center>")
165
 
166
+ pw = gr.Textbox(label="Password", type="password", placeholder="Enter the password to unlock the service", value="REBEL.pier6moment")
167
 
168
  #instructions
169
  with gr.Accordion("Instructions & Tips",label="instructions",open=False):
 
177
  regenerate_btn = gr.Button("New Challenge")
178
 
179
 
 
 
 
 
 
 
 
 
 
 
 
180
  #prompts
181
  with gr.Accordion("Prompts",label="Prompts",open=True):
182
+ text = gr.Textbox(label="What do you want to create?", placeholder="Enter your text and then click on the \"Image Generate\" button")
183
+ with gr.Row():
 
 
 
 
 
 
 
 
 
 
 
184
  btn = gr.Button("Generate Images")
185
 
186
  #output
 
196
  # generate new challenge
197
  regenerate_btn.click(fn=get_challenge, inputs=[], outputs=[challenge_display])
198
 
 
 
 
 
 
199
  #submissions
200
  #trigger generation either through hitting enter in the text field, or clicking the button.
201
+ btn.click(fn=generate_images_wrapper, inputs=[text, pw, show_labels ], outputs=output_images, api_name=False)
202
+ text.submit(fn=generate_images_wrapper, inputs=[text, pw, show_labels], outputs=output_images, api_name="generate_image") # Generate an api endpoint in Gradio / HF
203
  show_labels.change(fn=update_labels, inputs=[show_labels], outputs=[output_images])
204
 
205
  #downloads
requirements.txt CHANGED
@@ -2,4 +2,6 @@ gradio==4.2.0
2
  openai==1.2.3
3
  python-dotenv==1.0.0
4
  pymongo
5
- replicate==0.24.0
 
 
 
2
  openai==1.2.3
3
  python-dotenv==1.0.0
4
  pymongo
5
+ replicate==0.24.0
6
+ anthropic==0.18.1
7
+ tokenizers==0.15.2