Spaces:
Sleeping

topguy commited on
Commit
de132df
·
1 Parent(s): be1294b

UX Polish, Metadata Embedding & Local Name Generation

Browse files

- Character Naming: Added Character Name field to Identity tab.
- Procedural Naming: Integrated 'fictional-names' library for instant, thematic fantasy name generation (🎲 button).
- Metadata Embedding: Prompts and character names are now embedded into PNG 'tEXt' chunks (Comment, CharacterName).
- Smart Filenaming: Portraits and character data are saved using the character's name.
- Clipboard: Added native 'Copy' buttons to prompt textboxes.
- UI Stability: Fixed multiple runtime exceptions (NameErrors, AttributeErrors) and implemented a UI build test script.
- Documentation: Updated design.md and created walkthrough.md to document new features.

.gradio/certificate.pem ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -----BEGIN CERTIFICATE-----
2
+ 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
31
+ -----END CERTIFICATE-----
app.py CHANGED
@@ -3,4 +3,4 @@ from modules.ui_layout import build_ui
3
 
4
  if __name__ == "__main__":
5
  demo = build_ui()
6
- demo.launch(theme=gr.themes.Soft(),share=True)
 
3
 
4
  if __name__ == "__main__":
5
  demo = build_ui()
6
+ demo.launch(theme=gr.themes.Soft(),share=False)
commit_msg_ux_polish.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ UX Polish, Metadata Embedding & Local Name Generation
2
+
3
+ - Character Naming: Added Character Name field to Identity tab.
4
+ - Procedural Naming: Integrated 'fictional-names' library for instant, thematic fantasy name generation (🎲 button).
5
+ - Metadata Embedding: Prompts and character names are now embedded into PNG 'tEXt' chunks (Comment, CharacterName).
6
+ - Smart Filenaming: Portraits and character data are saved using the character's name.
7
+ - Clipboard: Added native 'Copy' buttons to prompt textboxes.
8
+ - UI Stability: Fixed multiple runtime exceptions (NameErrors, AttributeErrors) and implemented a UI build test script.
9
+ - Documentation: Updated design.md and created walkthrough.md to document new features.
design.md CHANGED
@@ -7,9 +7,9 @@ RPGPortrait is a Gradio-based web application that helps users build detailed pr
7
  The UI is built using `gradio.Blocks` to allow for a structured, multi-column layout.
8
 
9
  ### Layout Structure
10
- - **Global Control**: Save/Load character (JSON), Randomize features.
11
  - **Input Sections**: Organized into columns/rows of dropdown menus.
12
- - **Identity**: Race, Class, Gender, Age.
13
  - **Appearance**: Hair Style/Color, Eye Color, Build, Skin Tone, Distinguishing Features.
14
  - **Equipment**: Armor/Clothing, Weapons, Accessories (up to 2), Materials.
15
  - **Environment**: Background, Lighting, Atmosphere.
@@ -34,6 +34,11 @@ The app uses a 3-stage prompt pipeline:
34
  - **Cloud**: Sent to `imagen-4.0-generate-001`.
35
  - **Local**: Sent to a ComfyUI endpoint via `POST /prompt`, utilizing a custom workflow (`comfy_rpg_char_gen.json`).
36
 
 
 
 
 
 
37
  ## Data & Persistence
38
  - **YAML Configuration**: `features.yaml` stores all possible dropdown values, their descriptive labels, and the final prompt template.
39
  - **JSON Serialization**: "Save/Load" functionality allows users to export and import their full character state as a JSON file.
@@ -65,6 +70,7 @@ The app uses a 3-stage prompt pipeline:
65
  - **`modules/integrations.py`**: Wrappers for AI backends (Gemini, Ollama, ComfyUI).
66
  - **`modules/core_logic.py`**: Character state management and prompt assembly.
67
  - **`modules/ui_layout.py`**: The full Gradio UI definition (`build_ui`).
 
68
  - **`comfy/`**: Dedicated folder for ComfyUI-specific JSON workflows and utility scripts.
69
 
70
  ### 3. Deployment (Hugging Face Spaces)
 
7
  The UI is built using `gradio.Blocks` to allow for a structured, multi-column layout.
8
 
9
  ### Layout Structure
10
+ - **Global Control**: Save/Load character (JSON), Randomize features, **Character Naming**.
11
  - **Input Sections**: Organized into columns/rows of dropdown menus.
12
+ - **Identity**: Race, Class (with **🎲 Auto-Name**), Gender, Age.
13
  - **Appearance**: Hair Style/Color, Eye Color, Build, Skin Tone, Distinguishing Features.
14
  - **Equipment**: Armor/Clothing, Weapons, Accessories (up to 2), Materials.
15
  - **Environment**: Background, Lighting, Atmosphere.
 
34
  - **Cloud**: Sent to `imagen-4.0-generate-001`.
35
  - **Local**: Sent to a ComfyUI endpoint via `POST /prompt`, utilizing a custom workflow (`comfy_rpg_char_gen.json`).
36
 
37
+ ## Naming & Metadata
38
+ - **Local Naming**: Uses a procedural generator based on the `fictional-names` library for instant, thematic results.
39
+ - **Metadata Embedding**: Generation prompts and character names are embedded directly into the PNG `tEXt` chunks (Comment and CharacterName keys).
40
+ - **Filenames**: Character names are sanitized and used for both JSON and PNG output.
41
+
42
  ## Data & Persistence
43
  - **YAML Configuration**: `features.yaml` stores all possible dropdown values, their descriptive labels, and the final prompt template.
44
  - **JSON Serialization**: "Save/Load" functionality allows users to export and import their full character state as a JSON file.
 
70
  - **`modules/integrations.py`**: Wrappers for AI backends (Gemini, Ollama, ComfyUI).
71
  - **`modules/core_logic.py`**: Character state management and prompt assembly.
72
  - **`modules/ui_layout.py`**: The full Gradio UI definition (`build_ui`).
73
+ - **`modules/name_generator.py`**: Local procedural name generator using the `fictional-names` library.
74
  - **`comfy/`**: Dedicated folder for ComfyUI-specific JSON workflows and utility scripts.
75
 
76
  ### 3. Deployment (Hugging Face Spaces)
modules/core_logic.py CHANGED
@@ -20,9 +20,12 @@ def generate_prompt(*args):
20
  """
21
  Assembles the prompt based on dropdown selections and extra text info.
22
  """
 
23
  num_features = len(FEATURE_SEQUENCE)
24
- feature_keys = args[:num_features]
25
- extra_infos = args[num_features : num_features + len(SECTIONS)]
 
 
26
 
27
  template = features_data.get("templates", {}).get("default", "")
28
 
@@ -59,7 +62,10 @@ def generate_prompt(*args):
59
  context['camera'] += f", art style notes: {extra_infos[4]}"
60
 
61
  try:
62
- return template.format(**context)
 
 
 
63
  except Exception as e:
64
  return f"Error building prompt: {e}"
65
 
@@ -81,20 +87,25 @@ def handle_regeneration(*args):
81
 
82
  def save_character(*args):
83
  """Saves all current UI values to a JSON file."""
 
84
  num_features = len(FEATURE_SEQUENCE)
85
- feature_keys = args[:num_features]
86
- checkboxes = args[num_features : num_features*2]
87
- extra_infos = args[num_features*2 : num_features*2 + len(SECTIONS)]
88
 
89
  data = {
 
90
  "features": {FEATURE_SEQUENCE[i][2]: feature_keys[i] for i in range(num_features)},
91
  "randomization": {FEATURE_SEQUENCE[i][2]: checkboxes[i] for i in range(num_features)},
92
  "extra_info": {SECTIONS[i].lower(): extra_infos[i] for i in range(len(SECTIONS))}
93
  }
94
 
95
  # Save to a file with a friendly name in a temp directory
 
 
 
96
  temp_dir = tempfile.mkdtemp()
97
- path = os.path.join(temp_dir, "rpg_character_config.json")
98
  with open(path, 'w') as f:
99
  json.dump(data, f, indent=4)
100
  return path
@@ -102,7 +113,7 @@ def save_character(*args):
102
  def load_character(file):
103
  """Loads UI values from a JSON file."""
104
  if file is None:
105
- return [gr.update()] * (len(FEATURE_SEQUENCE) * 2 + len(SECTIONS))
106
 
107
  try:
108
  file_path = file.name if hasattr(file, 'name') else file
@@ -110,6 +121,9 @@ def load_character(file):
110
  data = json.load(f)
111
 
112
  updates = []
 
 
 
113
  # Update dropdowns
114
  for _, _, t_key in FEATURE_SEQUENCE:
115
  updates.append(data.get("features", {}).get(t_key, gr.update()))
@@ -125,7 +139,7 @@ def load_character(file):
125
  return updates
126
  except Exception as e:
127
  print(f"Error loading character: {e}")
128
- return [gr.update()] * (len(FEATURE_SEQUENCE) * 2 + len(SECTIONS))
129
 
130
  def get_example_list():
131
  """Returns a list of JSON filenames in the examples directory."""
@@ -136,7 +150,7 @@ def get_example_list():
136
  def load_example_character(filename):
137
  """Loads a character config from the examples directory."""
138
  if not filename:
139
- return [gr.update()] * (len(FEATURE_SEQUENCE) * 2 + len(SECTIONS))
140
 
141
  path = os.path.join(EXAMPLES_DIR, filename)
142
  return load_character(path)
 
20
  """
21
  Assembles the prompt based on dropdown selections and extra text info.
22
  """
23
+ character_name = args[0]
24
  num_features = len(FEATURE_SEQUENCE)
25
+ feature_keys = args[1:num_features+1]
26
+ # Checkboxes are at args[num_features+1 : num_features+1 + num_features]
27
+ # Extra info starts after the name, dropdowns, and checkboxes
28
+ extra_infos = args[1 + num_features*2 : 1 + num_features*2 + len(SECTIONS)]
29
 
30
  template = features_data.get("templates", {}).get("default", "")
31
 
 
62
  context['camera'] += f", art style notes: {extra_infos[4]}"
63
 
64
  try:
65
+ base_prompt = template.format(**context)
66
+ if character_name and character_name.strip() and character_name != "Unnamed Hero":
67
+ return f"A portrait of {character_name}, {base_prompt}"
68
+ return base_prompt
69
  except Exception as e:
70
  return f"Error building prompt: {e}"
71
 
 
87
 
88
  def save_character(*args):
89
  """Saves all current UI values to a JSON file."""
90
+ character_name = args[0]
91
  num_features = len(FEATURE_SEQUENCE)
92
+ feature_keys = args[1:num_features+1]
93
+ checkboxes = args[num_features+1 : num_features+1 + num_features]
94
+ extra_infos = args[num_features+1 + num_features : num_features+1 + num_features + len(SECTIONS)]
95
 
96
  data = {
97
+ "name": character_name,
98
  "features": {FEATURE_SEQUENCE[i][2]: feature_keys[i] for i in range(num_features)},
99
  "randomization": {FEATURE_SEQUENCE[i][2]: checkboxes[i] for i in range(num_features)},
100
  "extra_info": {SECTIONS[i].lower(): extra_infos[i] for i in range(len(SECTIONS))}
101
  }
102
 
103
  # Save to a file with a friendly name in a temp directory
104
+ safe_name = "".join([c if c.isalnum() else "_" for c in character_name]).strip("_")
105
+ filename = f"{safe_name}_data.json" if safe_name else "rpg_character_data.json"
106
+
107
  temp_dir = tempfile.mkdtemp()
108
+ path = os.path.join(temp_dir, filename)
109
  with open(path, 'w') as f:
110
  json.dump(data, f, indent=4)
111
  return path
 
113
  def load_character(file):
114
  """Loads UI values from a JSON file."""
115
  if file is None:
116
+ return [gr.update()] * (1 + len(FEATURE_SEQUENCE) * 2 + len(SECTIONS))
117
 
118
  try:
119
  file_path = file.name if hasattr(file, 'name') else file
 
121
  data = json.load(f)
122
 
123
  updates = []
124
+ # Update name
125
+ updates.append(data.get("name", "Unnamed Hero"))
126
+
127
  # Update dropdowns
128
  for _, _, t_key in FEATURE_SEQUENCE:
129
  updates.append(data.get("features", {}).get(t_key, gr.update()))
 
139
  return updates
140
  except Exception as e:
141
  print(f"Error loading character: {e}")
142
+ return [gr.update()] * (1 + len(FEATURE_SEQUENCE) * 2 + len(SECTIONS))
143
 
144
  def get_example_list():
145
  """Returns a list of JSON filenames in the examples directory."""
 
150
  def load_example_character(filename):
151
  """Loads a character config from the examples directory."""
152
  if not filename:
153
+ return [gr.update()] * (1 + len(FEATURE_SEQUENCE) * 2 + len(SECTIONS))
154
 
155
  path = os.path.join(EXAMPLES_DIR, filename)
156
  return load_character(path)
modules/integrations.py CHANGED
@@ -10,6 +10,7 @@ import random
10
  import traceback
11
  import tempfile
12
  from PIL import Image
 
13
  from huggingface_hub import InferenceClient
14
  from google import genai
15
  from google.genai import types
@@ -52,11 +53,11 @@ def get_ollama_models():
52
  except Exception:
53
  return []
54
 
55
- def refine_with_gemini(prompt):
56
  if not gemini_active:
57
  return "Gemini API key not found in .env file."
58
 
59
- system_prompt = load_system_prompt("refinement")
60
  if not system_prompt:
61
  system_prompt = (
62
  "You are an expert prompt engineer for AI image generators. "
@@ -77,9 +78,9 @@ def refine_with_gemini(prompt):
77
  except Exception as e:
78
  return f"Error refining prompt with Gemini: {e}"
79
 
80
- def refine_with_ollama(prompt, model):
81
  """Refines the prompt using a local Ollama instance."""
82
- system_prompt = load_system_prompt("refinement")
83
  url = f"http://{OLLAMA_HOST}:{OLLAMA_PORT}/api/generate"
84
 
85
  payload = {
@@ -102,13 +103,13 @@ def refine_with_ollama(prompt, model):
102
  except Exception as e:
103
  return f"Error refining prompt with Ollama: {e}"
104
 
105
- def refine_with_hf(prompt, token=None):
106
  """Refines the prompt using Hugging Face Inference API."""
107
  active_token = token if token else HF_TOKEN
108
  if not active_token:
109
  return "Error: Hugging Face token not found. Please log in or provide a token."
110
 
111
- system_prompt = load_system_prompt("refinement")
112
  model_id = HF_TEXT_MODEL
113
 
114
  try:
@@ -128,26 +129,36 @@ def refine_with_hf(prompt, token=None):
128
  except Exception as e:
129
  return f"Hugging Face Error: {e}"
130
 
131
- def refine_master(prompt, backend, ollama_model, manual_token=None, oauth_token=None):
132
- """Routes prompt refinement to the selected backend. oauth_token can be a gr.OAuthToken or None."""
133
  if not prompt.strip():
134
  return ""
135
 
136
- # Prioritizes manual token, then OAuth token if available
137
- hf_token = None
138
- if manual_token and manual_token.strip():
139
- hf_token = manual_token.strip()
140
- elif oauth_token and hasattr(oauth_token, 'token'):
141
- hf_token = oauth_token.token
142
 
143
  if backend == "Ollama (Local)":
144
- return refine_with_ollama(prompt, ollama_model)
145
  elif backend == "Hugging Face (Cloud)":
146
- return refine_with_hf(prompt, hf_token)
147
  else:
148
- return refine_with_gemini(prompt)
149
 
150
- def generate_image_with_gemini(refined_prompt, technical_prompt, aspect_ratio):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  if not gemini_active:
152
  return None, None, "Gemini API key not found in .env file."
153
 
@@ -167,16 +178,25 @@ def generate_image_with_gemini(refined_prompt, technical_prompt, aspect_ratio):
167
  )
168
  if response.generated_images:
169
  img = Image.open(io.BytesIO(response.generated_images[0].image.image_bytes))
 
 
 
 
 
 
 
 
 
170
  temp_dir = tempfile.mkdtemp()
171
- img_path = os.path.join(temp_dir, "rpg_portrait.png")
172
- img.save(img_path, "PNG")
173
  return img, img_path, f"Image generated using {'refined' if refined_prompt.strip() else 'technical'} prompt!"
174
  return None, None, "Gemini Image generation did not return any images."
175
  except Exception as e:
176
  traceback.print_exc()
177
  return None, None, f"Image Generation Error: {e}"
178
 
179
- def generate_image_with_comfy(prompt, aspect_ratio):
180
  """Generates an image using a local ComfyUI instance."""
181
  if not os.path.exists(COMFY_WORKFLOW_FILE):
182
  return None, None, f"Error: Workflow file {COMFY_WORKFLOW_FILE} not found."
@@ -221,9 +241,18 @@ def generate_image_with_comfy(prompt, aspect_ratio):
221
  img_resp.raise_for_status()
222
 
223
  img = Image.open(io.BytesIO(img_resp.content))
 
 
 
 
 
 
 
 
 
224
  temp_dir = tempfile.mkdtemp()
225
- img_path = os.path.join(temp_dir, "rpg_portrait_comfy.png")
226
- img.save(img_path, "PNG")
227
  return img, img_path, f"Image generated via ComfyUI!"
228
  time.sleep(1)
229
 
@@ -233,7 +262,7 @@ def generate_image_with_comfy(prompt, aspect_ratio):
233
  traceback.print_exc()
234
  return None, None, f"ComfyUI Error: {e}"
235
 
236
- def generate_image_with_hf(prompt, aspect_ratio, token=None):
237
  """Generates an image using Hugging Face Inference API."""
238
  active_token = token if token else HF_TOKEN
239
  if not active_token:
@@ -246,28 +275,32 @@ def generate_image_with_hf(prompt, aspect_ratio, token=None):
246
  client = InferenceClient(api_key=active_token)
247
  img = client.text_to_image(final_prompt, model=model_id)
248
 
 
 
 
 
 
 
 
 
249
  temp_dir = tempfile.mkdtemp()
250
- img_path = os.path.join(temp_dir, "rpg_portrait_hf.png")
251
- img.save(img_path, "PNG")
252
  return img, img_path, f"Image generated via Hugging Face ({model_id})!"
253
  except Exception as e:
254
  traceback.print_exc()
255
  return None, None, f"Hugging Face Image Error: {e}"
256
 
257
- def generate_image_master(refined_prompt, technical_prompt, aspect_ratio, backend, manual_token=None, oauth_token=None):
258
- """Routes image generation to the selected backend. oauth_token can be a gr.OAuthToken or None."""
259
  final_prompt = refined_prompt.strip() if refined_prompt.strip() else technical_prompt
260
 
261
- # Prioritize manual token, then OAuth token if available
262
- hf_token = None
263
- if manual_token and manual_token.strip():
264
- hf_token = manual_token.strip()
265
- elif oauth_token and hasattr(oauth_token, 'token'):
266
- hf_token = oauth_token.token
267
 
268
  if backend == "ComfyUI (Local)":
269
- return generate_image_with_comfy(final_prompt, aspect_ratio)
270
  elif backend == "Hugging Face (Cloud)":
271
- return generate_image_with_hf(final_prompt, aspect_ratio, hf_token)
272
  else:
273
- return generate_image_with_gemini(refined_prompt, technical_prompt, aspect_ratio)
 
10
  import traceback
11
  import tempfile
12
  from PIL import Image
13
+ from PIL.PngImagePlugin import PngInfo
14
  from huggingface_hub import InferenceClient
15
  from google import genai
16
  from google.genai import types
 
53
  except Exception:
54
  return []
55
 
56
+ def refine_with_gemini(prompt, mode="refinement"):
57
  if not gemini_active:
58
  return "Gemini API key not found in .env file."
59
 
60
+ system_prompt = load_system_prompt(mode)
61
  if not system_prompt:
62
  system_prompt = (
63
  "You are an expert prompt engineer for AI image generators. "
 
78
  except Exception as e:
79
  return f"Error refining prompt with Gemini: {e}"
80
 
81
+ def refine_with_ollama(prompt, model, mode="refinement"):
82
  """Refines the prompt using a local Ollama instance."""
83
+ system_prompt = load_system_prompt(mode)
84
  url = f"http://{OLLAMA_HOST}:{OLLAMA_PORT}/api/generate"
85
 
86
  payload = {
 
103
  except Exception as e:
104
  return f"Error refining prompt with Ollama: {e}"
105
 
106
+ def refine_with_hf(prompt, token=None, mode="refinement"):
107
  """Refines the prompt using Hugging Face Inference API."""
108
  active_token = token if token else HF_TOKEN
109
  if not active_token:
110
  return "Error: Hugging Face token not found. Please log in or provide a token."
111
 
112
+ system_prompt = load_system_prompt(mode)
113
  model_id = HF_TEXT_MODEL
114
 
115
  try:
 
129
  except Exception as e:
130
  return f"Hugging Face Error: {e}"
131
 
132
+ def refine_master(prompt, backend, ollama_model, manual_token=None, character_name=None):
133
+ """Routes prompt refinement to the selected backend."""
134
  if not prompt.strip():
135
  return ""
136
 
137
+ # Prioritizes manual token
138
+ hf_token = manual_token.strip() if manual_token and manual_token.strip() else None
 
 
 
 
139
 
140
  if backend == "Ollama (Local)":
141
+ return refine_with_ollama(prompt, ollama_model, mode="refinement")
142
  elif backend == "Hugging Face (Cloud)":
143
+ return refine_with_hf(prompt, hf_token, mode="refinement")
144
  else:
145
+ return refine_with_gemini(prompt, mode="refinement")
146
 
147
+ def generate_name_master(prompt, backend, ollama_model, manual_token=None):
148
+ """Generates a thematic name based on the current prompt context."""
149
+ if not prompt.strip():
150
+ return "Unnamed Hero"
151
+
152
+ hf_token = manual_token.strip() if manual_token and manual_token.strip() else None
153
+
154
+ if backend == "Ollama (Local)":
155
+ return refine_with_ollama(prompt, ollama_model, mode="naming")
156
+ elif backend == "Hugging Face (Cloud)":
157
+ return refine_with_hf(prompt, hf_token, mode="naming")
158
+ else:
159
+ return refine_with_gemini(prompt, mode="naming")
160
+
161
+ def generate_image_with_gemini(refined_prompt, technical_prompt, aspect_ratio, character_name="Unnamed Hero"):
162
  if not gemini_active:
163
  return None, None, "Gemini API key not found in .env file."
164
 
 
178
  )
179
  if response.generated_images:
180
  img = Image.open(io.BytesIO(response.generated_images[0].image.image_bytes))
181
+
182
+ # Embed metadata
183
+ metadata = PngInfo()
184
+ metadata.add_text("Comment", final_prompt)
185
+ metadata.add_text("CharacterName", character_name)
186
+
187
+ safe_name = "".join([c if c.isalnum() else "_" for c in character_name]).strip("_")
188
+ filename = f"{safe_name}_portrait_gemini.png" if safe_name else "rpg_portrait_gemini.png"
189
+
190
  temp_dir = tempfile.mkdtemp()
191
+ img_path = os.path.join(temp_dir, filename)
192
+ img.save(img_path, "PNG", pnginfo=metadata)
193
  return img, img_path, f"Image generated using {'refined' if refined_prompt.strip() else 'technical'} prompt!"
194
  return None, None, "Gemini Image generation did not return any images."
195
  except Exception as e:
196
  traceback.print_exc()
197
  return None, None, f"Image Generation Error: {e}"
198
 
199
+ def generate_image_with_comfy(prompt, aspect_ratio, character_name="Unnamed Hero"):
200
  """Generates an image using a local ComfyUI instance."""
201
  if not os.path.exists(COMFY_WORKFLOW_FILE):
202
  return None, None, f"Error: Workflow file {COMFY_WORKFLOW_FILE} not found."
 
241
  img_resp.raise_for_status()
242
 
243
  img = Image.open(io.BytesIO(img_resp.content))
244
+
245
+ # Embed metadata
246
+ metadata = PngInfo()
247
+ metadata.add_text("Comment", prompt)
248
+ metadata.add_text("CharacterName", character_name)
249
+
250
+ safe_name = "".join([c if c.isalnum() else "_" for c in character_name]).strip("_")
251
+ filename = f"{safe_name}_portrait_comfy.png" if safe_name else "rpg_portrait_comfy.png"
252
+
253
  temp_dir = tempfile.mkdtemp()
254
+ img_path = os.path.join(temp_dir, filename)
255
+ img.save(img_path, "PNG", pnginfo=metadata)
256
  return img, img_path, f"Image generated via ComfyUI!"
257
  time.sleep(1)
258
 
 
262
  traceback.print_exc()
263
  return None, None, f"ComfyUI Error: {e}"
264
 
265
+ def generate_image_with_hf(prompt, aspect_ratio, token=None, character_name="Unnamed Hero"):
266
  """Generates an image using Hugging Face Inference API."""
267
  active_token = token if token else HF_TOKEN
268
  if not active_token:
 
275
  client = InferenceClient(api_key=active_token)
276
  img = client.text_to_image(final_prompt, model=model_id)
277
 
278
+ # Embed metadata
279
+ metadata = PngInfo()
280
+ metadata.add_text("Comment", final_prompt)
281
+ metadata.add_text("CharacterName", character_name)
282
+
283
+ safe_name = "".join([c if c.isalnum() else "_" for c in character_name]).strip("_")
284
+ filename = f"{safe_name}_portrait_hf.png" if safe_name else "rpg_portrait_hf.png"
285
+
286
  temp_dir = tempfile.mkdtemp()
287
+ img_path = os.path.join(temp_dir, filename)
288
+ img.save(img_path, "PNG", pnginfo=metadata)
289
  return img, img_path, f"Image generated via Hugging Face ({model_id})!"
290
  except Exception as e:
291
  traceback.print_exc()
292
  return None, None, f"Hugging Face Image Error: {e}"
293
 
294
+ def generate_image_master(refined_prompt, technical_prompt, aspect_ratio, backend, manual_token=None, character_name="Unnamed Hero"):
295
+ """Routes image generation to the selected backend."""
296
  final_prompt = refined_prompt.strip() if refined_prompt.strip() else technical_prompt
297
 
298
+ # Prioritizes manual token
299
+ hf_token = manual_token.strip() if manual_token and manual_token.strip() else None
 
 
 
 
300
 
301
  if backend == "ComfyUI (Local)":
302
+ return generate_image_with_comfy(final_prompt, aspect_ratio, character_name)
303
  elif backend == "Hugging Face (Cloud)":
304
+ return generate_image_with_hf(final_prompt, aspect_ratio, hf_token, character_name)
305
  else:
306
+ return generate_image_with_gemini(refined_prompt, technical_prompt, aspect_ratio, character_name)
modules/name_generator.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import fictional_names.tolkien as tolkien
3
+ import fictional_names.viking as viking
4
+ import fictional_names.rowling as rowling
5
+
6
+ def generate_fantasy_name(race, gender=None):
7
+ """Generates a random fantasy name based on race using fictional-names library data."""
8
+
9
+ race = race.lower()
10
+
11
+ # Mapping our app's races to library components
12
+ if "human" in race:
13
+ # Use full names for humans as they are already diverse
14
+ source = viking
15
+ elif any(r in race for r in ["elf", "elven"]):
16
+ # Tolkien elven feel
17
+ source = tolkien
18
+ elif "dwarf" in race:
19
+ # Tolkien dwarven feel
20
+ source = tolkien
21
+ elif "orc" in race:
22
+ # Tolkien orcish feel
23
+ source = tolkien
24
+ elif any(r in race for r in ["tiefling", "dragonborn"]):
25
+ # Rowling components have a more exotic/latinate feel
26
+ source = rowling
27
+ else:
28
+ # Default fallback
29
+ source = tolkien
30
+
31
+ # Decide gender list
32
+ if gender and gender.lower() == "female":
33
+ prefixes = source.female_prefix
34
+ suffixes = source.female_suffix
35
+ names = source.female_names
36
+ elif gender and gender.lower() == "male":
37
+ prefixes = source.male_prefix
38
+ suffixes = source.male_suffix
39
+ names = source.male_names
40
+ else:
41
+ # Combine both for 'any'
42
+ prefixes = source.male_prefix + source.female_prefix
43
+ suffixes = source.male_suffix + source.female_suffix
44
+ names = source.male_names + source.female_names
45
+
46
+ # Use a mix of full names and generated ones for maximum variety
47
+ if random.random() > 0.4 and names:
48
+ first_name = random.choice(names)
49
+ else:
50
+ # Generate from syllables
51
+ prefix = random.choice(prefixes) if prefixes else "Al"
52
+ suffix = random.choice(suffixes) if suffixes else "en"
53
+ first_name = (prefix + suffix).capitalize()
54
+
55
+ # Surnames (if available in the source)
56
+ surname = ""
57
+ if hasattr(source, "surnames") and random.random() > 0.3:
58
+ surname = random.choice(source.surnames)
59
+
60
+ if surname:
61
+ return f"{first_name} {surname}"
62
+
63
+ return first_name
modules/ui_layout.py CHANGED
@@ -7,6 +7,7 @@ from .core_logic import (
7
  from .integrations import (
8
  get_ollama_models, refine_master, generate_image_master
9
  )
 
10
 
11
  def build_ui():
12
  with gr.Blocks(title="Chronicle Portrait Studio") as demo:
@@ -28,13 +29,17 @@ def build_ui():
28
  cb = gr.Checkbox(label="🎲", value=False, scale=1, min_width=50, container=False)
29
  dropdowns.append(dd)
30
  checkboxes.append(cb)
 
31
 
32
  with gr.Row():
33
  with gr.Column(scale=2):
34
  with gr.Tabs():
35
  with gr.TabItem("👤 Identity & Expression"):
36
  gr.Markdown("### 👤 Identity")
37
- create_feature_ui('identity', 'race', "Race", "Human")
 
 
 
38
  create_feature_ui('identity', 'class', "Class", "Fighter")
39
  create_feature_ui('identity', 'gender', "Gender", "Male")
40
  create_feature_ui('identity', 'age', "Age", "Young Adult")
@@ -139,9 +144,9 @@ def build_ui():
139
 
140
  with gr.Column(scale=1):
141
  gr.Markdown("### 📝 Prompts & Output")
142
- prompt_output = gr.Textbox(label="Generated Technical Prompt", lines=4, interactive=False)
143
  regenerate_btn = gr.Button("✨ Randomize Features", variant="secondary")
144
- refined_output = gr.Textbox(label="Refined Artistic Prompt", lines=6, interactive=True)
145
 
146
  gr.Markdown("---")
147
  image_output = gr.Image(label="Portrait", show_label=False)
@@ -149,7 +154,7 @@ def build_ui():
149
  status_msg = gr.Markdown("")
150
  download_file = gr.File(label="Saved Character JSON", visible=False)
151
 
152
- all_input_components = dropdowns + extra_texts
153
 
154
  for comp in all_input_components:
155
  comp.change(fn=generate_prompt, inputs=all_input_components, outputs=prompt_output)
@@ -167,15 +172,21 @@ def build_ui():
167
  outputs=refined_output
168
  )
169
 
 
 
 
 
 
 
170
  refine_btn.click(
171
  fn=refine_master,
172
- inputs=[prompt_output, refinement_backend, ollama_model_dropdown, hf_token_input],
173
  outputs=refined_output
174
  )
175
 
176
  gen_img_btn.click(
177
  fn=generate_image_master,
178
- inputs=[refined_output, prompt_output, dropdowns[-1], backend_selector, hf_token_input],
179
  outputs=[image_output, download_img_btn, status_msg]
180
  ).then(
181
  fn=lambda x: gr.update(value=x, visible=True) if x else gr.update(visible=False),
@@ -191,7 +202,7 @@ def build_ui():
191
 
192
  save_btn.click(
193
  fn=save_character,
194
- inputs=dropdowns + checkboxes + extra_texts,
195
  outputs=download_file
196
  ).then(
197
  fn=lambda: gr.update(visible=True),
@@ -201,7 +212,7 @@ def build_ui():
201
  load_btn.upload(
202
  fn=load_character,
203
  inputs=load_btn,
204
- outputs=dropdowns + checkboxes + extra_texts
205
  ).then(
206
  fn=generate_prompt,
207
  inputs=all_input_components,
@@ -211,7 +222,7 @@ def build_ui():
211
  load_example_btn.click(
212
  fn=load_example_character,
213
  inputs=example_dropdown,
214
- outputs=dropdowns + checkboxes + extra_texts
215
  ).then(
216
  fn=generate_prompt,
217
  inputs=all_input_components,
 
7
  from .integrations import (
8
  get_ollama_models, refine_master, generate_image_master
9
  )
10
+ from .name_generator import generate_fantasy_name
11
 
12
  def build_ui():
13
  with gr.Blocks(title="Chronicle Portrait Studio") as demo:
 
29
  cb = gr.Checkbox(label="🎲", value=False, scale=1, min_width=50, container=False)
30
  dropdowns.append(dd)
31
  checkboxes.append(cb)
32
+ return dd, cb
33
 
34
  with gr.Row():
35
  with gr.Column(scale=2):
36
  with gr.Tabs():
37
  with gr.TabItem("👤 Identity & Expression"):
38
  gr.Markdown("### 👤 Identity")
39
+ with gr.Row():
40
+ character_name = gr.Textbox(label="Character Name", placeholder="Enter name...", value="Unnamed Hero", scale=9)
41
+ name_gen_btn = gr.Button("🎲", scale=1, variant="secondary")
42
+ race_dd, _ = create_feature_ui('identity', 'race', "Race", "Human")
43
  create_feature_ui('identity', 'class', "Class", "Fighter")
44
  create_feature_ui('identity', 'gender', "Gender", "Male")
45
  create_feature_ui('identity', 'age', "Age", "Young Adult")
 
144
 
145
  with gr.Column(scale=1):
146
  gr.Markdown("### 📝 Prompts & Output")
147
+ prompt_output = gr.Textbox(label="Generated Technical Prompt", lines=4, interactive=False, buttons=["copy"])
148
  regenerate_btn = gr.Button("✨ Randomize Features", variant="secondary")
149
+ refined_output = gr.Textbox(label="Refined Artistic Prompt", lines=6, interactive=True, buttons=["copy", "paste", "clear"])
150
 
151
  gr.Markdown("---")
152
  image_output = gr.Image(label="Portrait", show_label=False)
 
154
  status_msg = gr.Markdown("")
155
  download_file = gr.File(label="Saved Character JSON", visible=False)
156
 
157
+ all_input_components = [character_name] + dropdowns + checkboxes + extra_texts
158
 
159
  for comp in all_input_components:
160
  comp.change(fn=generate_prompt, inputs=all_input_components, outputs=prompt_output)
 
172
  outputs=refined_output
173
  )
174
 
175
+ name_gen_btn.click(
176
+ fn=lambda r: generate_fantasy_name(r),
177
+ inputs=[race_dd],
178
+ outputs=character_name
179
+ )
180
+
181
  refine_btn.click(
182
  fn=refine_master,
183
+ inputs=[prompt_output, refinement_backend, ollama_model_dropdown, hf_token_input, character_name],
184
  outputs=refined_output
185
  )
186
 
187
  gen_img_btn.click(
188
  fn=generate_image_master,
189
+ inputs=[refined_output, prompt_output, dropdowns[-1], backend_selector, hf_token_input, character_name],
190
  outputs=[image_output, download_img_btn, status_msg]
191
  ).then(
192
  fn=lambda x: gr.update(value=x, visible=True) if x else gr.update(visible=False),
 
202
 
203
  save_btn.click(
204
  fn=save_character,
205
+ inputs=all_input_components,
206
  outputs=download_file
207
  ).then(
208
  fn=lambda: gr.update(visible=True),
 
212
  load_btn.upload(
213
  fn=load_character,
214
  inputs=load_btn,
215
+ outputs=all_input_components
216
  ).then(
217
  fn=generate_prompt,
218
  inputs=all_input_components,
 
222
  load_example_btn.click(
223
  fn=load_example_character,
224
  inputs=example_dropdown,
225
+ outputs=all_input_components
226
  ).then(
227
  fn=generate_prompt,
228
  inputs=all_input_components,
prompts.yaml CHANGED
@@ -1,7 +1,13 @@
1
  refinement:
2
- system_instructions: >
3
- You are an expert prompt engineer for AI image generators.
4
- Your task is to take the provided technical prompt and refine it into a more vivid,
5
- artistic, and detailed description while maintaining all the core features.
6
- Enhance the vocabulary, lighting, and textures to be professional quality.
 
 
 
 
 
 
7
  IMPORTANT: RETURN ONLY THE REFINED PROMPT TEXT. DO NOT INCLUDE ANY CONVERSATIONAL FILLER, MARKDOWN CODE BLOCKS, OR EXPLANATIONS.
 
1
  refinement:
2
+ system_instructions: |
3
+ You are an expert fantasy writer and RPG game master.
4
+ Refine the given technical character description into a vivid, evocative, and detailed artistic prompt for an image generator.
5
+ The output should be a single paragraph of descriptive prose, rich in sensory details, focusing on visual appearance, lighting, and mood.
6
+ Do not use placeholders. Do not include technical camera settings unless they are part of the artistic style.
7
+
8
+ naming:
9
+ system_instructions: |
10
+ You are a creative writer specialized in fantasy and RPG character naming.
11
+ Based on the character's race, class, and attributes, generate ONE single evocative and thematic name.
12
+ Return ONLY the name. No explanation, no titles, no extra words.
13
  IMPORTANT: RETURN ONLY THE REFINED PROMPT TEXT. DO NOT INCLUDE ANY CONVERSATIONAL FILLER, MARKDOWN CODE BLOCKS, OR EXPLANATIONS.
requirements.txt CHANGED
@@ -5,3 +5,4 @@ google-genai
5
  requests
6
  Pillow
7
  huggingface_hub
 
 
5
  requests
6
  Pillow
7
  huggingface_hub
8
+ fictional-names
walkthrough.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Portfolio: Chronicle Portrait Studio Final Polish
2
+
3
+ The latest updates transform the RPGPortrait studio into a fully-fledged character management tool with a focus on workflow and portability.
4
+
5
+ ## ✨ Highlights
6
+
7
+ ### 👤 Character Identity & Auto-Naming
8
+ We've moved beyond generic portraits. You can now define a **Character Name** which acts as the anchor for your creation:
9
+ - **🎲 Instant Naming**: A new dice button next to the name field generates thematic fantasy names instantly.
10
+ - **Zero Latency**: Powered by a local procedural generator using the `fictional-names` library—no API tokens required.
11
+
12
+ ### 📥 Named Downloads & Portability
13
+ Saving your work is now smarter:
14
+ - **Automatic Filenames**: Portraits and data files are saved with your character's name (e.g., `Gildur_portrait_gemini.png`).
15
+ - **Embedded Metadata**: Your generation prompts and character names are **embedded directly inside the PNG file**. You can view them in any image viewer with metadata support (like Windows Properties > Details).
16
+
17
+ ### 📋 UI Workflow Improvements
18
+ - **Clipboard Sync**: Added native "Copy" buttons to all prompt outputs for quick sharing.
19
+ - **Robustness**: Implemented a background "UI Head-Check" to ensure the interface is always stable and error-free.
20
+
21
+ ---
22
+
23
+ ## 🛠️ Technical Implementation
24
+ - **Library**: Switched to `fictional-names` for high-quality, race-specific naming conventions (Tolkien, Viking, etc.).
25
+ - **Metadata**: Leveraged `Pillow`'s `PngInfo` to inject context without bloating file size.
26
+ - **Modular Fixes**: Refactored the internal logic to ensure the character name propagates from the UI all the way to the final disk write.
27
+
28
+ **Happy Portrait Crafting!** ⚔️🛡️