Skip to content

Commit b638028

Browse files
authored
Merge pull request #279 from mrhan1993:url_support
url support for lora in replicate
2 parents 98ac6c5 + 51af7f6 commit b638028

File tree

5 files changed

+87
-5
lines changed

5 files changed

+87
-5
lines changed

.dockerignore

-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ user_path_config-deprecated.txt
2020
build_chb.py
2121
experiment.py
2222
/modules/*.png
23-
/repositories
2423
/venv
2524
/tmp
2625
/ui-config.json

fooocusapi/parameters.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
default_base_model_name = "juggernautXL_v8Rundiffusion.safetensors"
3636
default_refiner_model_name = "None"
3737
default_refiner_switch = 0.5
38-
default_loras = [[True, "sd_xl_offset_example-lora_1.0.safetensors", 0.1]]
38+
default_loras = [["sd_xl_offset_example-lora_1.0.safetensors", 0.1]]
3939
default_cfg_scale = 7.0
4040
default_prompt_negative = ""
4141
default_aspect_ratio = "1152*896"

fooocusapi/utils/lora_manager.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
Manager loras from url
3+
4+
@author: TechnikMax
5+
@github: https://github.com/TechnikMax
6+
"""
7+
import hashlib
8+
import os
9+
import requests
10+
11+
12+
def _hash_url(url):
13+
"""Generates a hash value for a given URL."""
14+
return hashlib.md5(url.encode('utf-8')).hexdigest()
15+
16+
17+
class LoraManager:
18+
"""
19+
Manager loras from url
20+
"""
21+
def __init__(self):
22+
self.cache_dir = os.path.join(
23+
os.path.dirname(os.path.realpath(__file__)),
24+
'../../',
25+
'repositories/Fooocus/models/loras')
26+
27+
def _download_lora(self, url):
28+
"""
29+
Downloads a LoRa from a URL and saves it in the cache.
30+
"""
31+
url_hash = _hash_url(url)
32+
filepath = os.path.join(self.cache_dir, f"{url_hash}.safetensors")
33+
file_name = f"{url_hash}.safetensors"
34+
35+
if not os.path.exists(filepath):
36+
print(f"start download for: {url}")
37+
38+
try:
39+
response = requests.get(url, timeout=10, stream=True)
40+
response.raise_for_status()
41+
with open(filepath, 'wb') as f:
42+
for chunk in response.iter_content(chunk_size=8192):
43+
f.write(chunk)
44+
print(f"Download successfully, saved as {file_name}")
45+
46+
except Exception as e:
47+
raise Exception(f"error downloading {url}: {e}") from e
48+
49+
else:
50+
print(f"LoRa already downloaded {url}")
51+
return file_name
52+
53+
def check(self, urls):
54+
"""Manages the specified LoRAs: downloads missing ones and returns their file names."""
55+
paths = []
56+
for url in urls:
57+
path = self._download_lora(url)
58+
paths.append(path)
59+
return paths

fooocusapi/worker.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -464,7 +464,8 @@ def yield_result(_, imgs, tasks, extension='png'):
464464
pipeline.refresh_everything(
465465
refiner_model_name=refiner_model_name,
466466
base_model_name=base_model_name,
467-
loras=loras, base_model_additional_loras=base_model_additional_loras,
467+
loras=loras,
468+
base_model_additional_loras=base_model_additional_loras,
468469
use_synthetic_refiner=use_synthetic_refiner)
469470

470471
progressbar(async_task, 3, 'Processing prompts ...')

predict.py

+25-2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
from PIL import Image
1212
from cog import BasePredictor, BaseModel, Input, Path
13+
from fooocusapi.utils.lora_manager import LoraManager
1314
from fooocusapi.utils.file_utils import output_dir
1415
from fooocusapi.models.common.task import GenerationFinishReason
1516
from fooocusapi.parameters import (
@@ -59,7 +60,7 @@ def predict(
5960
description="Fooocus styles applied for image generation, separated by comma"),
6061
performance_selection: str = Input(
6162
default='Speed',
62-
choices=['Speed', 'Quality', 'Extreme Speed'],
63+
choices=['Speed', 'Quality', 'Extreme Speed', 'Lightning'],
6364
description="Performance selection"),
6465
aspect_ratios_selection: str = Input(
6566
default='1152*896',
@@ -72,6 +73,12 @@ def predict(
7273
image_seed: int = Input(
7374
default=-1,
7475
description="Seed to generate image, -1 for random"),
76+
use_default_loras: bool = Input(
77+
default=True,
78+
description="Use default LoRAs"),
79+
loras_custom_urls: str = Input(
80+
default="",
81+
description="Custom LoRAs URLs in the format 'url,weight' provide multiple seperated by ; (example 'url1,0.3;url2,0.1')"),
7582
sharpness: float = Input(
7683
default=2.0,
7784
ge=0.0, le=30.0),
@@ -182,7 +189,23 @@ def predict(
182189

183190
base_model_name = default_base_model_name
184191
refiner_model_name = default_refiner_model_name
185-
loras = copy.copy(default_loras)
192+
193+
lora_manager = LoraManager()
194+
195+
# Use default loras if selected
196+
loras = copy.copy(default_loras) if use_default_loras else []
197+
198+
# add custom user loras if provided
199+
if loras_custom_urls:
200+
urls = [url.strip() for url in loras_custom_urls.split(';')]
201+
202+
loras_with_weights = [url.split(',') for url in urls]
203+
204+
custom_lora_paths = lora_manager.check([lw[0] for lw in loras_with_weights])
205+
custom_loras = [[path, float(lw[1]) if len(lw) > 1 else 1.0] for path, lw in
206+
zip(custom_lora_paths, loras_with_weights)]
207+
208+
loras.extend(custom_loras)
186209

187210
style_selections_arr = []
188211
for s in style_selections.strip().split(','):

0 commit comments

Comments
 (0)