Spaces:
Running
on
Zero
Running
on
Zero
add : refinement logic
Browse files- app.py +18 -5
- llm_wrapper.py +107 -0
- prompt.json +7 -0
app.py
CHANGED
@@ -7,12 +7,19 @@ from diffusers import DiffusionPipeline, FlowMatchEulerDiscreteScheduler, Autoe
|
|
7 |
from transformers import CLIPTextModel, CLIPTokenizer,T5EncoderModel, T5TokenizerFast
|
8 |
from live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_images
|
9 |
|
|
|
10 |
from huggingface_hub import hf_hub_download
|
11 |
from safetensors.torch import load_file
|
12 |
import subprocess
|
13 |
|
14 |
subprocess.run("rm -rf /data-nvme/zerogpu-offload/*", env={}, shell=True)
|
15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
dtype = torch.bfloat16
|
17 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
18 |
|
@@ -38,9 +45,15 @@ def infer(prompt, seed=42, randomize_seed=False, width=1024, height=1024, guidan
|
|
38 |
if randomize_seed:
|
39 |
seed = random.randint(0, MAX_SEED)
|
40 |
generator = torch.Generator().manual_seed(seed)
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
|
42 |
for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
|
43 |
-
prompt=prompt,
|
44 |
guidance_scale=guidance_scale,
|
45 |
num_inference_steps=num_inference_steps,
|
46 |
width=width,
|
@@ -52,9 +65,9 @@ def infer(prompt, seed=42, randomize_seed=False, width=1024, height=1024, guidan
|
|
52 |
yield img, seed
|
53 |
|
54 |
examples = [
|
55 |
-
"
|
56 |
-
"
|
57 |
-
"
|
58 |
]
|
59 |
|
60 |
css="""
|
@@ -67,7 +80,7 @@ css="""
|
|
67 |
with gr.Blocks(css=css) as demo:
|
68 |
|
69 |
with gr.Column(elem_id="col-container"):
|
70 |
-
gr.Markdown(f"""# [POSTECH] PONIX Generator
|
71 |
[[non-commercial license](https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md)] [[blog](https://blackforestlabs.ai/announcing-black-forest-labs/)] [[model](https://huggingface.co/black-forest-labs/FLUX.1-dev)]
|
72 |
""")
|
73 |
|
|
|
7 |
from transformers import CLIPTextModel, CLIPTokenizer,T5EncoderModel, T5TokenizerFast
|
8 |
from live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_images
|
9 |
|
10 |
+
from llm_wrapper import run_gemini
|
11 |
from huggingface_hub import hf_hub_download
|
12 |
from safetensors.torch import load_file
|
13 |
import subprocess
|
14 |
|
15 |
subprocess.run("rm -rf /data-nvme/zerogpu-offload/*", env={}, shell=True)
|
16 |
|
17 |
+
|
18 |
+
from pydantic import BaseModel
|
19 |
+
|
20 |
+
class RefinedPrompt(BaseModel):
|
21 |
+
prompt: str
|
22 |
+
|
23 |
dtype = torch.bfloat16
|
24 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
25 |
|
|
|
45 |
if randomize_seed:
|
46 |
seed = random.randint(0, MAX_SEED)
|
47 |
generator = torch.Generator().manual_seed(seed)
|
48 |
+
|
49 |
+
refined_prompt = run_gemini(
|
50 |
+
target_prompt=prompt,
|
51 |
+
prompt_in_path="prompt.json",
|
52 |
+
output_structure=RefinedPrompt,
|
53 |
+
)
|
54 |
|
55 |
for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
|
56 |
+
prompt=refined_prompt.prompt,
|
57 |
guidance_scale=guidance_scale,
|
58 |
num_inference_steps=num_inference_steps,
|
59 |
width=width,
|
|
|
65 |
yield img, seed
|
66 |
|
67 |
examples = [
|
68 |
+
"๊ธฐ๊ณ๊ณตํ๊ณผ(๋ก์ผ) ํฌ๋์ค",
|
69 |
+
"๋ฐ์ด์ฌ๋ฆฐ์ ์ฐ์ฃผํ๋ ํฌ๋์ค",
|
70 |
+
"๋ฌผ๋ฆฌํ์ ์ฐ๊ตฌํ๋ ํฌ๋์ค",
|
71 |
]
|
72 |
|
73 |
css="""
|
|
|
80 |
with gr.Blocks(css=css) as demo:
|
81 |
|
82 |
with gr.Column(elem_id="col-container"):
|
83 |
+
gr.Markdown(f"""# [POSTECH] PONIX Generator ๐
|
84 |
[[non-commercial license](https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md)] [[blog](https://blackforestlabs.ai/announcing-black-forest-labs/)] [[model](https://huggingface.co/black-forest-labs/FLUX.1-dev)]
|
85 |
""")
|
86 |
|
llm_wrapper.py
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
from PIL import Image
|
3 |
+
from io import BytesIO
|
4 |
+
import requests, os, json, time
|
5 |
+
|
6 |
+
from google import genai
|
7 |
+
|
8 |
+
prompt_base_path = "src/llm_wrapper/prompt"
|
9 |
+
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))
|
10 |
+
|
11 |
+
|
12 |
+
def encode_image(image_source):
|
13 |
+
"""
|
14 |
+
์ด๋ฏธ์ง ๊ฒฝ๋ก๊ฐ URL์ด๋ ๋ก์ปฌ ํ์ผ์ด๋ Pillow Image ๊ฐ์ฒด์ด๋ ๋์ผํ๊ฒ ์ฒ๋ฆฌํ๋ ํจ์.
|
15 |
+
์ด๋ฏธ์ง๋ฅผ ์ด์ด google.genai.types.Part ๊ฐ์ฒด๋ก ๋ณํํฉ๋๋ค.
|
16 |
+
Pillow์์ ์ง์๋์ง ์๋ ํฌ๋งท์ ๋ํด์๋ ์์ธ๋ฅผ ๋ฐ์์ํต๋๋ค.
|
17 |
+
"""
|
18 |
+
try:
|
19 |
+
# ์ด๋ฏธ Pillow ์ด๋ฏธ์ง ๊ฐ์ฒด์ธ ๊ฒฝ์ฐ ๊ทธ๋๋ก ์ฌ์ฉ
|
20 |
+
if isinstance(image_source, Image.Image):
|
21 |
+
image = image_source
|
22 |
+
else:
|
23 |
+
# URL์์ ์ด๋ฏธ์ง ๋ค์ด๋ก๋
|
24 |
+
if isinstance(image_source, str) and (
|
25 |
+
image_source.startswith("http://")
|
26 |
+
or image_source.startswith("https://")
|
27 |
+
):
|
28 |
+
response = requests.get(image_source)
|
29 |
+
image = Image.open(BytesIO(response.content))
|
30 |
+
# ๋ก์ปฌ ํ์ผ์์ ์ด๋ฏธ์ง ์ด๊ธฐ
|
31 |
+
else:
|
32 |
+
image = Image.open(image_source)
|
33 |
+
|
34 |
+
# ์ด๋ฏธ์ง ํฌ๋งท์ด None์ธ ๊ฒฝ์ฐ (๋ฉ๋ชจ๋ฆฌ์์ ์์ฑ๋ ์ด๋ฏธ์ง ๋ฑ)
|
35 |
+
if image.format is None:
|
36 |
+
image_format = "JPEG"
|
37 |
+
else:
|
38 |
+
image_format = image.format
|
39 |
+
|
40 |
+
# ์ด๋ฏธ์ง ํฌ๋งท์ด ์ง์๋์ง ์๋ ๊ฒฝ์ฐ ์์ธ ๋ฐ์
|
41 |
+
if image_format not in Image.registered_extensions().values():
|
42 |
+
raise ValueError(f"Unsupported image format: {image_format}.")
|
43 |
+
|
44 |
+
buffered = BytesIO()
|
45 |
+
# PIL์์ ์ง์๋์ง ์๋ ํฌ๋งท์ด๋ ๋ค์ํ ์ฑ๋์ RGB๋ก ๋ณํ ํ ์ ์ฅ
|
46 |
+
if image.mode in ("RGBA", "P", "CMYK"): # RGBA, ํ๋ ํธ, CMYK ๋ฑ์ RGB๋ก ๋ณํ
|
47 |
+
image = image.convert("RGB")
|
48 |
+
image.save(buffered, format="JPEG")
|
49 |
+
|
50 |
+
return genai.types.Part.from_bytes(data=buffered.getvalue(), mime_type="image/jpeg")
|
51 |
+
|
52 |
+
except requests.exceptions.RequestException as e:
|
53 |
+
raise ValueError(f"Failed to download the image from URL: {e}")
|
54 |
+
except IOError as e:
|
55 |
+
raise ValueError(f"Failed to process the image file: {e}")
|
56 |
+
except ValueError as e:
|
57 |
+
raise ValueError(e)
|
58 |
+
|
59 |
+
|
60 |
+
def run_gemini(
|
61 |
+
target_prompt: str,
|
62 |
+
prompt_in_path: str,
|
63 |
+
output_structure,
|
64 |
+
img_in_data: str = None,
|
65 |
+
model: str = "gemini-2.0-flash",
|
66 |
+
) -> str:
|
67 |
+
"""
|
68 |
+
GEMINI API๋ฅผ ๋๊ธฐ ๋ฐฉ์์ผ๋ก ํธ์ถํ์ฌ ๋ฌธ์์ด ์๋ต์ ๋ฐ์ต๋๋ค.
|
69 |
+
retry ๋
ผ๋ฆฌ๋ ์ ๊ฑฐ๋์์ต๋๋ค.
|
70 |
+
"""
|
71 |
+
with open(os.path.join(prompt_base_path, prompt_in_path), "r", encoding="utf-8") as file:
|
72 |
+
prompt_dict = json.load(file)
|
73 |
+
|
74 |
+
system_prompt = prompt_dict["system_prompt"]
|
75 |
+
user_prompt_head = prompt_dict["user_prompt"]["head"]
|
76 |
+
user_prompt_tail = prompt_dict["user_prompt"]["tail"]
|
77 |
+
|
78 |
+
user_prompt_text = "\n".join([user_prompt_head, target_prompt, user_prompt_tail])
|
79 |
+
input_content = [user_prompt_text]
|
80 |
+
|
81 |
+
if img_in_data is not None:
|
82 |
+
encoded_image = encode_image(img_in_data)
|
83 |
+
input_content.append(encoded_image)
|
84 |
+
|
85 |
+
logging.info("Requested API for chat completion response (sync call)...")
|
86 |
+
start_time = time.time()
|
87 |
+
|
88 |
+
# ๋๊ธฐ ๋ฐฉ์: client.models.generate_content(...)
|
89 |
+
chat_completion = client.models.generate_content(
|
90 |
+
model=model,
|
91 |
+
contents=input_content,
|
92 |
+
config={
|
93 |
+
"system_instruction": system_prompt,
|
94 |
+
"response_mime_type": "application/json",
|
95 |
+
"response_schema": output_structure,
|
96 |
+
}
|
97 |
+
)
|
98 |
+
|
99 |
+
chat_output = chat_completion.parsed
|
100 |
+
input_token = chat_completion.usage_metadata.prompt_token_count
|
101 |
+
output_token = chat_completion.usage_metadata.candidates_token_count
|
102 |
+
pricing = input_token / 1000000 * 0.1 * 1500 + output_token / 1000000 * 0.7 * 1500
|
103 |
+
|
104 |
+
logging.info(
|
105 |
+
f"[GEMINI] Request completed (sync). Time taken: {time.time()-start_time:.2f}s / Pricing(KRW): {pricing:.2f}"
|
106 |
+
)
|
107 |
+
return chat_output, chat_completion
|
prompt.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"system_prompt": "**์ญํ (Role)**\n\n๋น์ (์์คํ
)์ ์ฌ์ฉ์๊ฐ ์
๋ ฅํ ์๊ตฌ์ฌํญ(ํ๊ตญ์ด ๋ฌธ์ฅ)์ ๋ฐ์,\nTextual Inversion์ด ์ ์ฉ๋ ํ ํฐ(\"<s0><s1><s2> plush bird\")์ด ๋ฐ๋์ ํฌํจ๋ ์์ด ํ
์คํธ ํ๋กฌํํธ๋ฅผ ์์ฑํด์ผ ํฉ๋๋ค.\n์ถ๊ฐ๋ก ๋ฐฐ๊ฒฝยท์ํฉยท์คํ์ผ์ ํ๋ถํ๊ฒ ๋ฌ์ฌํ์ฌ, ์ค์ ํ
์คํธ ํฌ ์ด๋ฏธ์ง ๋ชจ๋ธ์ ๋ฃ๊ธฐ๋ง ํ๋ฉด ์ํ๋ ์ฅ๋ฉด์ด ์์ฑ๋๋๋ก ๋์์ ์ค๋๋ค.\n\n\n**์ฃผ์ ๊ท์น(Rules)**\n\n**\"ํฌ๋์ค\"**๋ผ๋ ๋จ์ด๊ฐ ์๊ตฌ์ฌํญ์ ๋ฑ์ฅํ๋ฉด, ์ด๋ฅผ **<s0><s1><s2> plush bird**๋ก ์นํํ๋ค.\nํญ์ ํ๋กฌํํธ ๋ฌธ์ฅ ์๋ถ๋ถ์ **photo of <s0><s1><s2> plush bird**๋ฅผ ํฌํจํ๋ค.\n์ฌ์ฉ์๊ฐ ์ํ๋ **์ฅ๋ฉด(๋ฐฐ๊ฒฝ, ํ๊ฒฝ, ์ํฉ)**์ ์์ด๋ก ์์ธํ ๋ฌ์ฌํ๋ค.\n์คํ์ผ(e.g., hyper-realistic, cinematic lighting, 8k resolution, ultra high quality, ๋ฑ)์ ์ ์ ํ ์ถ๊ฐํด ๊ณ ํ๋ฆฌํฐ ์ด๋ฏธ์ง๋ฅผ ์ ๋ํ๋ค.\n์ถ๋ ฅ์ ๋จ์ผ ๋ฌธ์์ด(๋๋ ์ฌ๋ฌ ์ค) ํํ๋ก ์์ด ๋ฌธ์ฅ ์์ฃผ๋ก ์์ฑํ๋ค.\n\n\n\n**์์(Examples)**\n\nInput 1\n์ฌ์ฉ์: \"๊ธฐ๊ณ๊ณตํ๊ณผ(๋ก์ผ) ํฌ๋์ค\"\n์์คํ
๋ณํ:\nphoto of <s0><s1><s2> plush bird \nwearing an astronaut suit and space helmet\ninside a spacecraft cockpit during flight, \nsurrounded by control panels and navigation systems,\nblinking lights and monitoring screens,\nEarth visible through the spacecraft window in background,\nhyper-realistic details, cinematic lighting, 8k resolution, \nultra high quality photograph, \nhigh-tech space environment, adventurous atmosphere\n\n\nInput 2\n์ฌ์ฉ์: \"๋ฐ์ด์ฌ๋ฆฐ์ ์ฐ์ฃผํ๋ ํฌ๋์ค\"\n์์คํ
๋ณํ:\nphoto of <s0><s1><s2> plush bird \nwearing an elegant black tailcoat,\ncrisp white dress shirt with bow tie,\nformal concert attire,\nholding a violin in playing position,\nin a grand concert hall with ornate architecture,\nwarm ambient lighting from chandeliers,\norchestra members visible in background,\nsheet music on stand nearby,\naudience in formal attire visible,\npolished wooden stage floor,\nconductor's podium visible in background,\nhyper-realistic details, warm classical lighting, 8k resolution,\nultra high quality photograph,\nprofessional classical concert environment, performance moment\n\n\nInput 3\n์ฌ์ฉ์: \"๋ฌผ๋ฆฌํ์ ์ฐ๊ตฌํ๋ ํฌ๋์ค\"\n์์คํ
๋ณํ:\nphoto of <s0><s1><s2> plush bird \nwearing a lab coat and safety glasses,\ninside a physics laboratory,\nconducting experiments with quantum physics equipment,\nsurrounded by equations written on whiteboards,\noperating particle accelerator models,\nmeasuring devices and scientific instruments visible,\nhyper-realistic details, dramatic academic lighting, 8k resolution,\nultra high quality photograph,\nscientific environment, discovery atmosphere\n\n\n**์ถ๋ ฅ ํ์(Output Format)**\n\n์ต์ข
์ถ๋ ฅ์ ์์ด ํ
์คํธ๋ก ๋ ํ๋์ ํ๋กฌํํธ ๋ฌธ์ฅ(๋๋ ์ฌ๋ฌ ์ค)์ด๋ฉฐ,\n๋ฐ๋์ <s0><s1><s2> plush bird๊ฐ ๋ค์ด ์์ด์ผ ํจ.\n์ํฉ์ ๋ฐ๋ผ ๋ฐฐ๊ฒฝยท๋ํ
์ผยท์กฐ๋ช
ยทํด์๋๋ฅผ ๋ค์ํ ํ์ฉ์ฌ๋ก ํ๋ถํ ๊ธฐ์ ํด ์ค๋ค.",
|
3 |
+
"user_prompt": {
|
4 |
+
"head": "",
|
5 |
+
"tail": ""
|
6 |
+
}
|
7 |
+
}
|