File size: 19,822 Bytes
1e6762b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e82103
ad622f9
1e6762b
6e82103
6b20e72
 
 
c514fd1
91b54d9
1e6762b
6b20e72
c514fd1
6b20e72
c7c3a3c
c514fd1
1e6762b
 
 
76c627a
a5f9d20
e11abed
8083a61
1e6762b
a5f9d20
76c627a
 
91b54d9
 
8083a61
1e6762b
91b54d9
76c627a
922bd17
1e6762b
 
 
 
 
61450e6
1e6762b
 
 
 
61450e6
76c627a
 
91b54d9
 
 
1e6762b
 
76c627a
1e6762b
76c627a
c514fd1
76c627a
c514fd1
91b54d9
76c627a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91b54d9
 
76c627a
91b54d9
76c627a
91b54d9
76c627a
 
91b54d9
76c627a
1e6762b
707436a
76c627a
8083a61
76c627a
 
14d6943
76c627a
8083a61
14d6943
6e82103
76c627a
 
 
 
 
 
91b54d9
76c627a
8083a61
c70c3a9
76c627a
 
c70c3a9
 
 
 
 
 
 
76c627a
 
c70c3a9
76c627a
 
 
8083a61
 
c70c3a9
1e6762b
76c627a
c70c3a9
1e6762b
8083a61
c70c3a9
6b20e72
76c627a
06df4c1
28667ad
06df4c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76c627a
28667ad
 
 
8083a61
 
 
 
28667ad
 
 
76c627a
06df4c1
7155028
 
 
 
 
 
 
 
 
 
 
 
 
 
1e6762b
 
544cd77
1e6762b
 
7155028
1e6762b
 
 
 
9c3622c
922bd17
1e6762b
 
 
 
544cd77
1e6762b
 
 
 
 
 
 
544cd77
1e6762b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
# import streamlit as st
# import re
# from transformers import pipeline
# from diffusers import StableDiffusionPipeline
# from pydub import AudioSegment
# import zipfile
# from io import BytesIO
# import json
# import torch

# # 初始化模型 (全部使用原始pipeline)
# @st.cache_resource
# def load_pipelines():
#     try:
#         # 1. Script generation
#         script_pipe = pipeline(
#             "text2text-generation",
#             model="RUCAIBox/mvp-story",
#             device=0 if torch.cuda.is_available() else -1
#         )

#         # 2. Storyboard generation (BART model)
#         storyboard_pipe = pipeline(
#             "text2text-generation",
#             model="Jessiesj/script_gpt2-story",
#             device=0 if torch.cuda.is_available() else -1
#         )

#         # 3. Soundtrack generation (MusicGen)
#         music_pipe = pipeline(
#             "text-to-audio", 
#             model="facebook/musicgen-small",
#             device_map="auto"
#         )

#         # 4. Storyboard image generation (Stable Diffusion)
#         image_pipe = StableDiffusionPipeline.from_pretrained(
#             "prompthero/openjourney-v4",
#             safety_checker=None,
#             torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
#         )

#         return script_pipe, storyboard_pipe, image_pipe
#         # return script_pipe, storyboard_pipe, music_pipe, image_pipe

#     except Exception as e:
#         st.error(f"Failed to load models: {str(e)}")
#         raise

# # Prompt template
# def build_script_prompt(theme, style_or_opening):
#     return f"""
# {style_or_opening}
# Generate a micro - movie script with two scenes, with the theme: {theme}.
# ### Format requirements (must be strictly followed):
# - Use Markdown syntax
# - Each scene starts with ### Scene X: [Location] (INT/EXT. Time)
# - Include action descriptions (wrapped in square brackets []) and character dialogues

# ### Example:
# ### Scene 1: Spaceship cockpit (INT. Emergency)
# [Alarm lights are flashing wildly, sparks are coming out of the console]
# Captain (shouting): Start the backup engine!
# Co - pilot (typing on the keyboard): The power system has failed!

# ### Scene 2: Alien jungle (EXT. Dusk)
# [The expedition team pushes aside the dense purple bushes]
# Team member A (pointing into the distance): Look! Is that the entrance to the ruins?
# """


# # Content cleaning
# def format_script(text):
#     # Remove invalid symbols
#     text = re.sub(r"[():<>]{2,}", "", text)
#     # Standardize scene titles
#     return re.sub(r"(?<!### )Scene\d+", r"### Scene\g<0>", text)

# # Load pipelines
# script_pipe, storyboard_pipe, image_pipe = load_pipelines()
# # script_pipe, storyboard_pipe, music_pipe, image_pipe = load_pipelines()

# # Streamlit interface
# st.title("🎥 Micro - movie Intelligent Creation System")

# # User input
# user_input = st.text_input(
#     "Enter the movie theme (e.g., Sci - fi space adventure)",
#     help="Recommended format: Genre + Core conflict, example: 'Jungle exploration + Search for the lost golden city'"
# )

# style_or_opening = st.text_input(
#     "Enter the script style or opening",
#     help="Provide a style description or the beginning of the script"
# )

# if user_input and style_or_opening:

#     # 1. Generate the script
#     with st.status("🖋️ Generating the script...", expanded=True) as status:
#         try:
#             # Generate content
#             prompt = build_script_prompt(user_input, style_or_opening)
#             response = script_pipe(
#                 prompt,
#                 max_length=600,
#                 temperature=0.8,
#                 num_beams=4,
#                 no_repeat_ngram_size=3
#             )[0]["generated_text"]

#             # Post - processing
#             def format_script(text):
#                 return text

#             # Display the result
#             st.subheader("Generated Script")
#             cleaned = format_script(response)  # Ensure cleaned is defined here
#             st.markdown(f"```markdown\n{format_script(response)}\n```")
#             status.update(label="✅ Generation completed", state="complete")

#         except Exception as e:
#             status.update(label="❌ Generation failed", status="error")
#             st.error(f"Error details: {str(e)}")
#             st.stop()

#     # 2. Generate the storyboard
#     with st.status("🎥 Converting to storyboard script...", expanded=True) as status:
#         try:
#             # 示例数据模板
#             sample_storyboard = """
#             {
#               "scenes": [
#                 {
#                   "scene_number": 1,
#                   "location": "Abandoned Space Station (INT. Dystopian Future)",
#                   "characters": ["Eve", "R2-D9"],
#                   "camera_angle": "Wide shot showing decaying corridors",
#                   "action": "Eve scans walls with her holographic projector, R2-D9 beeps nervously"
#                 },
#                 {
#                   "scene_number": 2,
#                   "location": "Alien Wasteland (EXT. Toxic Sunset)",
#                   "characters": ["Eve", "Mutant Leader"],
#                   "camera_angle": "Low-angle shot of Eve aiming plasma rifle",
#                   "action": "Mutant leader growls, acid rain hisses on Eve's protective suit"
#                 }
#               ]
#             }
#             """

#             # JSON模板引导
#             json_template = """{
#               "scenes": [
#                 {
#                   "scene_number": 1,
#                   "location": "Scene location (INT/EXT)",
#                   "characters": ["Character 1", "Character 2"],
#                   "camera_angle": "Camera angle",
#                   "action": "Main action description"
#                 }
#               ]
#             }"""

#             # 生成分镜
#             # storyboard = storyboard_pipe(
#             #     f"Convert to storyboard JSON: {cleaned[:800]}",
#             #     max_length=1500,
#             #     temperature=0.3
#             # )[0]["generated_text"]

#             # 增强的格式修复
#             # storyboard = (
#             #     storyboard.replace("'", '"')
#             #     .replace("None", '""')
#             #     .replace("True", "true")
#             #     .replace("False", "false")
#             # )
#             # storyboard = re.search(r'\{.*\}', storyboard, re.DOTALL).group()
#             # parsed = json.loads(storyboard)
#             parsed = json.loads(sample_storyboard)
#         except Exception as e:
#             # st.warning(f"Using sample storyboard due to error: {str(e)}")
#             # parsed = json.loads(sample_storyboard)  # 回退到示例数据
#             # status.update(label="⚠️ Using sample storyboard", status="warning")
#             pass

#         finally:
#         #     status.update(label="Storyboard ready", status="complete")
#         #     st.subheader("Storyboard Script")
#         #     st.json(parsed)
#             # st.caption("*Note: If using sample data, edit the JSON before proceeding*")
#             pass


#     # 3. 生成配乐
#     # with st.spinner("🎵 正在生成配乐..."):
#     #     audio = music_pipe(
#     #         "epic sci-fi background music", 
#     #         max_new_tokens=256
#     #     )
#     #     audio_buffer = BytesIO()
#     #     audio["audio"].export(audio_buffer, format="wav")
    
#     # st.subheader("🎧 背景音乐")
#     # st.audio(audio_buffer, format="audio/wav")

#     # 4. 生成分镜图(可选)
#     # if st.toggle("🎨 生成分镜预览图(需要2-3分钟)"):
#     #         with st.spinner("🖼️ 正在渲染电影级画面..."):
#     #             # 从剧本提取关键描述
#     #             scene_desc = re.search(r"场景\d+:(.*?)\n", script)
#     #             if scene_desc:
#     #                 scene_desc = scene_desc.group(1)
#     #             else:
#     #                 scene_desc = f"movie scene of {user_input}"
                
#     #             # 精细化图片提示词
#     #             image_prompt = f"""电影剧照,{scene_desc},
#     #                 超高清8K分辨率,
#     #                 电影级打光,浅景深效果,
#     #                 Unreal Engine 5渲染,
#     #                 电影胶片颗粒感"""
                
#     #             # 优化生成参数
#     #             image = image_pipe(
#     #                 image_prompt,
#     #                 num_inference_steps=50,
#     #                 guidance_scale=9.5,
#     #                 width=1024,
#     #                 height=576  # 16:9电影比例
#     #             ).images[0]
                
#     #             st.subheader("🎞️ 首场景预览")
#     #             st.image(image, caption=scene_desc)
                
#     # except Exception as e:
#     #     st.error("生成过程中发生错误")
#     #     st.code(f"错误详情:{str(e)}")
#     #     st.button("点击查看技术详情", 
#     #              help="将以下信息提供给技术人员:\n" + str(e))
    
# st.subheader("🎧 Background Music")
# for i, scene in enumerate(parsed["scenes"]):
#     action = scene["action"]
#     with st.spinner(f"🎵 Generating soundtrack for scene {i + 1}..."):
#         try:
#             audio = music_pipe(
#                 action,
#                 max_new_tokens=256
#             )
#             audio_buffer = BytesIO()
#             audio["audio"].export(audio_buffer, format="wav")
#             st.audio(audio_buffer, format="audio/wav", caption=f"Soundtrack for scene {i + 1}")
#         except Exception as e:
#             st.error(f"Failed to generate soundtrack for scene {i + 1}: {str(e)}")

# st.subheader("🎨 Storyboard Images")
# for i, scene in enumerate(parsed["scenes"]):
#     location = scene["location"]
#     if st.toggle(f"Generate preview for scene {i + 1} (takes 2 - 3 minutes)"):
#         with st.spinner(f"🖼️ Rendering image for scene {i + 1}..."):
#             try:
#                 # 精细化图片提示词
#                 image_prompt = f"""Movie still, {location},
#                     Ultra - high - definition 8K resolution,
#                     Movie - level lighting, shallow depth - of - field effect,
#                     Unreal Engine 5 rendering,
#                     Movie film graininess"""

#                 # 优化生成参数
#                 image = image_pipe(
#                     image_prompt,
#                     num_inference_steps=50,
#                     guidance_scale=9.5,
#                     width=1024,
#                     height=576  # 16:9 movie ratio
#                 ).images[0]

#                 st.image(image, caption=f"Preview for scene {i + 1}")
#             except Exception as e:
#                 st.error(f"Failed to generate image for scene {i + 1}: {str(e)}")

import streamlit as st
import re
from transformers import pipeline, AutoModelForTextToWaveform, AutoTokenizer
from diffusers import StableDiffusionPipeline
from pydub import AudioSegment
import zipfile
from io import BytesIO
import json
import torch
import torchaudio

# 初始化模型 (全部使用原始pipeline)
@st.cache_resource
def load_pipelines():
    try:
        device = "cuda:0" if torch.cuda.is_available() else "cpu"
        torch_dtype = torch.float16 if device == "cuda:0" else torch.float32

        # 1. Script generation
        script_pipe = pipeline(
            "text2text-generation",
            model="RUCAIBox/mvp-story",
            device=device
        )

        # 2. Storyboard generation (BART model)
        storyboard_pipe = pipeline(
            "text2text-generation",
            model="Jessiesj/script_gpt2-story",
            device=device
        )

        # 3. Soundtrack generation (MusicGen)
        music_model = AutoModelForTextToWaveform.from_pretrained(
            "facebook/musicgen-small",
            torch_dtype=torch_dtype
        ).to(device)
        music_tokenizer = AutoTokenizer.from_pretrained("facebook/musicgen-small")
        music_pipe = pipeline(
            "text-to-audio",
            model=music_model,
            tokenizer=music_tokenizer,
            device=device
        )

        # 4. Storyboard image generation (Stable Diffusion)
        image_pipe = StableDiffusionPipeline.from_pretrained(
            "prompthero/openjourney-v4",
            safety_checker=None,
            torch_dtype=torch_dtype
        ).to(device)

        return script_pipe, storyboard_pipe, music_pipe, image_pipe

    except Exception as e:
        st.error(f"Failed to load models: {str(e)}")
        raise

# Prompt template
def build_script_prompt(theme, style_or_opening):
    return f"""
{style_or_opening}
Generate a micro - movie script with two scenes, with the theme: {theme}.
### Format requirements (must be strictly followed):
- Use Markdown syntax
- Each scene starts with ### Scene X: [Location] (INT/EXT. Time)
- Include action descriptions (wrapped in square brackets []) and character dialogues

### Example:
### Scene 1: Spaceship cockpit (INT. Emergency)
[Alarm lights are flashing wildly, sparks are coming out of the console]
Captain (shouting): Start the backup engine!
Co - pilot (typing on the keyboard): The power system has failed!

### Scene 2: Alien jungle (EXT. Dusk)
[The expedition team pushes aside the dense purple bushes]
Team member A (pointing into the distance): Look! Is that the entrance to the ruins?
"""


# Content cleaning
def format_script(text):
    # Remove invalid symbols
    text = re.sub(r"[():<>]{2,}", "", text)
    # Standardize scene titles
    return re.sub(r"(?<!### )Scene\d+", r"### Scene\g<0>", text)

# Load pipelines
script_pipe, storyboard_pipe, music_pipe, image_pipe = load_pipelines()

# Streamlit interface
st.title("🎥 Micro - movie Intelligent Creation System")

# User input
user_input = st.text_input(
    "Enter the movie theme (e.g., Sci - fi space adventure)",
    help="Recommended format: Genre + Core conflict, example: 'Jungle exploration + Search for the lost golden city'"
)

style_or_opening = st.text_input(
    "Enter the script style or opening",
    help="Provide a style description or the beginning of the script"
)

if user_input and style_or_opening:

    # 1. Generate the script
    with st.status("🖋️ Generating the script...", expanded=True) as status:
        try:
            # Generate content
            prompt = build_script_prompt(user_input, style_or_opening)
            response = script_pipe(
                prompt,
                max_length=600,
                temperature=0.8,
                num_beams=4,
                no_repeat_ngram_size=3
            )[0]["generated_text"]

            # Post - processing
            def format_script(text):
                return text

            # Display the result
            st.subheader("Generated Script")
            cleaned = format_script(response)  # Ensure cleaned is defined here
            st.markdown(f"```markdown\n{format_script(response)}\n```")
            status.update(label="✅ Generation completed")

        except Exception as e:
            status.update(label="❌ Generation failed")
            st.error(f"Error details: {str(e)}")
            st.stop()

    # 2. Generate the storyboard
    with st.status("🎥 Converting to storyboard script...", expanded=True) as status:
        try:
            # 示例数据模板
            sample_storyboard = """
            {
              "scenes": [
                {
                  "scene_number": 1,
                  "location": "Abandoned Space Station (INT. Dystopian Future)",
                  "characters": ["Eve", "R2-D9"],
                  "camera_angle": "Wide shot showing decaying corridors",
                  "action": "Eve scans walls with her holographic projector, R2-D9 beeps nervously"
                },
                {
                  "scene_number": 2,
                  "location": "Alien Wasteland (EXT. Toxic Sunset)",
                  "characters": ["Eve", "Mutant Leader"],
                  "camera_angle": "Low-angle shot of Eve aiming plasma rifle",
                  "action": "Mutant leader growls, acid rain hisses on Eve's protective suit"
                }
              ]
            }
            """

            # JSON模板引导
            json_template = """{
              "scenes": [
                {
                  "scene_number": 1,
                  "location": "Scene location (INT/EXT)",
                  "characters": ["Character 1", "Character 2"],
                  "camera_angle": "Camera angle",
                  "action": "Main action description"
                }
              ]
            }"""

            # 生成分镜
            storyboard = storyboard_pipe(
                f"Convert to storyboard JSON: {cleaned[:800]}",
                max_length=1500,
                temperature=0.3
            )[0]["generated_text"]

            # 增强的格式修复
            storyboard = (
                storyboard.replace("'", '"')
                .replace("None", '""')
                .replace("True", "true")
                .replace("False", "false")
            )
            storyboard = re.search(r'\{.*\}', storyboard, re.DOTALL).group()
            parsed = json.loads(storyboard)

        except Exception as e:
            st.warning(f"Using sample storyboard due to error: {str(e)}")
            parsed = json.loads(sample_storyboard)
            status.update(label="⚠️ This is sample storyboard")

        status.update(label="Storyboard ready")
        st.subheader("Storyboard Script")
        st.json(parsed)
        # st.caption("*Note: If using sample data, edit the JSON before proceeding*")

    st.subheader("🎧 Background Music")
    for i, scene in enumerate(parsed["scenes"]):
        action = scene["action"]
        with st.spinner(f"🎵 Generating soundtrack for scene {i + 1}..."):
            try:
                audio = music_pipe(
                    action,
                    max_new_tokens=256
                )
                audio_buffer = BytesIO()
                audio["audio"].export(audio_buffer, format="wav")
                st.audio(audio_buffer, format="audio/wav", caption=f"Soundtrack for scene {i + 1}")
            except Exception as e:
                st.error(f"Failed to generate soundtrack for scene {i + 1}: {str(e)}")

    st.subheader("🎨 Storyboard Images")
    for i, scene in enumerate(parsed["scenes"]):
        location = scene["location"]
        if st.toggle(f"Generate preview for scene {i + 1} (takes 2 - 3 minutes)"):
            with st.spinner(f"🖼️ Rendering image for scene {i + 1}..."):
                try:
                    # 精细化图片提示词
                    image_prompt = f"""Movie still, {location},
                        Ultra - high - definition 8K resolution,
                        Movie - level lighting, shallow depth - of - field effect,
                        Unreal Engine 5 rendering,
                        Movie film graininess"""

                    # 优化生成参数
                    image = image_pipe(
                        image_prompt,
                        num_inference_steps=50,
                        guidance_scale=9.5,
                        width=1024,
                        height=576  # 16:9 movie ratio
                    ).images[0]

                    st.image(image, caption=f"Preview for scene {i + 1}")
                except Exception as e:
                    st.error(f"Failed to generate image for scene {i + 1}: {str(e)}")