Files changed (3) hide show
  1. README.md +10 -11
  2. app.py +173 -176
  3. requirements.txt +1 -1
README.md CHANGED
@@ -1,12 +1,11 @@
1
- ---
2
- title: Consistent Character
3
- emoji: 🤹
4
- colorFrom: indigo
5
- colorTo: blue
6
- sdk: docker
7
- pinned: false
8
- disable_embedding: true
9
- short_description: Create images of a given character in different poses
10
- ---
11
-
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ ---
2
+ title: Consistent Character
3
+ emoji: 🤹
4
+ colorFrom: indigo
5
+ colorTo: blue
6
+ sdk: docker
7
+ pinned: false
8
+ short_description: Create images of a given character in different poses
9
+ ---
10
+
 
11
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py CHANGED
@@ -1,176 +1,173 @@
1
- import gradio as gr
2
- from urllib.parse import urlparse
3
- import requests
4
- import time
5
- import os
6
- import re
7
-
8
- hf_token = os.environ.get("HF_TOKEN")
9
- from gradio_client import Client
10
-
11
-
12
- def safety_check(user_prompt):
13
-
14
- client = Client("fffiloni/safety-checker-bot", hf_token=hf_token)
15
- response = client.predict(
16
- source_space="consistent-character space",
17
- user_prompt=user_prompt,
18
- api_name="/infer"
19
- )
20
- print(response)
21
-
22
- return response
23
-
24
- from utils.gradio_helpers import parse_outputs, process_outputs
25
-
26
- names = ['prompt', 'negative_prompt', 'subject', 'number_of_outputs', 'number_of_images_per_pose', 'randomise_poses', 'output_format', 'output_quality', 'seed']
27
-
28
- def predict(request: gr.Request, *args, progress=gr.Progress(track_tqdm=True)):
29
- print(f"""
30
- —/n
31
- {args[0]}
32
- """)
33
- if args[0] == '' or args[0] is None:
34
- raise gr.Error(f"You forgot to provide a prompt.")
35
-
36
- try:
37
-
38
- is_safe = safety_check(args[0])
39
- print(is_safe)
40
-
41
- match = re.search(r'\bYes\b', is_safe)
42
-
43
- if match:
44
- status = 'Yes'
45
- else:
46
- status = None
47
-
48
- if status == "Yes" :
49
- raise gr.Error("Do not ask for such things.")
50
- else:
51
-
52
- headers = {'Content-Type': 'application/json'}
53
-
54
- payload = {"input": {}}
55
-
56
-
57
- base_url = "http://0.0.0.0:7860"
58
- for i, key in enumerate(names):
59
- value = args[i]
60
- if value and (os.path.exists(str(value))):
61
- value = f"{base_url}/file=" + value
62
- if value is not None and value != "":
63
- payload["input"][key] = value
64
-
65
- response = requests.post("http://0.0.0.0:5000/predictions", headers=headers, json=payload)
66
-
67
-
68
- if response.status_code == 201:
69
- follow_up_url = response.json()["urls"]["get"]
70
- response = requests.get(follow_up_url, headers=headers)
71
- while response.json()["status"] != "succeeded":
72
- if response.json()["status"] == "failed":
73
- raise gr.Error("The submission failed!")
74
- response = requests.get(follow_up_url, headers=headers)
75
- time.sleep(1)
76
- if response.status_code == 200:
77
- json_response = response.json()
78
- #If the output component is JSON return the entire output response
79
- if(outputs[0].get_config()["name"] == "json"):
80
- return json_response["output"]
81
- predict_outputs = parse_outputs(json_response["output"])
82
- processed_outputs = process_outputs(predict_outputs)
83
- return tuple(processed_outputs) if len(processed_outputs) > 1 else processed_outputs[0]
84
- else:
85
- if(response.status_code == 409):
86
- raise gr.Error(f"Sorry, the Cog image is still processing. Try again in a bit.")
87
- raise gr.Error(f"The submission failed! Error: {response.status_code}")
88
-
89
- except Exception as e:
90
- # Handle any other type of error
91
- raise gr.Error(f"An error occurred: {e}")
92
-
93
- title = "Demo for consistent-character cog image by fofr"
94
- description = "Create images of a given character in different poses • running cog image by fofr"
95
-
96
- css="""
97
- #col-container{
98
- margin: 0 auto;
99
- max-width: 1400px;
100
- text-align: left;
101
- }
102
- """
103
- with gr.Blocks(css=css) as app:
104
- with gr.Column(elem_id="col-container"):
105
- gr.HTML(f"""
106
- <h2 style="text-align: center;">Consistent Character Workflow</h2>
107
- <p style="text-align: center;">{description}</p>
108
- """)
109
-
110
- with gr.Row():
111
- with gr.Column(scale=1):
112
- prompt = gr.Textbox(
113
- label="Prompt", info='''Describe the subject. Include clothes and hairstyle for more consistency.''',
114
- value="a person, darkblue suit, black tie, white pocket"
115
- )
116
-
117
- subject = gr.Image(
118
- label="Subject", type="filepath"
119
- )
120
-
121
- submit_btn = gr.Button("Submit")
122
-
123
- with gr.Accordion(label="Advanced Settings", open=False):
124
-
125
- negative_prompt = gr.Textbox(
126
- label="Negative Prompt", info='''Things you do not want to see in your image''',
127
- value="text, watermark, lowres, low quality, worst quality, deformed, glitch, low contrast, noisy, saturation, blurry"
128
- )
129
-
130
- with gr.Row():
131
-
132
- number_of_outputs = gr.Slider(
133
- label="Number Of Outputs", info='''The number of images to generate.''', value=2,
134
- minimum=1, maximum=4, step=1,
135
- )
136
-
137
- number_of_images_per_pose = gr.Slider(
138
- label="Number Of Images Per Pose", info='''The number of images to generate for each pose.''', value=1,
139
- minimum=1, maximum=4, step=1,
140
- )
141
-
142
- with gr.Row():
143
-
144
- randomise_poses = gr.Checkbox(
145
- label="Randomise Poses", info='''Randomise the poses used.''', value=True
146
- )
147
-
148
- output_format = gr.Dropdown(
149
- choices=['webp', 'jpg', 'png'], label="output_format", info='''Format of the output images''', value="webp"
150
- )
151
-
152
- with gr.Row():
153
-
154
- output_quality = gr.Number(
155
- label="Output Quality", info='''Quality of the output images, from 0 to 100. 100 is best quality, 0 is lowest quality.''', value=80
156
- )
157
-
158
- seed = gr.Number(
159
- label="Seed", info='''Set a seed for reproducibility. Random by default.''', value=None
160
- )
161
-
162
- with gr.Column(scale=1.5):
163
- consistent_results = gr.Gallery(label="Consistent Results")
164
-
165
- inputs = [prompt, negative_prompt, subject, number_of_outputs, number_of_images_per_pose, randomise_poses, output_format, output_quality, seed]
166
- outputs = [consistent_results]
167
-
168
- submit_btn.click(
169
- fn = predict,
170
- inputs = inputs,
171
- outputs = outputs,
172
- show_api = False
173
- )
174
-
175
- app.queue(max_size=12, api_open=False).launch(share=False, show_api=False, show_error=True)
176
-
 
1
+ import gradio as gr
2
+ from urllib.parse import urlparse
3
+ import requests
4
+ import time
5
+ import os
6
+ import re
7
+
8
+ hf_token = os.environ.get("HF_TOKEN")
9
+ from gradio_client import Client
10
+
11
+
12
+ def safety_check(user_prompt):
13
+ client = Client("fffiloni/safety-checker-bot", hf_token=hf_token)
14
+ response = client.predict(
15
+ "consistent-character space", # str source space
16
+ user_prompt, # str in 'User sent this' Textbox component
17
+ api_name="/infer"
18
+ )
19
+ return response
20
+
21
+ from utils.gradio_helpers import parse_outputs, process_outputs
22
+
23
+ names = ['prompt', 'negative_prompt', 'subject', 'number_of_outputs', 'number_of_images_per_pose', 'randomise_poses', 'output_format', 'output_quality', 'seed']
24
+
25
+ def predict(request: gr.Request, *args, progress=gr.Progress(track_tqdm=True)):
26
+ print(f"""
27
+ —/n
28
+ {args[0]}
29
+ """)
30
+ if args[0] == '' or args[0] is None:
31
+ raise gr.Error(f"You forgot to provide a prompt.")
32
+
33
+ try:
34
+
35
+ is_safe = safety_check(args[0])
36
+ print(is_safe)
37
+
38
+ match = re.search(r'\bYes\b', is_safe)
39
+
40
+ if match:
41
+ status = 'Yes'
42
+ else:
43
+ status = None
44
+
45
+ if status == "Yes" :
46
+ raise gr.Error("Do not ask for such things.")
47
+ else:
48
+
49
+ headers = {'Content-Type': 'application/json'}
50
+
51
+ payload = {"input": {}}
52
+
53
+
54
+ base_url = "http://0.0.0.0:7860"
55
+ for i, key in enumerate(names):
56
+ value = args[i]
57
+ if value and (os.path.exists(str(value))):
58
+ value = f"{base_url}/file=" + value
59
+ if value is not None and value != "":
60
+ payload["input"][key] = value
61
+
62
+ response = requests.post("http://0.0.0.0:5000/predictions", headers=headers, json=payload)
63
+
64
+
65
+ if response.status_code == 201:
66
+ follow_up_url = response.json()["urls"]["get"]
67
+ response = requests.get(follow_up_url, headers=headers)
68
+ while response.json()["status"] != "succeeded":
69
+ if response.json()["status"] == "failed":
70
+ raise gr.Error("The submission failed!")
71
+ response = requests.get(follow_up_url, headers=headers)
72
+ time.sleep(1)
73
+ if response.status_code == 200:
74
+ json_response = response.json()
75
+ #If the output component is JSON return the entire output response
76
+ if(outputs[0].get_config()["name"] == "json"):
77
+ return json_response["output"]
78
+ predict_outputs = parse_outputs(json_response["output"])
79
+ processed_outputs = process_outputs(predict_outputs)
80
+ return tuple(processed_outputs) if len(processed_outputs) > 1 else processed_outputs[0]
81
+ else:
82
+ if(response.status_code == 409):
83
+ raise gr.Error(f"Sorry, the Cog image is still processing. Try again in a bit.")
84
+ raise gr.Error(f"The submission failed! Error: {response.status_code}")
85
+
86
+ except Exception as e:
87
+ # Handle any other type of error
88
+ raise gr.Error(f"An error occurred: {e}")
89
+
90
+ title = "Demo for consistent-character cog image by fofr"
91
+ description = "Create images of a given character in different poses • running cog image by fofr"
92
+
93
+ css="""
94
+ #col-container{
95
+ margin: 0 auto;
96
+ max-width: 1400px;
97
+ text-align: left;
98
+ }
99
+ """
100
+ with gr.Blocks(css=css) as app:
101
+ with gr.Column(elem_id="col-container"):
102
+ gr.HTML(f"""
103
+ <h2 style="text-align: center;">Consistent Character Workflow</h2>
104
+ <p style="text-align: center;">{description}</p>
105
+ """)
106
+
107
+ with gr.Row():
108
+ with gr.Column(scale=1):
109
+ prompt = gr.Textbox(
110
+ label="Prompt", info='''Describe the subject. Include clothes and hairstyle for more consistency.''',
111
+ value="a person, darkblue suit, black tie, white pocket"
112
+ )
113
+
114
+ subject = gr.Image(
115
+ label="Subject", type="filepath"
116
+ )
117
+
118
+ submit_btn = gr.Button("Submit")
119
+
120
+ with gr.Accordion(label="Advanced Settings", open=False):
121
+
122
+ negative_prompt = gr.Textbox(
123
+ label="Negative Prompt", info='''Things you do not want to see in your image''',
124
+ value="text, watermark, lowres, low quality, worst quality, deformed, glitch, low contrast, noisy, saturation, blurry"
125
+ )
126
+
127
+ with gr.Row():
128
+
129
+ number_of_outputs = gr.Slider(
130
+ label="Number Of Outputs", info='''The number of images to generate.''', value=2,
131
+ minimum=1, maximum=4, step=1,
132
+ )
133
+
134
+ number_of_images_per_pose = gr.Slider(
135
+ label="Number Of Images Per Pose", info='''The number of images to generate for each pose.''', value=1,
136
+ minimum=1, maximum=4, step=1,
137
+ )
138
+
139
+ with gr.Row():
140
+
141
+ randomise_poses = gr.Checkbox(
142
+ label="Randomise Poses", info='''Randomise the poses used.''', value=True
143
+ )
144
+
145
+ output_format = gr.Dropdown(
146
+ choices=['webp', 'jpg', 'png'], label="output_format", info='''Format of the output images''', value="webp"
147
+ )
148
+
149
+ with gr.Row():
150
+
151
+ output_quality = gr.Number(
152
+ label="Output Quality", info='''Quality of the output images, from 0 to 100. 100 is best quality, 0 is lowest quality.''', value=80
153
+ )
154
+
155
+ seed = gr.Number(
156
+ label="Seed", info='''Set a seed for reproducibility. Random by default.''', value=None
157
+ )
158
+
159
+ with gr.Column(scale=1.5):
160
+ consistent_results = gr.Gallery(label="Consistent Results")
161
+
162
+ inputs = [prompt, negative_prompt, subject, number_of_outputs, number_of_images_per_pose, randomise_poses, output_format, output_quality, seed]
163
+ outputs = [consistent_results]
164
+
165
+ submit_btn.click(
166
+ fn = predict,
167
+ inputs = inputs,
168
+ outputs = outputs,
169
+ show_api = False
170
+ )
171
+
172
+ app.queue(max_size=12, api_open=False).launch(share=False, show_api=False, show_error=True)
173
+
 
 
 
requirements.txt CHANGED
@@ -1,2 +1,2 @@
1
- gradio==5.0.1
2
  prance
 
1
+ gradio==4.44.0
2
  prance