jiadisu commited on
Commit
c75b16d
Β·
1 Parent(s): dba126e

update prompt

Browse files
Files changed (1) hide show
  1. app.py +80 -56
app.py CHANGED
@@ -10,6 +10,8 @@ Architecture:
10
  """
11
 
12
  import os
 
 
13
 
14
  import gradio as gr
15
  from openai import OpenAI
@@ -20,17 +22,17 @@ OUTPUT_DIR = "/tmp/magihuman_webui_outputs"
20
 
21
  # ── Prompt rewrite via LLM ───────────────────────────────────────────
22
 
23
- _rewrite_client = OpenAI(
24
  base_url="https://apicz.boyuerichdata.com/v1/",
25
  api_key=os.environ.get("REWRITE_API_KEY", ""),
26
  )
27
- _REWRITE_MODEL = "gemini-3-flash-preview"
28
 
29
  _PROMPT_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "prompt.txt")
30
  with open(_PROMPT_FILE, "r") as f:
31
- _REWRITE_SYSTEM_PROMPT = f.read()
32
- print(f"[Rewrite] Loaded system prompt from {os.path.basename(_PROMPT_FILE)}, length={len(_REWRITE_SYSTEM_PROMPT)} chars")
33
- print(f"[Rewrite] System prompt preview: {_REWRITE_SYSTEM_PROMPT[:200]}...")
34
 
35
  def _pil_to_base64_url(image) -> str:
36
  """Convert a PIL Image to a base64 data URL for the vision API."""
@@ -47,7 +49,7 @@ class ContentBlockedError(Exception):
47
  pass
48
 
49
 
50
- def rewrite_prompt(user_prompt: str, image=None) -> str:
51
  """Rewrite user prompt into the model's required format via LLM API.
52
 
53
  Sends both the text prompt and the reference image to the LLM
@@ -55,8 +57,8 @@ def rewrite_prompt(user_prompt: str, image=None) -> str:
55
 
56
  Raises ContentBlockedError if the safety filter blocks the content.
57
  """
58
- print(f"[Rewrite] Starting rewrite, input length={len(user_prompt)} chars, has_image={image is not None}")
59
- print(f"[Rewrite] User prompt: {user_prompt[:100]}...")
60
  try:
61
  # Build user message with text + image
62
  user_content = []
@@ -70,10 +72,10 @@ def rewrite_prompt(user_prompt: str, image=None) -> str:
70
  "text": user_prompt,
71
  })
72
 
73
- resp = _rewrite_client.chat.completions.create(
74
- model=_REWRITE_MODEL,
75
  messages=[
76
- {"role": "system", "content": _REWRITE_SYSTEM_PROMPT},
77
  {"role": "user", "content": user_content},
78
  ],
79
  temperature=0.3,
@@ -82,32 +84,32 @@ def rewrite_prompt(user_prompt: str, image=None) -> str:
82
  choice = resp.choices[0]
83
  raw_content = choice.message.content
84
  finish_reason = choice.finish_reason
85
- print(f"[Rewrite] API returned: finish_reason={finish_reason}, "
86
  f"content_length={len(raw_content) if raw_content else 0}")
87
 
88
  # Check for content filter block
89
  if finish_reason == "content_filter" or not (raw_content or "").strip():
90
- print(f"[Rewrite] Content blocked by safety filter (finish_reason={finish_reason})")
91
  raise ContentBlockedError(
92
  "Your request was blocked by the content safety filter. "
93
  "Please modify your prompt or image and try again."
94
  )
95
 
96
  rewritten = raw_content.strip()
97
- print(f"[Rewrite] Done, output length={len(rewritten)} chars")
98
- print(f"[Rewrite] Rewritten: {rewritten[:150]}...")
99
  return rewritten
100
  except ContentBlockedError:
101
  raise
102
  except Exception as e:
103
  err_str = str(e).lower()
104
  if "block" in err_str or "safety" in err_str or "content" in err_str:
105
- print(f"[Rewrite] Content blocked by API error: {e}")
106
  raise ContentBlockedError(
107
  "Your request was blocked by the content safety filter. "
108
  "Please modify your prompt or image and try again."
109
  )
110
- print(f"[Rewrite] FAILED: {e}, using original prompt")
111
  return user_prompt
112
 
113
 
@@ -115,9 +117,9 @@ def rewrite_prompt(user_prompt: str, image=None) -> str:
115
 
116
 
117
  def run_generation(image, prompt, seed, seconds):
118
- """Validate inputs, rewrite prompt, and send a generation request.
119
 
120
- This is a generator β€” yields intermediate results so the rewritten prompt
121
  appears on the frontend immediately, before video generation finishes.
122
  """
123
  if image is None:
@@ -125,50 +127,83 @@ def run_generation(image, prompt, seed, seconds):
125
  if not prompt or not prompt.strip():
126
  raise gr.Error("Please enter a text prompt.")
127
 
128
- # Step 1: Rewrite prompt via LLM (also acts as content safety gate)
129
  print(f"[Generate] Request received: seed={seed} seconds={seconds} prompt={prompt[:50]!r}")
130
- try:
131
- rewritten = rewrite_prompt(prompt.strip(), image=image)
132
- except ContentBlockedError as e:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  print(f"[Generate] Blocked by content filter, aborting generation")
134
- yield None, "", str(e)
135
  return
136
 
137
- # Yield immediately so the user sees the rewritten prompt + "Generating..."
138
- yield None, rewritten, "Generating video, please wait ..."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
- # Step 2: Send to router
141
  print(f"[Generate] Sending to router ...")
142
- result = generate(
143
- image=image,
144
- video_prompt=rewritten,
145
- seed=int(seed),
146
- output_dir=OUTPUT_DIR,
147
- seconds=int(seconds),
148
- )
 
 
149
 
150
  if result["error"]:
151
  print(f"[Generate] Error from router: {result['error']}")
152
- yield None, rewritten, f"Error: {result['error']}"
153
  return
154
 
155
  video_path = result["video_path"]
156
  if not video_path or not os.path.isfile(video_path):
157
- yield None, rewritten, "Error: Video file not found."
158
  return
159
 
160
- status = f"Done. seed={result['seed']}"
161
  print(f"[Generate] Success: {video_path}")
162
- yield video_path, rewritten, status
163
 
164
 
165
  # ── Gradio UI ────────────────────────────────────────────────────────
166
 
167
  TITLE = "daVinci-MagiHuman β€” Audio-Video Generation"
168
  DESCRIPTION = (
169
- "Upload a reference image, enter a descriptive prompt, choose the video "
170
  "duration (4–10 s), and click **Generate**. Your prompt will be automatically "
171
- "rewritten into the optimal format before generation.\n\n"
172
  "**Model**: 15B single-stream Transformer (distilled, 8-step inference) "
173
  "| **Resolution**: 448Γ—256 β†’ 540p | **FPS**: 25"
174
  )
@@ -184,20 +219,9 @@ with gr.Blocks(title=TITLE, theme=gr.themes.Soft()) as demo:
184
  type="pil",
185
  height=300,
186
  )
187
- _prompt_template = (
188
- 'Prompt format: [Video Description] + [Dialogue] + [Background Sound]\n'
189
- '\n'
190
- '- Use English for the entire prompt (except the spoken text in Dialogue, '
191
- 'which can be in any language).\n'
192
- '- Video Description: Describe the scene, characters, actions, camera angles, etc.\n'
193
- '- Dialogue: <role, language>: "spoken text"\n'
194
- ' e.g. Dialogue: <Little girl in yellow raincoat, English>: "Mommy, look! I made a big splash!"\n'
195
- '- Background Sound: <description of ambient sounds>\n'
196
- ' e.g. Background Sound: <Light rain falling, splashing water, distant suburban ambiance>'
197
- )
198
  prompt_input = gr.Textbox(
199
- label="Prompt",
200
- placeholder=_prompt_template,
201
  lines=6,
202
  )
203
  with gr.Row():
@@ -217,8 +241,8 @@ with gr.Blocks(title=TITLE, theme=gr.themes.Soft()) as demo:
217
 
218
  with gr.Column(scale=1):
219
  video_output = gr.Video(label="Generated Video")
220
- rewritten_prompt_box = gr.Textbox(
221
- label="Rewritten Prompt (sent to model)",
222
  interactive=False,
223
  lines=8,
224
  )
@@ -227,7 +251,7 @@ with gr.Blocks(title=TITLE, theme=gr.themes.Soft()) as demo:
227
  generate_btn.click(
228
  fn=run_generation,
229
  inputs=[image_input, prompt_input, seed_input, seconds_slider],
230
- outputs=[video_output, rewritten_prompt_box, status_box],
231
  )
232
 
233
  if __name__ == "__main__":
 
10
  """
11
 
12
  import os
13
+ import threading
14
+ import time
15
 
16
  import gradio as gr
17
  from openai import OpenAI
 
22
 
23
  # ── Prompt rewrite via LLM ───────────────────────────────────────────
24
 
25
+ _enhance_client = OpenAI(
26
  base_url="https://apicz.boyuerichdata.com/v1/",
27
  api_key=os.environ.get("REWRITE_API_KEY", ""),
28
  )
29
+ _ENHANCE_MODEL = "gemini-3-flash-preview"
30
 
31
  _PROMPT_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "prompt.txt")
32
  with open(_PROMPT_FILE, "r") as f:
33
+ _ENHANCE_SYSTEM_PROMPT = f.read()
34
+ print(f"[Enhance] Loaded system prompt from {os.path.basename(_PROMPT_FILE)}, length={len(_ENHANCE_SYSTEM_PROMPT)} chars")
35
+ print(f"[Enhance] System prompt preview: {_ENHANCE_SYSTEM_PROMPT[:200]}...")
36
 
37
  def _pil_to_base64_url(image) -> str:
38
  """Convert a PIL Image to a base64 data URL for the vision API."""
 
49
  pass
50
 
51
 
52
+ def enhance_prompt(user_prompt: str, image=None) -> str:
53
  """Rewrite user prompt into the model's required format via LLM API.
54
 
55
  Sends both the text prompt and the reference image to the LLM
 
57
 
58
  Raises ContentBlockedError if the safety filter blocks the content.
59
  """
60
+ print(f"[Enhance] Starting rewrite, input length={len(user_prompt)} chars, has_image={image is not None}")
61
+ print(f"[Enhance] User prompt: {user_prompt[:100]}...")
62
  try:
63
  # Build user message with text + image
64
  user_content = []
 
72
  "text": user_prompt,
73
  })
74
 
75
+ resp = _enhance_client.chat.completions.create(
76
+ model=_ENHANCE_MODEL,
77
  messages=[
78
+ {"role": "system", "content": _ENHANCE_SYSTEM_PROMPT},
79
  {"role": "user", "content": user_content},
80
  ],
81
  temperature=0.3,
 
84
  choice = resp.choices[0]
85
  raw_content = choice.message.content
86
  finish_reason = choice.finish_reason
87
+ print(f"[Enhance] API returned: finish_reason={finish_reason}, "
88
  f"content_length={len(raw_content) if raw_content else 0}")
89
 
90
  # Check for content filter block
91
  if finish_reason == "content_filter" or not (raw_content or "").strip():
92
+ print(f"[Enhance] Content blocked by safety filter (finish_reason={finish_reason})")
93
  raise ContentBlockedError(
94
  "Your request was blocked by the content safety filter. "
95
  "Please modify your prompt or image and try again."
96
  )
97
 
98
  rewritten = raw_content.strip()
99
+ print(f"[Enhance] Done, output length={len(rewritten)} chars")
100
+ print(f"[Enhance] Rewritten: {rewritten[:150]}...")
101
  return rewritten
102
  except ContentBlockedError:
103
  raise
104
  except Exception as e:
105
  err_str = str(e).lower()
106
  if "block" in err_str or "safety" in err_str or "content" in err_str:
107
+ print(f"[Enhance] Content blocked by API error: {e}")
108
  raise ContentBlockedError(
109
  "Your request was blocked by the content safety filter. "
110
  "Please modify your prompt or image and try again."
111
  )
112
+ print(f"[Enhance] FAILED: {e}, using original prompt")
113
  return user_prompt
114
 
115
 
 
117
 
118
 
119
  def run_generation(image, prompt, seed, seconds):
120
+ """Validate inputs, enhance prompt, and send a generation request.
121
 
122
+ This is a generator β€” yields intermediate results so the enhanced prompt
123
  appears on the frontend immediately, before video generation finishes.
124
  """
125
  if image is None:
 
127
  if not prompt or not prompt.strip():
128
  raise gr.Error("Please enter a text prompt.")
129
 
130
+ # ── Phase 1: Enhance prompt (with live timer on both boxes) ──
131
  print(f"[Generate] Request received: seed={seed} seconds={seconds} prompt={prompt[:50]!r}")
132
+
133
+ enhance_result = [None] # str | ContentBlockedError
134
+ enhance_done = threading.Event()
135
+
136
+ def _do_enhance():
137
+ try:
138
+ enhance_result[0] = enhance_prompt(prompt.strip(), image=image)
139
+ except ContentBlockedError as e:
140
+ enhance_result[0] = e
141
+ enhance_done.set()
142
+
143
+ threading.Thread(target=_do_enhance, daemon=True).start()
144
+ t0 = time.time()
145
+
146
+ while not enhance_done.wait(timeout=2):
147
+ elapsed = int(time.time() - t0)
148
+ yield None, f"Enhancing prompt ... ({elapsed}s)", f"Waiting for prompt enhancement ... ({elapsed}s)"
149
+
150
+ # Check enhance result
151
+ if isinstance(enhance_result[0], ContentBlockedError):
152
  print(f"[Generate] Blocked by content filter, aborting generation")
153
+ yield None, "", str(enhance_result[0])
154
  return
155
 
156
+ enhanced = enhance_result[0]
157
+
158
+ # ── Phase 2: Generate video (enhanced prompt shown, timer on status) ──
159
+ yield None, enhanced, "Generating video, please wait ... (0s)"
160
+
161
+ gen_result = [None]
162
+ gen_done = threading.Event()
163
+
164
+ def _do_generate():
165
+ gen_result[0] = generate(
166
+ image=image,
167
+ video_prompt=enhanced,
168
+ seed=int(seed),
169
+ output_dir=OUTPUT_DIR,
170
+ seconds=int(seconds),
171
+ )
172
+ gen_done.set()
173
 
 
174
  print(f"[Generate] Sending to router ...")
175
+ threading.Thread(target=_do_generate, daemon=True).start()
176
+ t1 = time.time()
177
+
178
+ while not gen_done.wait(timeout=5):
179
+ elapsed = int(time.time() - t1)
180
+ yield None, enhanced, f"Generating video, please wait ... ({elapsed}s)"
181
+
182
+ result = gen_result[0]
183
+ total = int(time.time() - t0)
184
 
185
  if result["error"]:
186
  print(f"[Generate] Error from router: {result['error']}")
187
+ yield None, enhanced, f"Error: {result['error']}"
188
  return
189
 
190
  video_path = result["video_path"]
191
  if not video_path or not os.path.isfile(video_path):
192
+ yield None, enhanced, "Error: Video file not found."
193
  return
194
 
195
+ status = f"Done in {total}s. seed={result['seed']}"
196
  print(f"[Generate] Success: {video_path}")
197
+ yield video_path, enhanced, status
198
 
199
 
200
  # ── Gradio UI ────────────────────────────────────────────────────────
201
 
202
  TITLE = "daVinci-MagiHuman β€” Audio-Video Generation"
203
  DESCRIPTION = (
204
+ "Upload a reference image, describe what you want in the video, choose the "
205
  "duration (4–10 s), and click **Generate**. Your prompt will be automatically "
206
+ "enhanced into the optimal format before generation.\n\n"
207
  "**Model**: 15B single-stream Transformer (distilled, 8-step inference) "
208
  "| **Resolution**: 448Γ—256 β†’ 540p | **FPS**: 25"
209
  )
 
219
  type="pil",
220
  height=300,
221
  )
 
 
 
 
 
 
 
 
 
 
 
222
  prompt_input = gr.Textbox(
223
+ label="Video Description (will be auto-enhanced)",
224
+ placeholder="Describe the scene, character actions, dialogue, etc. Your prompt will be automatically enhanced for optimal generation.",
225
  lines=6,
226
  )
227
  with gr.Row():
 
241
 
242
  with gr.Column(scale=1):
243
  video_output = gr.Video(label="Generated Video")
244
+ enhanced_prompt_box = gr.Textbox(
245
+ label="Enhanced Prompt (sent to model)",
246
  interactive=False,
247
  lines=8,
248
  )
 
251
  generate_btn.click(
252
  fn=run_generation,
253
  inputs=[image_input, prompt_input, seed_input, seconds_slider],
254
+ outputs=[video_output, enhanced_prompt_box, status_box],
255
  )
256
 
257
  if __name__ == "__main__":