PSNbst commited on
Commit
88aafac
·
verified ·
1 Parent(s): 8b7a80b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -28
app.py CHANGED
@@ -1,5 +1,6 @@
1
  import gradio as gr
2
  import random
 
3
  import os
4
  from openai import OpenAI
5
  from dotenv import load_dotenv
@@ -13,7 +14,7 @@ ITEMS = ["magic wand", "sword", "flower", "book of spells", "ancient scroll", "m
13
  OTHER_DETAILS = ["sparkles", "magical aura", "lens flare", "fireworks in the background"]
14
  SCENES = ["sunset beach", "rainy city street at night", "fantasy forest with glowing mushrooms", "futuristic skyline at dawn"]
15
  CAMERA_ANGLES = ["low-angle shot", "close-up shot", "bird's-eye view", "wide-angle shot"]
16
- QUALITY_PROMPTS = ["8k", "ultra-realistic", "high detail", "cinematic lighting", "award-winning"]
17
 
18
  # ========== 工具函数 ==========
19
  def load_candidates_from_files(files):
@@ -23,7 +24,6 @@ def load_candidates_from_files(files):
23
  all_lines = []
24
  if files:
25
  for file in files:
26
- # Gradio 的 Files 返回文件路径
27
  if isinstance(file, str):
28
  with open(file, "r", encoding="utf-8") as f:
29
  all_lines.extend([line.strip() for line in f if line.strip()])
@@ -35,56 +35,70 @@ def get_random_item(candidates):
35
  """
36
  return random.choice(candidates) if candidates else ""
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  def generate_natural_language_description(tags, api_key=None):
39
  """
40
- 使用 OpenAI GPT 生成自然语言描述(适配 GPT-4o)。
41
  """
42
- # 如果用户未输入 API Key,则尝试从环境变量获取
43
  if not api_key:
44
  api_key = os.getenv("OPENAI_API_KEY")
45
  if not api_key:
46
  return "Error: No API Key provided and none found in environment variables."
47
 
 
 
48
  try:
49
- # 初始化 OpenAI 客户端
50
  client = OpenAI(api_key=api_key)
51
 
52
- # 调用 chat.completions.create
53
  response = client.chat.completions.create(
54
  messages=[
55
  {
56
  "role": "system",
57
  "content": (
58
- "You are a helpful assistant that generates creative painting/prompt descriptions. "
59
- "Write at least three sentences in English, separated by periods."
 
60
  ),
61
  },
62
  {
63
  "role": "user",
64
- "content": f"Here are the tags: {tags}\nPlease generate a vivid, imaginative scene description.",
65
  },
66
  ],
67
  model="gpt-4o",
68
  )
69
- generated_content = response.choices[0].message.content.strip()
70
- return generated_content
71
  except Exception as e:
72
  return f"GPT generation failed. Error: {e}"
73
 
74
- def generate_prompt(action_file, style_file, artist_files, character_files, api_key, selected_categories):
75
  """
76
  生成随机提示词和描述。
77
  """
78
- # 从文件加载候选项
79
  actions = load_candidates_from_files([action_file]) if action_file else []
80
  styles = load_candidates_from_files([style_file]) if style_file else []
81
  artists = load_candidates_from_files(artist_files) if artist_files else []
82
  characters = load_candidates_from_files(character_files) if character_files else []
 
83
 
84
- # 确定角色类型
85
  number_of_characters = ", ".join(selected_categories) if selected_categories else random.choice(["1girl", "1boy"])
86
 
87
- # 随机生成提示词
88
  tags = {
89
  "number_of_characters": number_of_characters,
90
  "character_name": get_random_item(characters),
@@ -97,15 +111,15 @@ def generate_prompt(action_file, style_file, artist_files, character_files, api_
97
  "items": get_random_item(ITEMS),
98
  "other_details": get_random_item(OTHER_DETAILS),
99
  "quality_prompts": get_random_item(QUALITY_PROMPTS),
 
100
  }
101
 
102
- # 生成描述
103
  description = generate_natural_language_description(tags, api_key)
104
 
105
- # 返回结果
106
  tags_list = [value for value in tags.values() if value]
107
- final_tags = ", ".join(tags_list)
108
- combined_output = f"{final_tags}\n {description}"
 
109
  return final_tags, description, combined_output
110
 
111
  # ========== Gradio 界面 ==========
@@ -116,41 +130,39 @@ def gradio_interface():
116
  with gr.Blocks() as demo:
117
  gr.Markdown("## Random Prompt Generator with User-Provided GPT API Key")
118
 
119
- # API Key 输入区
120
  api_key_input = gr.Textbox(
121
- label="Enter your OpenAI API Key (Optional) 请输入你充值好了的GPT的API不然不好使",
122
  placeholder="sk-...",
123
  type="password"
124
  )
125
 
126
- # 文件上传
127
  with gr.Row():
128
  action_file = gr.File(label="Upload Action File (Optional)", file_types=[".txt"])
129
  style_file = gr.File(label="Upload Style File (Optional)", file_types=[".txt"])
130
-
131
  with gr.Row():
132
  artist_files = gr.Files(label="Upload Artist Files (Multiple Allowed)", file_types=[".txt"])
133
  character_files = gr.Files(label="Upload Character Files (Multiple Allowed)", file_types=[".txt"])
134
 
135
- # 角色类型选择
 
136
  selected_categories = gr.CheckboxGroup(
137
  ["1boy", "1girl", "furry", "mecha", "fantasy monster", "animal", "still life"],
138
  label="Choose Character Categories (Optional)"
139
  )
140
 
141
- # 输出区域
142
  with gr.Row():
143
  tags_output = gr.Textbox(label="Generated Tags")
144
  description_output = gr.Textbox(label="Generated Description")
145
  combined_output = gr.Textbox(label="Combined Output: Tags + Description")
146
 
147
- # 按钮
148
  generate_button = gr.Button("Generate Prompt")
149
 
150
- # 按钮动作
151
  generate_button.click(
152
  generate_prompt,
153
- inputs=[action_file, style_file, artist_files, character_files, api_key_input, selected_categories],
 
 
154
  outputs=[tags_output, description_output, combined_output],
155
  )
156
 
 
1
  import gradio as gr
2
  import random
3
+ import glob
4
  import os
5
  from openai import OpenAI
6
  from dotenv import load_dotenv
 
14
  OTHER_DETAILS = ["sparkles", "magical aura", "lens flare", "fireworks in the background"]
15
  SCENES = ["sunset beach", "rainy city street at night", "fantasy forest with glowing mushrooms", "futuristic skyline at dawn"]
16
  CAMERA_ANGLES = ["low-angle shot", "close-up shot", "bird's-eye view", "wide-angle shot"]
17
+ QUALITY_PROMPTS = ["8k", "ultra-realistic", "high detail", "cinematic lighting", "award-winning", "masterpiece"]
18
 
19
  # ========== 工具函数 ==========
20
  def load_candidates_from_files(files):
 
24
  all_lines = []
25
  if files:
26
  for file in files:
 
27
  if isinstance(file, str):
28
  with open(file, "r", encoding="utf-8") as f:
29
  all_lines.extend([line.strip() for line in f if line.strip()])
 
35
  """
36
  return random.choice(candidates) if candidates else ""
37
 
38
+ def load_dtr_from_directory(directory=".", pattern="*DTR*"):
39
+ """
40
+ 从指定目录中加载所有包含特定模式的文件内容。
41
+ :param directory: 目标目录,默认为当前目录
42
+ :param pattern: 匹配文件名的模式,默认是包含 "DTR" 的文件
43
+ :return: 文件内容的列表
44
+ """
45
+ dtr_candidates = []
46
+ try:
47
+ files = glob.glob(os.path.join(directory, pattern))
48
+ for file in files:
49
+ with open(file, "r", encoding="utf-8") as f:
50
+ dtr_candidates.extend([line.strip() for line in f if line.strip()])
51
+ except Exception as e:
52
+ print(f"Error loading DTR files: {e}")
53
+ return dtr_candidates
54
+
55
  def generate_natural_language_description(tags, api_key=None):
56
  """
57
+ 使用 OpenAI GPT 生成自然语言描述。
58
  """
 
59
  if not api_key:
60
  api_key = os.getenv("OPENAI_API_KEY")
61
  if not api_key:
62
  return "Error: No API Key provided and none found in environment variables."
63
 
64
+ tag_descriptions = "\n".join([f"{key}: {value}" for key, value in tags.items() if value])
65
+
66
  try:
 
67
  client = OpenAI(api_key=api_key)
68
 
 
69
  response = client.chat.completions.create(
70
  messages=[
71
  {
72
  "role": "system",
73
  "content": (
74
+ "You are a creative assistant that generates vivid and imaginative scene descriptions for painting prompts. "
75
+ "Focus on the details provided and incorporate them into a cohesive narrative. "
76
+ "Use at least three sentences."
77
  ),
78
  },
79
  {
80
  "role": "user",
81
+ "content": f"Here are the tags and details:\n{tag_descriptions}\nPlease generate a vivid, imaginative scene description.",
82
  },
83
  ],
84
  model="gpt-4o",
85
  )
86
+ return response.choices[0].message.content.strip()
 
87
  except Exception as e:
88
  return f"GPT generation failed. Error: {e}"
89
 
90
+ def generate_prompt(action_file, style_file, artist_files, character_files, dtr_directory, api_key, selected_categories):
91
  """
92
  生成随机提示词和描述。
93
  """
 
94
  actions = load_candidates_from_files([action_file]) if action_file else []
95
  styles = load_candidates_from_files([style_file]) if style_file else []
96
  artists = load_candidates_from_files(artist_files) if artist_files else []
97
  characters = load_candidates_from_files(character_files) if character_files else []
98
+ dtr_candidates = load_dtr_from_directory(dtr_directory) if dtr_directory else []
99
 
 
100
  number_of_characters = ", ".join(selected_categories) if selected_categories else random.choice(["1girl", "1boy"])
101
 
 
102
  tags = {
103
  "number_of_characters": number_of_characters,
104
  "character_name": get_random_item(characters),
 
111
  "items": get_random_item(ITEMS),
112
  "other_details": get_random_item(OTHER_DETAILS),
113
  "quality_prompts": get_random_item(QUALITY_PROMPTS),
114
+ "dtr": get_random_item(dtr_candidates)
115
  }
116
 
 
117
  description = generate_natural_language_description(tags, api_key)
118
 
 
119
  tags_list = [value for value in tags.values() if value]
120
+ unique_tags = list(dict.fromkeys(tags_list))
121
+ final_tags = ", ".join(unique_tags)
122
+ combined_output = f"{final_tags}\n\n{description}"
123
  return final_tags, description, combined_output
124
 
125
  # ========== Gradio 界面 ==========
 
130
  with gr.Blocks() as demo:
131
  gr.Markdown("## Random Prompt Generator with User-Provided GPT API Key")
132
 
 
133
  api_key_input = gr.Textbox(
134
+ label="Enter your OpenAI API Key (Optional)",
135
  placeholder="sk-...",
136
  type="password"
137
  )
138
 
 
139
  with gr.Row():
140
  action_file = gr.File(label="Upload Action File (Optional)", file_types=[".txt"])
141
  style_file = gr.File(label="Upload Style File (Optional)", file_types=[".txt"])
142
+
143
  with gr.Row():
144
  artist_files = gr.Files(label="Upload Artist Files (Multiple Allowed)", file_types=[".txt"])
145
  character_files = gr.Files(label="Upload Character Files (Multiple Allowed)", file_types=[".txt"])
146
 
147
+ dtr_enabled = gr.Checkbox(label="Enable DTR Directory")
148
+
149
  selected_categories = gr.CheckboxGroup(
150
  ["1boy", "1girl", "furry", "mecha", "fantasy monster", "animal", "still life"],
151
  label="Choose Character Categories (Optional)"
152
  )
153
 
 
154
  with gr.Row():
155
  tags_output = gr.Textbox(label="Generated Tags")
156
  description_output = gr.Textbox(label="Generated Description")
157
  combined_output = gr.Textbox(label="Combined Output: Tags + Description")
158
 
 
159
  generate_button = gr.Button("Generate Prompt")
160
 
 
161
  generate_button.click(
162
  generate_prompt,
163
+ inputs=[
164
+ action_file, style_file, artist_files, character_files, dtr_enabled, api_key_input, selected_categories
165
+ ],
166
  outputs=[tags_output, description_output, combined_output],
167
  )
168