JarvisLabs commited on
Commit
564ac48
·
verified ·
1 Parent(s): 34492bf

Upload 2 files

Browse files
Files changed (2) hide show
  1. src/rep_api.py +298 -213
  2. src/utils.py +138 -100
src/rep_api.py CHANGED
@@ -1,213 +1,298 @@
1
- import replicate
2
- import os
3
- from src.utils import image_to_base64 , update_model_dicts, BB_uploadfile,numpy_to_base64
4
- from src.deepl import detect_and_translate
5
- import json
6
- import time
7
- style_json="model_dict.json"
8
- model_dict=json.load(open(style_json,"r"))
9
-
10
-
11
-
12
- def generate_image_replicate(prompt,lora_model,api_path,aspect_ratio,gallery,model,lora_scale,num_outputs=1,guidance_scale=3.5,seed=None):
13
- print(prompt,lora_model,api_path,aspect_ratio)
14
-
15
- #if model=="dev":
16
- num_inference_steps=30
17
- if model=="schnell":
18
- num_inference_steps=5
19
-
20
- if lora_model is not None:
21
- api_path=model_dict[lora_model]
22
-
23
- inputs={
24
- "model": model,
25
- "prompt": detect_and_translate(prompt),
26
- "lora_scale":lora_scale,
27
- "aspect_ratio": aspect_ratio,
28
- "num_outputs":num_outputs,
29
- "num_inference_steps":num_inference_steps,
30
- "guidance_scale":guidance_scale,
31
- "output_format":"png",
32
- }
33
- if seed is not None:
34
- inputs["seed"]=seed
35
- output = replicate.run(
36
- api_path,
37
- input=inputs
38
- )
39
- print(output)
40
- if gallery is None:
41
- gallery=[]
42
- gallery.append(output[0])
43
- return output[0],gallery
44
-
45
-
46
- def replicate_caption_api(image,model,context_text):
47
- base64_image = image_to_base64(image)
48
- if model=="blip":
49
- output = replicate.run(
50
- "andreasjansson/blip-2:f677695e5e89f8b236e52ecd1d3f01beb44c34606419bcc19345e046d8f786f9",
51
- input={
52
- "image": base64_image,
53
- "caption": True,
54
- "question": context_text,
55
- "temperature": 1,
56
- "use_nucleus_sampling": False
57
- }
58
- )
59
- print(output)
60
-
61
- elif model=="llava-16":
62
- output = replicate.run(
63
- # "yorickvp/llava-13b:80537f9eead1a5bfa72d5ac6ea6414379be41d4d4f6679fd776e9535d1eb58bb",
64
- "yorickvp/llava-v1.6-34b:41ecfbfb261e6c1adf3ad896c9066ca98346996d7c4045c5bc944a79d430f174",
65
- input={
66
- "image": base64_image,
67
- "top_p": 1,
68
- "prompt": context_text,
69
- "max_tokens": 1024,
70
- "temperature": 0.2
71
- }
72
- )
73
- print(output)
74
- output = "".join(output)
75
-
76
- elif model=="img2prompt":
77
- output = replicate.run(
78
- "methexis-inc/img2prompt:50adaf2d3ad20a6f911a8a9e3ccf777b263b8596fbd2c8fc26e8888f8a0edbb5",
79
- input={
80
- "image":base64_image
81
- }
82
- )
83
- print(output)
84
- return output
85
-
86
- def update_replicate_api_key(api_key):
87
- os.environ["REPLICATE_API_TOKEN"] = api_key
88
- return f"Replicate API key updated: {api_key[:5]}..." if api_key else "Replicate API key cleared"
89
-
90
-
91
- def virtual_try_on(crop, seed, steps, category, garm_img, human_img, garment_des):
92
- output = replicate.run(
93
- "cuuupid/idm-vton:906425dbca90663ff5427624839572cc56ea7d380343d13e2a4c4b09d3f0c30f",
94
- input={
95
- "crop": crop,
96
- "seed": seed,
97
- "steps": steps,
98
- "category": category,
99
- # "force_dc": force_dc,
100
- "garm_img": numpy_to_base64( garm_img),
101
- "human_img": numpy_to_base64(human_img),
102
- #"mask_only": mask_only,
103
- "garment_des": garment_des
104
- }
105
- )
106
- print(output)
107
- return output
108
-
109
-
110
- from src.utils import create_zip
111
- from PIL import Image
112
-
113
-
114
- def process_images(files,model,context_text,token_string):
115
- images = []
116
- textbox =""
117
- for file in files:
118
- print(file)
119
- image = Image.open(file)
120
- if model=="None":
121
- caption="[Insert cap here]"
122
- else:
123
- caption = replicate_caption_api(image,model,context_text)
124
- textbox += f"Tags: {caption}, file: " + os.path.basename(file) + "\n"
125
- images.append(image)
126
- #texts.append(textbox)
127
- zip_path=create_zip(files,textbox,token_string)
128
-
129
- return images, textbox,zip_path
130
-
131
- def replicate_create_model(owner,name,visibility="private",hardware="gpu-a40-large"):
132
- try:
133
- model = replicate.models.create(
134
- owner=owner,
135
- name=name,
136
- visibility=visibility,
137
- hardware=hardware,
138
- )
139
- print(model)
140
- return True
141
- except Exception as e:
142
- print(e)
143
- if "A model with that name and owner already exists" in str(e):
144
- return True
145
- return False
146
-
147
-
148
-
149
- def traning_function(zip_path,training_model,training_destination,seed,token_string,max_train_steps,hf_repo_id=None,hf_token=None):
150
- ##Place holder for now
151
- BB_bucket_name="jarvisdataset"
152
- BB_defult="https://f005.backblazeb2.com/file/"
153
- if BB_defult not in zip_path:
154
- zip_path=BB_uploadfile(zip_path,os.path.basename(zip_path),BB_bucket_name)
155
- print(zip_path)
156
- training_logs = f"Using zip traning file at: {zip_path}\n"
157
- yield training_logs, None
158
- input={
159
- "steps": max_train_steps,
160
- "lora_rank": 16,
161
- "batch_size": 1,
162
- "autocaption": True,
163
- "trigger_word": token_string,
164
- "learning_rate": 0.0004,
165
- "seed": seed,
166
- "input_images": zip_path
167
- }
168
- print(training_destination)
169
- username,model_name=training_destination.split("/")
170
- assert replicate_create_model(username,model_name,visibility="private",hardware="gpu-a40-large"),"Error in creating model on replicate, check API key and username is correct "
171
-
172
- print(input)
173
- try:
174
- training = replicate.trainings.create(
175
- destination=training_destination,
176
- version="ostris/flux-dev-lora-trainer:1296f0ab2d695af5a1b5eeee6e8ec043145bef33f1675ce1a2cdb0f81ec43f02",
177
- input=input,
178
- )
179
-
180
- training_logs = f"Training started with model: {training_model}\n"
181
- training_logs += f"Destination: {training_destination}\n"
182
- training_logs += f"Seed: {seed}\n"
183
- training_logs += f"Token string: {token_string}\n"
184
- training_logs += f"Max train steps: {max_train_steps}\n"
185
-
186
- # Poll the training status
187
- while training.status != "succeeded":
188
- training.reload()
189
- training_logs += f"Training status: {training.status}\n"
190
- training_logs += f"{training.logs}\n"
191
- if training.status == "failed":
192
- training_logs += "Training failed!\n"
193
- return training_logs, training
194
-
195
- yield training_logs, None
196
- time.sleep(10) # Wait for 10 seconds before checking again
197
-
198
- training_logs += "Training completed!\n"
199
- if hf_repo_id and hf_token:
200
- training_logs += f"Uploading to Hugging Face repo: {hf_repo_id}\n"
201
- # Here you would implement the logic to upload to Hugging Face
202
-
203
- traning_finnal=training.output
204
-
205
- # In a real scenario, you might want to download and display some result images
206
- # For now, we'll just return the original images
207
- #images = [Image.open(file) for file in files]
208
- _= update_model_dicts(traning_finnal["version"],token_string,style_json="model_dict.json")
209
- traning_finnal["replicate_link"]="https://replicate.com/"+traning_finnal["version"].replace(":","/")
210
- yield training_logs, traning_finnal
211
-
212
- except Exception as e:
213
- yield f"An error occurred: {str(e)}", None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import replicate
2
+ import os
3
+ from src.utils import image_to_base64 , update_model_dicts, BB_uploadfile,numpy_to_base64
4
+ from src.deepl import detect_and_translate
5
+ import json
6
+ import time
7
+ style_json="model_dict.json"
8
+ model_dict=json.load(open(style_json,"r"))
9
+
10
+
11
+ def generate_image_control_net(prompt,lora_model,api_path,aspect_ratio,lora_scale,
12
+ use_control_net,control_net_type,control_net_img,control_net_strength,
13
+ num_outputs=1,guidance_scale=3.5,seed=None,
14
+ ):
15
+ print(prompt,lora_model,api_path,aspect_ratio,use_control_net)
16
+ inputs = {
17
+ "prompt": detect_and_translate(prompt),
18
+ "output_format": "png",
19
+ "num_outputs":num_outputs,
20
+ "guidance_scale": guidance_scale,
21
+ "output_quality": 100,
22
+ }
23
+ if seed is not None:
24
+ inputs["seed"]=seed
25
+
26
+
27
+ if use_control_net:
28
+ api_path= "xlabs-ai/flux-dev-controlnet:f2c31c31d81278a91b2447a304dae654c64a5d5a70340fba811bb1cbd41019a2" #X labs control net replicate repo
29
+ lora_url=model_dict[lora_model][1]
30
+ assert control_net_img is not None, "Please add control net image"
31
+ control_net_img=image_to_base64(control_net_img)
32
+ inputs["lora_url"]=lora_url
33
+ inputs["prompt"]+=", "+model_dict[lora_model][2]
34
+ inputs["control_image"]=control_net_img
35
+ inputs["control_type"]=control_net_type
36
+ inputs["control_strengh"]=control_net_strength
37
+ #other settings
38
+ inputs["steps"]=30
39
+ inputs["lora_strength"]=lora_scale
40
+ inputs["negative_prompt"]= "low quality, ugly, distorted, artefacts"
41
+ else:
42
+ api_path=model_dict[lora_model][0]
43
+ inputs["aspect_ratio"]=aspect_ratio
44
+ inputs["prompt"]+=", "+model_dict[lora_model][2]
45
+ inputs["num_inference_steps"]=28
46
+ inputs["model"]="dev"
47
+ inputs["lora_scale"]=lora_scale
48
+
49
+ #run model
50
+ output = replicate.run(
51
+ api_path,
52
+ input=inputs
53
+ )
54
+ print(output)
55
+ return output[0]
56
+
57
+
58
+
59
+
60
+ def generate_image_replicate(prompt,lora_model,api_path,aspect_ratio,model,lora_scale,
61
+ num_outputs=1,guidance_scale=3.5,seed=None,
62
+
63
+ ):
64
+ print(prompt,lora_model,api_path,aspect_ratio)
65
+
66
+ #if model=="dev":
67
+ num_inference_steps=30
68
+ if model=="schnell":
69
+ num_inference_steps=5
70
+
71
+ if lora_model is not None:
72
+ api_path=model_dict[lora_model][0]
73
+
74
+ inputs={
75
+ "model": model,
76
+ "prompt": detect_and_translate(prompt),
77
+ "lora_scale":lora_scale,
78
+ "aspect_ratio": aspect_ratio,
79
+ "num_outputs":num_outputs,
80
+ "num_inference_steps":num_inference_steps,
81
+ "guidance_scale":guidance_scale,
82
+ "output_format":"png",
83
+ }
84
+ if seed is not None:
85
+ inputs["seed"]=seed
86
+ output = replicate.run(
87
+ api_path,
88
+ input=inputs
89
+ )
90
+ print(output)
91
+ return output[0]
92
+
93
+
94
+ def replicate_caption_api(image,model,context_text):
95
+ base64_image = image_to_base64(image)
96
+ if model=="blip":
97
+ output = replicate.run(
98
+ "andreasjansson/blip-2:f677695e5e89f8b236e52ecd1d3f01beb44c34606419bcc19345e046d8f786f9",
99
+ input={
100
+ "image": base64_image,
101
+ "caption": True,
102
+ "question": context_text,
103
+ "temperature": 1,
104
+ "use_nucleus_sampling": False
105
+ }
106
+ )
107
+ print(output)
108
+
109
+ elif model=="llava-16":
110
+ output = replicate.run(
111
+ # "yorickvp/llava-13b:80537f9eead1a5bfa72d5ac6ea6414379be41d4d4f6679fd776e9535d1eb58bb",
112
+ "yorickvp/llava-v1.6-34b:41ecfbfb261e6c1adf3ad896c9066ca98346996d7c4045c5bc944a79d430f174",
113
+ input={
114
+ "image": base64_image,
115
+ "top_p": 1,
116
+ "prompt": context_text,
117
+ "max_tokens": 1024,
118
+ "temperature": 0.2
119
+ }
120
+ )
121
+ print(output)
122
+ output = "".join(output)
123
+
124
+ elif model=="img2prompt":
125
+ output = replicate.run(
126
+ "methexis-inc/img2prompt:50adaf2d3ad20a6f911a8a9e3ccf777b263b8596fbd2c8fc26e8888f8a0edbb5",
127
+ input={
128
+ "image":base64_image
129
+ }
130
+ )
131
+ print(output)
132
+ return output
133
+
134
+ def update_replicate_api_key(api_key):
135
+ os.environ["REPLICATE_API_TOKEN"] = api_key
136
+ return f"Replicate API key updated: {api_key[:5]}..." if api_key else "Replicate API key cleared"
137
+
138
+
139
+ def virtual_try_on(crop, seed, steps, category, garm_img, human_img, garment_des):
140
+ output = replicate.run(
141
+ "cuuupid/idm-vton:906425dbca90663ff5427624839572cc56ea7d380343d13e2a4c4b09d3f0c30f",
142
+ input={
143
+ "crop": crop,
144
+ "seed": seed,
145
+ "steps": steps,
146
+ "category": category,
147
+ # "force_dc": force_dc,
148
+ "garm_img": numpy_to_base64( garm_img),
149
+ "human_img": numpy_to_base64(human_img),
150
+ #"mask_only": mask_only,
151
+ "garment_des": garment_des
152
+ }
153
+ )
154
+ print(output)
155
+ return output
156
+
157
+
158
+ from src.utils import create_zip
159
+ from PIL import Image
160
+
161
+
162
+ def process_images(files,model,context_text,token_string):
163
+ images = []
164
+ textbox =""
165
+ for file in files:
166
+ print(file)
167
+ image = Image.open(file)
168
+ if model=="None":
169
+ caption="[Insert cap here]"
170
+ else:
171
+ caption = replicate_caption_api(image,model,context_text)
172
+ textbox += f"Tags: {caption}, file: " + os.path.basename(file) + "\n"
173
+ images.append(image)
174
+ #texts.append(textbox)
175
+ zip_path=create_zip(files,textbox,token_string)
176
+
177
+ return images, textbox,zip_path
178
+
179
+ def replicate_create_model(owner,name,visibility="private",hardware="gpu-a40-large"):
180
+ try:
181
+ model = replicate.models.create(
182
+ owner=owner,
183
+ name=name,
184
+ visibility=visibility,
185
+ hardware=hardware,
186
+ )
187
+ print(model)
188
+ return True
189
+ except Exception as e:
190
+ print(e)
191
+ if "A model with that name and owner already exists" in str(e):
192
+ return True
193
+ return False
194
+
195
+
196
+
197
+ def traning_function(zip_path,training_model,training_destination,seed,token_string,max_train_steps,hf_repo_id=None,hf_token=None):
198
+ ##Place holder for now
199
+ BB_bucket_name="jarvisdataset"
200
+ BB_defult="https://f005.backblazeb2.com/file/"
201
+ if BB_defult not in zip_path:
202
+ zip_path=BB_uploadfile(zip_path,os.path.basename(zip_path),BB_bucket_name)
203
+ print(zip_path)
204
+ training_logs = f"Using zip traning file at: {zip_path}\n"
205
+ yield training_logs, None
206
+ input={
207
+ "steps": max_train_steps,
208
+ "lora_rank": 16,
209
+ "batch_size": 1,
210
+ "autocaption": True,
211
+ "trigger_word": token_string,
212
+ "learning_rate": 0.0004,
213
+ "seed": seed,
214
+ "input_images": zip_path
215
+ }
216
+ print(training_destination)
217
+ username,model_name=training_destination.split("/")
218
+ assert replicate_create_model(username,model_name,visibility="private",hardware="gpu-a40-large"),"Error in creating model on replicate, check API key and username is correct "
219
+
220
+ print(input)
221
+ try:
222
+ training = replicate.trainings.create(
223
+ destination=training_destination,
224
+ version="ostris/flux-dev-lora-trainer:1296f0ab2d695af5a1b5eeee6e8ec043145bef33f1675ce1a2cdb0f81ec43f02",
225
+ input=input,
226
+ )
227
+
228
+ training_logs = f"Training started with model: {training_model}\n"
229
+ training_logs += f"Destination: {training_destination}\n"
230
+ training_logs += f"Seed: {seed}\n"
231
+ training_logs += f"Token string: {token_string}\n"
232
+ training_logs += f"Max train steps: {max_train_steps}\n"
233
+
234
+ # Poll the training status
235
+ while training.status != "succeeded":
236
+ training.reload()
237
+ training_logs += f"Training status: {training.status}\n"
238
+ training_logs += f"{training.logs}\n"
239
+ if training.status == "failed":
240
+ training_logs += "Training failed!\n"
241
+ return training_logs, training
242
+
243
+ yield training_logs, None
244
+ time.sleep(10) # Wait for 10 seconds before checking again
245
+
246
+ training_logs += "Training completed!\n"
247
+ if hf_repo_id and hf_token:
248
+ training_logs += f"Uploading to Hugging Face repo: {hf_repo_id}\n"
249
+ # Here you would implement the logic to upload to Hugging Face
250
+
251
+ traning_finnal=training.output
252
+
253
+ # In a real scenario, you might want to download and display some result images
254
+ # For now, we'll just return the original images
255
+ #images = [Image.open(file) for file in files]
256
+ _= update_model_dicts(traning_finnal["version"],token_string,style_json="model_dict.json")
257
+ traning_finnal["replicate_link"]="https://replicate.com/"+traning_finnal["version"].replace(":","/")
258
+ yield training_logs, traning_finnal
259
+
260
+ except Exception as e:
261
+ yield f"An error occurred: {str(e)}", None
262
+
263
+
264
+ def sam_segment(image,prompt,negative_prompt,adjustment_factor=-15):
265
+ #img2 base64
266
+ image = image_to_base64(image)
267
+ output = replicate.run(
268
+ "schananas/grounded_sam:ee871c19efb1941f55f66a3d7d960428c8a5afcb77449547fe8e5a3ab9ebc21c",
269
+ input={
270
+ "image": image,
271
+ "mask_prompt": prompt,
272
+ "adjustment_factor": adjustment_factor,
273
+ "negative_mask_prompt":negative_prompt
274
+ }
275
+ )
276
+ out_items={}
277
+ for item in output:
278
+ # https://replicate.com/schananas/grounded_sam/api#output-schema
279
+ print(item)
280
+ out_items[os.path.basename(item).split(".")[0]]=item
281
+ return out_items
282
+
283
+
284
+ def replicate_zest(img,material_img="https://replicate.delivery/pbxt/Kl23gJODaW7EuxrDzBG9dcgqRdMaYSWmBQ9UexnwPiL7AnIr/3.jpg"):
285
+ if type(img)!=str:
286
+ img=image_to_base64(img)
287
+ if type(material_img)!=str:
288
+ material_img=image_to_base64(material_img)
289
+
290
+ output = replicate.run(
291
+ "camenduru/zest:11abc0a411459327938957581151c642dd1bee4cefe443a9a63b230c4fbc0952",
292
+ input={
293
+ "input_image": img,
294
+ "material_image":material_img
295
+ }
296
+ )
297
+ print(output)
298
+ return output
src/utils.py CHANGED
@@ -1,100 +1,138 @@
1
- import b2sdk.v2 as b2 #Backblaze img2img upload bucket
2
- import base64
3
- import shutil
4
- import os
5
- import requests
6
- import io
7
- from PIL import Image
8
- import numpy as npzipfile
9
- import zipfile
10
-
11
- import tempfile
12
- import json
13
- import gradio as gr
14
-
15
- def update_model_dicts(traning_finnal,token_string,style_json="model_dict.json"):
16
-
17
- print(traning_finnal,token_string)
18
- current_style_dict=json.load(open(style_json,"r"))
19
- current_style_dict[token_string]=traning_finnal
20
- with open(style_json, "w") as json_file:
21
- json.dump(current_style_dict, json_file, indent=4)
22
- json_file.close()
23
- # Return the updated dictionary keys for updating the Dropdown
24
- return list(current_style_dict.keys())
25
-
26
- def update_dropdown(traning_finnal, token_string):
27
- updated_keys = update_model_dicts(traning_finnal, token_string)
28
- return gr.Dropdown.update(choices=updated_keys)
29
-
30
- def add_to_prompt(existing_prompt, new_prompt):
31
- if existing_prompt:
32
- return f"{existing_prompt}, {new_prompt}"
33
- else:
34
- return new_prompt
35
-
36
-
37
- def numpy_to_base64(image_np):
38
- """Converts a numpy image to base64 string."""
39
- img = Image.fromarray(image_np)
40
- buffered = io.BytesIO()
41
- img.save(buffered, format="PNG")
42
- img_str = base64.b64encode(buffered.getvalue()).decode('utf-8')
43
- return "data:image/png;base64,"+img_str
44
-
45
- def image_to_base64(img):
46
- buffered = io.BytesIO()
47
- img.save(buffered, format="PNG")
48
- img_str = base64.b64encode(buffered.getvalue()).decode('utf-8')
49
- return "data:image/png;base64,"+img_str
50
-
51
-
52
- def create_zip(files,captions,trigger):
53
- #Caption processing
54
- captions=captions.split("\n")
55
- #cute files and "tags:"
56
- captions= [cap.split("file:")[0][5:] for cap in captions]
57
- print("files",len(files),"captions",len(captions))
58
- #assert len(files)==len(captions) , "File amount does not equal the captions amount please check"
59
- temp_dir="./datasets/"
60
- os.makedirs(temp_dir,exist_ok=True)
61
-
62
- zip_path = os.path.join(temp_dir, f"training_data_{trigger}.zip")
63
- if os.path.exists(zip_path):
64
- os.remove(zip_path)
65
-
66
- with zipfile.ZipFile(zip_path, "w") as zip_file:
67
- for i, file in enumerate(files):
68
- # Add image to zip
69
- image_name = f"image_{i}.jpg"
70
- print(file)
71
- zip_file.write(file, image_name)
72
- # Add caption to zip
73
- caption_name = f"image_{i}.txt"
74
- caption_content = captions[i] +f", {trigger}"
75
- zip_file.writestr(caption_name, caption_content)
76
- return zip_path
77
-
78
- def BB_uploadfile(local_file,file_name,BB_bucket_name,FRIENDLY_URL=True):
79
- info = b2.InMemoryAccountInfo()
80
- b2_api = b2.B2Api(info)
81
- #print(application_key_id,application_key)
82
- application_key_id = os.getenv("BB_KeyID")
83
- application_key = os.getenv("BB_AppKey")
84
- b2_api.authorize_account("production", application_key_id, application_key)
85
- BB_bucket=b2_api.get_bucket_by_name(BB_bucket_name)
86
- BB_defurl="https://f005.backblazeb2.com/file/"
87
-
88
- metadata = {"key": "value"}
89
- uploaded_file = BB_bucket.upload_local_file(
90
- local_file=local_file,
91
- file_name=file_name,
92
- file_infos=metadata,
93
- )
94
- img_url=b2_api.get_download_url_for_fileid(uploaded_file.id_)
95
- if FRIENDLY_URL: #Get friendly URP
96
- img_url=BB_defurl+BB_bucket_name+"/"+file_name
97
- print("backblaze", img_url)
98
- return img_url
99
- #file="/content/training_data.zip"
100
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import b2sdk.v2 as b2 #Backblaze img2img upload bucket
2
+ import base64
3
+ import os
4
+ from io import BytesIO
5
+ import requests
6
+ import io
7
+ from PIL import Image
8
+ import numpy as npzipfile
9
+ import zipfile
10
+ import numpy as np
11
+ import json
12
+ import gradio as gr
13
+
14
+
15
+ def convert_to_pil(img):
16
+ if isinstance(img, np.ndarray):
17
+ img = Image.fromarray(img)
18
+ # If the image is a URL, fetch the image and convert it to a PIL image
19
+ elif isinstance(img, str) and img.startswith('http'):
20
+ response = requests.get(img)
21
+ img = Image.open(BytesIO(response.content))
22
+ return img
23
+
24
+ def open_image_from_url(image_url):
25
+ response = requests.get(image_url)
26
+ img = Image.open(BytesIO(response.content))
27
+ return img
28
+ def image_to_base64(img):
29
+ buffered = io.BytesIO()
30
+ img.save(buffered, format="PNG")
31
+ img_str = base64.b64encode(buffered.getvalue()).decode('utf-8')
32
+ return "data:image/png;base64,"+img_str
33
+
34
+ def cut_alpha_from_image(image):
35
+ """Cuts out the alpha channel from a Pillow image, returning a new image.
36
+
37
+ Args:
38
+ image: The Pillow image to cut the alpha channel from.
39
+
40
+ Returns:
41
+ A new Pillow image with the alpha channel removed.
42
+ """
43
+ if image.mode == 'RGBA':
44
+ # Extract RGB channels and create a new image without alpha
45
+ rgb_image = Image.new("RGB", image.size, (0, 0, 0))
46
+ rgb_image.paste(image, mask=image.split()[3]) # Use alpha channel as mask
47
+ return rgb_image
48
+ else:
49
+ return image # Image doesn't have an alpha channel, return as is
50
+
51
+ def update_model_dicts(traning_finnal,token_string,style_json="model_dict.json"):
52
+
53
+ print(traning_finnal,token_string)
54
+ current_style_dict=json.load(open(style_json,"r"))
55
+ current_style_dict[token_string]=traning_finnal
56
+ with open(style_json, "w") as json_file:
57
+ json.dump(current_style_dict, json_file, indent=4)
58
+ json_file.close()
59
+ # Return the updated dictionary keys for updating the Dropdown
60
+ return list(current_style_dict.keys())
61
+
62
+ def update_dropdown(traning_finnal, token_string):
63
+ updated_keys = update_model_dicts(traning_finnal, token_string)
64
+ return gr.Dropdown.update(choices=updated_keys)
65
+
66
+ def add_to_prompt(existing_prompt, new_prompt):
67
+ if existing_prompt:
68
+ return f"{existing_prompt}, {new_prompt}"
69
+ else:
70
+ return new_prompt
71
+
72
+
73
+
74
+ def numpy_to_base64(image_np):
75
+ """Converts a numpy image to base64 string."""
76
+ img = Image.fromarray(image_np)
77
+ buffered = io.BytesIO()
78
+ img.save(buffered, format="PNG")
79
+ img_str = base64.b64encode(buffered.getvalue()).decode('utf-8')
80
+ return "data:image/png;base64,"+img_str
81
+
82
+ def image_to_base64(img):
83
+ buffered = io.BytesIO()
84
+ if isinstance(img, np.ndarray):
85
+ img=Image.fromarray(img)
86
+ img.save(buffered, format="PNG")
87
+ img_str = base64.b64encode(buffered.getvalue()).decode('utf-8')
88
+ return "data:image/png;base64,"+img_str
89
+
90
+ def create_zip(files,captions,trigger):
91
+ #Caption processing
92
+ captions=captions.split("\n")
93
+ #cute files and "tags:"
94
+ captions= [cap.split("file:")[0][5:] for cap in captions]
95
+ print("files",len(files),"captions",len(captions))
96
+ #assert len(files)==len(captions) , "File amount does not equal the captions amount please check"
97
+ temp_dir="./datasets/"
98
+ os.makedirs(temp_dir,exist_ok=True)
99
+
100
+ zip_path = os.path.join(temp_dir, f"training_data_{trigger}.zip")
101
+ if os.path.exists(zip_path):
102
+ os.remove(zip_path)
103
+
104
+ with zipfile.ZipFile(zip_path, "w") as zip_file:
105
+ for i, file in enumerate(files):
106
+ # Add image to zip
107
+ image_name = f"image_{i}.jpg"
108
+ print(file)
109
+ zip_file.write(file, image_name)
110
+ # Add caption to zip
111
+ caption_name = f"image_{i}.txt"
112
+ caption_content = captions[i] +f", {trigger}"
113
+ zip_file.writestr(caption_name, caption_content)
114
+ return zip_path
115
+
116
+ def BB_uploadfile(local_file,file_name,BB_bucket_name,FRIENDLY_URL=True):
117
+ info = b2.InMemoryAccountInfo()
118
+ b2_api = b2.B2Api(info)
119
+ #print(application_key_id,application_key)
120
+ application_key_id = os.getenv("BB_KeyID")
121
+ application_key = os.getenv("BB_AppKey")
122
+ b2_api.authorize_account("production", application_key_id, application_key)
123
+ BB_bucket=b2_api.get_bucket_by_name(BB_bucket_name)
124
+ BB_defurl="https://f005.backblazeb2.com/file/"
125
+
126
+ metadata = {"key": "value"}
127
+ uploaded_file = BB_bucket.upload_local_file(
128
+ local_file=local_file,
129
+ file_name=file_name,
130
+ file_infos=metadata,
131
+ )
132
+ img_url=b2_api.get_download_url_for_fileid(uploaded_file.id_)
133
+ if FRIENDLY_URL: #Get friendly URP
134
+ img_url=BB_defurl+BB_bucket_name+"/"+file_name
135
+ print("backblaze", img_url)
136
+ return img_url
137
+ #file="/content/training_data.zip"
138
+