1 files added
12 files modified
| | |
| | | _log_listener = setup_concurrent_logging() |
| | | logger = logging.getLogger("api_server") |
| | | # ================================= |
| | | from fastapi import FastAPI, Request, HTTPException |
| | | from fastapi import FastAPI, Request, HTTPException, UploadFile, File |
| | | from fastapi.responses import StreamingResponse |
| | | from fastapi.staticfiles import StaticFiles |
| | | from fastapi.middleware.cors import CORSMiddleware |
| | | from pydantic import BaseModel |
| | | from typing import Any, Optional, Dict, List |
| | | import shutil |
| | | |
| | | sys.path.append(os.path.dirname(os.path.abspath(__file__))) |
| | | |
| | | from config import settings |
| | | from core.orchestrator import WorkflowEngine, WorkflowStage |
| | | from tool.file_reader import FileReader |
| | | |
| | | app = FastAPI(title="AI导演工作室", version="2.0.0") |
| | | workflow_engine = WorkflowEngine() |
| | |
| | | |
| | | class ProjectStartRequest(BaseModel): |
| | | idea: str |
| | | file_path: Optional[str] = None # 用户上传的文件路径 |
| | | style: Optional[str] = "anime" |
| | | video_ratio: Optional[str] = "16:9" |
| | | expand_idea: Optional[bool] = True # 默认启用创意扩写 |
| | |
| | | return {"status": "ok", "timestamp": time.time()} |
| | | |
| | | |
| | | @app.post("/api/upload_file") |
| | | async def upload_file(file: UploadFile = File(...)): |
| | | """ |
| | | 接收用户上传的文件 (.docx, .doc, .txt, .md, .pdf),将其保存到 temp 目录。 |
| | | 返回保存的相对路径给前端。 |
| | | """ |
| | | allowed_exts = [".docx", ".doc", ".txt", ".md", ".pdf"] |
| | | filename = file.filename |
| | | ext = os.path.splitext(filename)[1].lower() |
| | | if ext not in allowed_exts: |
| | | raise HTTPException(status_code=400, detail=f"仅支持 {', '.join(allowed_exts)} 格式的文件") |
| | | |
| | | # 1. 确保临时目录存在 |
| | | os.makedirs(settings.TEMP_DIR, exist_ok=True) |
| | | |
| | | # 2. 生成唯一文件名并保存 |
| | | safe_filename = f"{int(time.time())}_{filename}" |
| | | file_path = os.path.join(settings.TEMP_DIR, safe_filename) |
| | | try: |
| | | with open(file_path, "wb") as buffer: |
| | | shutil.copyfileobj(file.file, buffer) |
| | | except Exception as e: |
| | | logger.error(f"保存上传文件失败: {e}") |
| | | raise HTTPException(status_code=500, detail=f"文件保存失败: {str(e)}") |
| | | |
| | | return { |
| | | "filename": filename, |
| | | "file_path": safe_filename # 只返回文件名部分,相对于 TEMP_DIR |
| | | } |
| | | |
| | | |
| | | @app.post("/api/project/start") |
| | | async def start_project(req: ProjectStartRequest): |
| | | # 处理上传的文件 |
| | | final_idea = req.idea |
| | | if req.file_path: |
| | | # file_path 是储存在 settings.TEMP_DIR 下的文件名 |
| | | full_path = os.path.join(settings.TEMP_DIR, req.file_path) |
| | | if os.path.exists(full_path): |
| | | content = FileReader.extract_text(full_path) |
| | | if content: |
| | | # 提取原始文件名 (去掉时间戳前缀) |
| | | original_filename = "_".join(req.file_path.split("_")[1:]) |
| | | prompt_fragment = FileReader.format_as_prompt(original_filename, content) |
| | | # 静默拼接到 idea 中 |
| | | final_idea = f"{final_idea}\n\n{prompt_fragment}" |
| | | logger.info(f"成功处理上传文件: {full_path}") |
| | | else: |
| | | logger.warning(f"上传的文件未找到: {full_path}") |
| | | |
| | | session_id = str(int(time.time() * 1000)) |
| | | state = workflow_engine.get_or_create_state(session_id) |
| | | state.started_at = __import__('datetime').datetime.now() |
| | |
| | | |
| | | # 保存会话元数据(未传参数时使用 config.py 中的默认值) |
| | | meta = { |
| | | "idea": req.idea, |
| | | "style": req.style or "anime", |
| | | "idea": final_idea, |
| | | "user_textbox_input": req.idea, # 保留原始的用户输入,用于前端展示 |
| | | "style": req.style or "realistic", |
| | | "video_ratio": req.video_ratio or "16:9", |
| | | "expand_idea": req.expand_idea if req.expand_idea is not None else True, |
| | | "llm_model": req.llm_model or settings.LLM_MODEL, |
| | |
| | | "session_id": session_id, |
| | | "status": state.status, |
| | | "params": { |
| | | "idea": req.idea, |
| | | "idea": final_idea, |
| | | "file_path": req.file_path, |
| | | "style": req.style, |
| | | "llm_model": req.llm_model, |
| | | "vlm_model": req.vlm_model, |
| | |
| | | # 注入会话级元数据(模型配置等),确保模型参数始终可用 |
| | | if state.meta: |
| | | for k, v in state.meta.items(): |
| | | if v is not None and k not in body: # 区分 None 和 False |
| | | # 即使 body[k] 存在但为空字符串(如 idea),也应该使用 meta 中的完整内容 |
| | | if v is not None: |
| | | if k not in body or not body[k]: |
| | | body[k] = v |
| | | |
| | | # 从已持久化的 artifacts 中注入用户选项(selected_images / selected_clips) |
| | |
| | | "session_id": sid, |
| | | "version": 1, |
| | | "created_at": datetime.now(timezone.utc).isoformat(), |
| | | "metadata": { |
| | | "meta": { |
| | | "generation_model": llm_model, |
| | | "generation_prompt": idea, |
| | | "original_text": full_script_text |
| | |
| | | data["error"] = state.error |
| | | data["updated_at"] = state.updated_at.timestamp() if isinstance(state.updated_at, datetime) else time.time() |
| | | |
| | | # 保存元数据 |
| | | # 保存元数据(将 meta 中的键展开到根目录下) |
| | | if state.meta: |
| | | for k, v in state.meta.items(): |
| | | if v is not None: |
| | |
| | | You are a professional script analyst. Please carefully read the following [Full Script Text], and per instructions, extract the entirety of **Episode {act_number}**, reference the [Global Assets], and organize it into standard JSON format. |
| | | You are a professional script analyst. You need to accurately split the entire content of the script into an array format based on episodic labels (such as "Episode 1", "Episode 2", etc.). |
| | | |
| | | --- |
| | | |
| | | [Global Assets] |
| | | Character Library: |
| | | {asset_characters} |
| | | [Script Input] |
| | | |
| | | Setting Library: |
| | | {asset_settings} |
| | | {script_text} |
| | | |
| | | --- |
| | | |
| | | [Full Script Text] |
| | | {outline} |
| | | [Splitting Requirements] |
| | | |
| | | 1. Group the script content into the corresponding `episode_number`. |
| | | 2. For `act_title`, summarize a concise and engaging title of no more than 10 words based on the story of the episode. |
| | | 3. For `content`, preserve the full script text of the episode (including scene descriptions, action directions, and character dialogue). |
| | | |
| | | **Note (Strictly Adhere to):** |
| | | 1. **Output Format**: You must output ONLY a pure JSON array. No Markdown formatting (such as ```json code blocks), explanatory text, analysis, or closing remarks are allowed. |
| | | 2. Ensure the JSON structure is complete and valid. |
| | | |
| | | --- |
| | | |
| | | [Important Rules] |
| | | |
| | | 1. Extract the entirety of Episode {act_number} from the [Full Script Text]. |
| | | 2. Provide a one-sentence summary for `episode_title`. |
| | | 3. Put the full text of this episode into `episode_content`, preserving all details, dialogue, and actions. |
| | | 4. Keep the `scenes` array empty `[]` as scene extraction will be handled in a later stage. |
| | | 5. `episode_number` must be {act_number}. |
| | | 6. Output ONLY pure JSON. Do NOT generate `characters` and `settings` arrays. |
| | | |
| | | --- |
| | | |
| | | [Output Format] |
| | | |
| | | Please strictly output in the following JSON structure (direct pure JSON, no ``` wrappers, no extra text): |
| | | |
| | | [Output Format Example (Return only this JSON array)] |
| | | [ |
| | | {{ |
| | | "episode_number": {act_number}, |
| | | "episode_title": "A one-sentence summary of Episode {act_number}", |
| | | "episode_content": "The full script text of this episode (containing all details, dialogue)", |
| | | "scenes": [] |
| | | "episode_number": 1, |
| | | "act_title": "Episode Title", |
| | | "content": "Detailed script content..." |
| | | }}, |
| | | {{ |
| | | "episode_number": 2, |
| | | "act_title": "Episode Title", |
| | | "content": "Detailed script content..." |
| | | }} |
| | | ] |
| | |
| | | You are a professional script analyst. Your task is to accurately split the continued (sequel) script content into a JSON array based on episode labels (e.g., "Episode {start_episode_num}", etc.). |
| | | You are a professional script analyst. You need to accurately split the continued (sequel) script content into a JSON array based on episodic labels (such as "Episode {start_episode_num}", etc.). |
| | | |
| | | --- |
| | | |
| | | [SCRIPT INPUT] |
| | | [Script Input] |
| | | |
| | | {sequel_script} |
| | | |
| | | --- |
| | | |
| | | [SPLITTING REQUIREMENTS] |
| | | [Splitting Requirements] |
| | | |
| | | 1. Please categorize the input script content into the corresponding `episode_number`. This continuation starts from Episode {start_episode_num}. |
| | | 2. For `act_title`, please summarize a concise title within 10 words. |
| | | 3. For `content`, please include the full original script text of that episode (including scene descriptions, action instructions, and character dialogues). |
| | | 1. Group the input script content into the corresponding `episode_number`. This continuation starts from Episode {start_episode_num}. |
| | | 2. For `act_title`, summarize a concise title of no more than 20 words. |
| | | 3. For `content`, preserve the full original script text of that episode (including scene descriptions, action directions, and character dialogue). |
| | | |
| | | **NOTICE (STRICTLY FOLLOW):** |
| | | 1. **Output Format**: You must and only output a pure JSON array. Markdown formats (such as ```json blocks), explanatory text, or closing remarks are strictly prohibited. |
| | | **Note (Strictly Adhere to):** |
| | | 1. **Output Format**: You must output ONLY a pure JSON array. No Markdown formatting (such as ```json code blocks), explanatory text, or closing remarks are allowed. |
| | | 2. Ensure the JSON structure is complete and valid. |
| | | |
| | | --- |
| | | |
| | | [OUTPUT FORMAT EXAMPLE (ONLY return this JSON array)] |
| | | [Output Format Example (ONLY return this JSON array)] |
| | | [ |
| | | {{ |
| | | "episode_number": {start_episode_num}, |
| | |
| | | You are an expert micro-drama screenwriter. Based on the user's "core idea" and "story style", directly write out the complete micro-drama script. |
| | | You are an expert micro-drama screenwriter. Based on the user's "core inspiration" and "story style," directly create a complete micro-drama script. |
| | | |
| | | [Script Format and Writing Methodology]: |
| | | 1. **Episodic Structure**: The script must be divided into episodes (e.g., "Episode 1", "Episode 2"...), and each episode must have a fast pace. |
| | | 2. **Scene and Layout Format**: You must strictly follow the industrial scene script format. |
| | | For example: `**x-x Day/Night Int/Ext Scene Name**` |
| | | The next line specifies `Characters: xxx, xxx`, followed by a blank line. |
| | | 3. **Action and Visual Descriptions**: Action descriptions must start with "<action>" (e.g., "<action>Lin Yichen stares at the screen, dark circles under his eyes..."). Never write psychological activities that cannot be filmed. |
| | | 1. **Adaptation Principles**: Optimize the narrative rhythm for a micro-drama format while strictly respecting the core plot, classic dialogue structure, and character relationships provided in the user's "core inspiration/story setting." Do not significantly deviate from the spirit of the original or replace it with irrelevant, trivial anecdotes. |
| | | 2. **Episodic Structure**: The script must be divided into episodes (e.g., "Episode 1", "Episode 2", etc.), with a fast-paced narrative in each episode. |
| | | 3. **Scene and Layout Format**: You must strictly follow the industrial scene script format. |
| | | Example: `**a-b Day/Night Int/Ext Scene Name**`, where 'a' represents the episode number and 'b' represents the scene number within that episode. |
| | | An episode can have one or multiple scenes. If the same scene appears in different episodes, ensure the scene name is identical. |
| | | The next line should specify `Characters: xxx, xxx`, followed by a blank line. |
| | | 3. **Action and Visual Descriptions**: Action descriptions must start with "<action>" and describe objective physical actions and camera visuals (e.g., "<action>Lin Yichen stares at the screen, dark circles under his eyes, his fingers typing quickly on the keyboard."). Never write psychological activities that cannot be filmed. |
| | | 4. **Vivid Dialogue and Synchronized Monologue**: Dialogues should fit the character's identity and emotions. Emotion and action hints are written in parentheses after the character's name. Example: `Lin Yichen (sneering): ...` |
| | | * **Text Synchronization Technique**: If key visual text appears in the script (such as text on the wall, email subject, SMS content, etc.), a line of character dialogue must be added (can be normal dialogue, reading aloud, off-screen voice OS, or inner-monologue VO). **The dialogue must output the complete and specific text body; using generic terms like "reading the SMS content" or "seeing the text" is strictly prohibited.** Example: `Lin Yichen (reading aloud): Honey, let's break up.` (Instead of: `Lin Yichen: [Reads the SMS]`). |
| | | 5. **Strong Dramatic Satisfaction**: The opening should quickly cut into the core conflict (such as being fired, betrayed, humiliated), and then swiftly enter the counterattack/entrepreneurship/face-slapping phase. The pace must be fast and emotions high. |
| | | 6. **Visual Contrast**: Use the contrast between bottom-level dilapidated scenes and top-level luxurious scenes to enhance dramatic tension. |
| | | 7. **No Separate Lore/Settings**: Do not write character bios or background outlines. Start the script text directly. |
| | | 8. **Use Dialogue to Drive the Plot**: Use more dialogue, monologues, and off-screen voices to express the character's thoughts, drive the plot development, and create conflicts. |
| | | 9. **Script Length Requirements**: Each episode is 1-2 minutes long, roughly 20-30 actions or dialogues (i.e., 20-30 lines per episode). Pay attention to controlling the length of each episode's script. |
| | | * **Text Synchronization Technique**: If key visual text appears (such as text on a wall, an email subject, or SMS content), a line of character dialogue must be added (can be normal dialogue, off-screen voice OS, or inner-monologue VO). **The dialogue must contain the full, specific text; never use descriptive terms like "reading the SMS content" or "displaying text."** Example: `Lin Yichen (reading aloud): Honey, let's break up.` |
| | | 5. **Strong Dramatic Satisfaction**: The opening should quickly cut into a core conflict (e.g., being fired, betrayed, or humiliated), then swiftly transition to the counterattack/entrepreneurship/payback phase. The pace must be fast, and emotions should be high. |
| | | 6. **Scene and Visual Contrast**: Utilize the contrast between dilapidated low-end scenes and luxurious high-end scenes to enhance dramatic tension. |
| | | 7. **No Separate Lore/Settings**: Do not write character biographies or background outlines. Start the script text directly. |
| | | 8. **Drive Plot with Dialogue**: Use dialogue, monologues, and off-screen voices to express character thoughts, drive the plot, and create conflicts. |
| | | 9. **Script Length Requirements**: Each episode should be 1-2 minutes long, roughly 20-30 actions or dialogues (20-30 lines per episode). Control the length of each episode's script accordingly. |
| | | |
| | | --- |
| | | [Script Example (Learn its action, dialogue, and rhythmic structure)]: |
| | | ## Episode 1 |
| | | |
| | | **1-1 Day Int Tech Company Office** |
| | | [Core Scriptwriting Specifications]: |
| | | |
| | | Characters: Lin Yichen, Boss Wang, Colleague A, Colleague B, HR Sister Li |
| | | |
| | | <action>Inside the office, cubicles are densely packed, programmers are buried in writing code, the atmosphere is oppressive. |
| | | |
| | | <action>Lin Yichen stares at the screen, dark circles under his eyes, his fingers typing quickly on the keyboard. |
| | | |
| | | <action>Boss Wang, with a beer belly, paces behind Lin Yichen. |
| | | |
| | | Boss Wang (sarcastically): Lin Yichen, you haven't finished this module you've been writing for three days? Did I hire you to do nothing? |
| | | |
| | | Lin Yichen (without looking up): Boss Wang, this architecture needs refactoring. The previous technical debt is too heavy... |
| | | |
| | | Boss Wang (slamming the table): Stop making excuses! Little Zhang launched three features in two days, what about you? Low efficiency is an ability problem! |
| | | |
| | | <action>Lin Yichen takes a deep breath and continues typing. |
| | | |
| | | (...End of example...) |
| | | 1. **Episodes and Pacing**: The script must be divided by episodes (e.g., "Episode 1", "Episode 2", etc.). Each episode should be 1-2 minutes long, with a very fast narrative pace. The length of a single episode's script should remain between 20-30 lines of action or dialogue. |
| | | 2. **Industrial Layout Format**: |
| | | - Each scene starts with a bold, centered scene heading: `**a-b Day/Night Int/Ext Scene Name**` (where 'a' is the episode number and 'b' is the scene sequence within that episode). |
| | | - Immediately follow the heading with: `Characters: xxx, xxx`, and then leave one blank line before starting the body text. |
| | | 3. **Action Description Standards**: All visual/action descriptions must start with `<action>` and describe only objective, filmable physical actions, expressions, or camera visuals. Prohibit describing inner thoughts or text that cannot be perceived through the screen. |
| | | 4. **Dialogue and Cues**: Dialogues must fit the character's identity. Emotion, tone, or simultaneous micro-action cues must be written in half-width parentheses after the character's name, e.g., `Character Name (tone cue): Dialogue`. |
| | | 5. **Audiovisual Text Synchronization**: If key text appears in the scene (e.g., letters, SMS, announcements, signs, etc.), a character must be arranged to read it out completely, or express its specific content through inner monologue (VO) / off-screen voice (OS). Generic descriptions like "finished reading the message" are prohibited. |
| | | 6. **Dramatic Structure Requirements**: The opening must have a strong conflict point (e.g., passively falling into a low point or facing a crisis). Drive the plot through dense dialogue and monologues, create visual contrast between scene transitions, and ensure each episode ends with a cliffhanger or emotional release point. |
| | | 7. **Consistency Principle**: Scene names for the same location appearing in different episodes must remain completely identical for later asset matching. |
| | | 8. **Direct Output**: No need to output character bios, outlines, or prefaces. Start the script body directly from "## Episode 1". |
| | | |
| | | --- |
| | | [User Core Idea]: |
| | | |
| | | [User Core Inspiration/Story Setting]: |
| | | {idea} |
| | | |
| | | [Story Style]: |
| | | {style} |
| | | |
| | | --- |
| | | Take a deep breath and start your creation. Based on the inspiration above, directly output the complete script text (containing the full content of {episodes} episodes, with estimated duration of 1 to 2 minutes per episode). Do not include any filler words or prefaces. |
| | | |
| | | Now, begin your creation. Based on the [User Core Inspiration/Story Setting], output the complete script text containing {episodes} episodes. Each episode is estimated at 1-2 minutes, with about 20-30 lines of action or dialogue. Only output the complete script; no additional commentary or preface is required. |
| | |
| | | 你是顶级微短剧编剧专家。请根据用户提供的“核心灵感”与“故事风格”,直接创作出完整的微短剧剧本。 |
| | | |
| | | 【剧本格式与创作方法】: |
| | | 1. **分集结构**:剧本必须分集(如“等1集”、“第2集”...),每一集起承转合要快。 |
| | | 2. **场次与排版格式**:必须严格遵循工业场志格式。 |
| | | 1. **改编原则**:在尊重用户提供的“核心灵感/故事设定”中核心情节、经典台词架构和人物关系的前提下,进行微短剧化的节奏优化。严禁过度偏移原著精神或将其生硬替换为风马牛不相及的琐碎情节。 |
| | | 2. **分集结构**:剧本必须分集(如“等1集”、“第2集”...),每一集起承转合要快。 |
| | | 3. **场次与排版格式**:必须严格遵循工业场志格式。 |
| | | 例如:`**a-b 日/夜 内/外 场景名称**`,其中a代表所属剧集,b代表剧集下的场景。 |
| | | 每集可以只有一个场景,也可以有多个场景。如果不同剧集中需要在相同场景拍摄,请确保场景名称完全一致。 |
| | | 下一行写明`人物:xxx, xxx`,再下一行空出。 |
| | |
| | | |
| | | --- |
| | | |
| | | 【剧本示例(参考学习其动作、对白与节奏结构)】: |
| | | 【剧本创作核心规范】: |
| | | |
| | | ## 第1集 |
| | | |
| | | **1-1 日 内 科技公司办公室** |
| | | 人物:林逸尘,王总,同事甲、乙,HR李姐 |
| | | <action>办公室内,格子间密密麻麻,程序员们埋头敲代码,气氛压抑。 |
| | | <action>林逸尘盯着屏幕,眼眶乌青,手指在键盘上飞快敲击。 |
| | | <action>王总挺着啤酒肚,踱步到林逸尘身后。 |
| | | 王总(冷嘲热讽):林逸尘,你这个模块写了三天了还没搞定?我招你进来是吃干饭的? |
| | | 林逸尘(头也不抬):王总,这个架构需要重构,之前的技术债太重了…… |
| | | 王总(猛地拍桌):少给我找借口!人家小张两天就上线了三个功能,你呢?效率低下就是能力问题! |
| | | <action>林逸尘手指顿了顿,没有说话。 |
| | | <action>同事甲凑过来,小声嘀咕。 |
| | | 同事甲:逸尘,你就别顶嘴了,上个月老李就是顶嘴被开了。 |
| | | <action>林逸尘深吸一口气,继续敲代码。 |
| | | 王总(指着屏幕):今晚12点之前,这个模块必须上线。不然这个月绩效全扣! |
| | | <action>王总转身离开,走到半路又回头。 |
| | | 王总:对了,周末团建你得来,别又找借口加班。团队凝聚力也是考核指标! |
| | | <action>林逸尘攥紧鼠标,指节发白。 |
| | | |
| | | **1-2 夜 内 出租屋** |
| | | 人物:林逸尘 |
| | | <action>狭小的出租屋里,堆满了外卖盒和空红牛罐。 |
| | | <action>林逸尘瘫在椅子上,双眼布满血丝,盯着天花板。 |
| | | 林逸尘OS:三年了,天天加班,天天被骂,工资从一万五涨到一万八……连房租都快付不起了。 |
| | | <action>手机突然震动,是母亲发来的消息。 |
| | | 母亲微信语音(焦急):逸尘啊,你爸住院了,医生说要做手术,要五万块钱……你那边能不能…… |
| | | <action>林逸尘猛地坐直,脸上闪过一丝慌乱。 |
| | | <action>他打开银行APP,余额显示:4,327元。 |
| | | 林逸尘(喃喃自语):五万…… |
| | | <action>他打开通讯录,翻到王总的号码,犹豫了很久,还是没有拨出去。 |
| | | <action>林逸尘瘫回椅子,闭上眼睛,眼角滑下一滴泪。 |
| | | 1. **分集与节奏**:剧本必须按集划分(如“第1集”、“第2集”...)。每集时长控制在1-2分钟,剧情起承转合要极快,单集脚本长度保持在20-30行动作或对白之间。 |
| | | 2. **工业化排版格式**: |
| | | - 每场戏以居中的粗体场志开始:`**a-b 日/夜 内/外 场景名称**`(a为集数,b为本集内的场序)。 |
| | | - 场志下方紧跟一行:`人物:xxx, xxx`,随后空一行开始正文。 |
| | | 3. **动作描述规范**:所有视觉/动作描述必须以 `<action>` 开头,且仅描述客观可拍摄的物理动作、表情或镜头画面。严禁描写内心活动或无法通过画面感知的文字。 |
| | | 4. **对话与提示语**:对白应符合人物身份。情绪、语气或同步的微动作提示必须写在角色名后的半角括号内,如:`角色名(语气提示):台词`。 |
| | | 5. **视听文字同步**:若画面中出现关键文字(如:书信、短信、公告、招牌等),必须安排角色将其完整读出,或通过内心独白(VO)/画外音(OS)表达其具体内容,禁止使用“读完短信”等概括性叙述。 |
| | | 6. **剧作结构要求**:开场必须有强烈的冲突点(如被动陷入低谷或面临危机)。通过密集的对白和独白推动情节,在场景转换间创造视觉反差,确保每集结尾留有悬念或情绪释放点。 |
| | | 7. **一致性原则**:不同剧集中出现的相同场景,其名称必须保持完全一致,以便于后期资产匹配。 |
| | | 8. **内容直接产出**:无需输出人物小传、大纲或前言,直接从“## 第1集”开始输出剧本正文。 |
| | | |
| | | --- |
| | | |
| | |
| | | You are a professional script analyst. Below is the complete full script text: |
| | | You are a professional script designer. You need to extract information from the script, design character profiles, and setting layouts. |
| | | |
| | | --- |
| | | |
| | | [Script Input] |
| | | |
| | | Below is the complete full script text: |
| | | |
| | | {script_text} |
| | | |
| | | [Design Requirements (Strictly Follow)]: |
| | | 1. **Output Format**: Must and only output a pure JSON object. Markdown formats (such as ```json blocks), explanatory text, introductions, or conclusions are strictly prohibited. |
| | | 2. **Extraction Object**: Extract all [Characters] and [Settings] that appear in the script with dialogues or key actions. Ignore group/extra characters. |
| | | 3. **Character Description**: |
| | | - Use the "age + gender + hairstyle/jewelry + clothing + body type + facial features/expression" format. |
| | | - Core Features: Must include hairstyle, body type, clothing color and style, etc. |
| | | - Prohibition: No sci-fi or fantasy elements; appearance must be normal. |
| | | - Style: 30-50 words, plain and direct language, no metaphors or literary rhetoric. |
| | | 4. **Setting Description**: |
| | | - Use the "space type + lighting direction and color + core furniture/decor (texture/material) + atmosphere" format. |
| | | - Style: 30-50 words, concrete and shootable description. |
| | | - Example: "Modern minimalist office, cold moonlight spills through floor-to-ceiling windows, the desk is cold-toned solid wood, atmosphere is quiet and serious." |
| | | --- |
| | | |
| | | [Design Requirements] |
| | | |
| | | Please extract the following information from the [Script Input], specifically focusing on building the [Global Asset Baseline (Core Characters and Main Settings)]. The appearance and layout of these assets should remain consistent throughout the series. Additionally, please provide a suitable title for the script based on its content. |
| | | |
| | | **Note (Strictly Adhere to):** |
| | | 1. **Output Format**: You must output ONLY a pure JSON object. No Markdown formatting (such as ```json code blocks), explanatory text, introductions, or conclusions are allowed. |
| | | 2. Extract all [Characters] (not just the protagonist) who appear in the script with dialogue or significant actions, but do not extract group characters (e.g., "some employees," "a few customers"). |
| | | 3. Extract all [Settings] (not just general locations) that are specifically described in the script in different geographical positions. |
| | | 4. **Character Description**: |
| | | - Use a descriptive format: "age + gender + hairstyle/accessories + clothing + body type + facial features/expression." |
| | | - Core Features: Must include visual characteristics such as hairstyle, body type, clothing color, and style. |
| | | - Strictly prohibit sci-fi or fantasy elements; the appearance must be realistic. |
| | | - Style: 30-50 words, plain and direct language; avoid metaphors or literary rhetoric. |
| | | 5. **Setting Layout**: |
| | | - Use a descriptive format: "space type + lighting direction and color + core furnishings (texture/material) + environmental atmosphere." |
| | | - Example: "Modern minimalist office, cold moonlight spills in from floor-to-ceiling windows, the desk is cold-toned solid wood, and the air feels quiet and serious." |
| | | - Style: 30-50 words, specific and shootable descriptions. |
| | | |
| | | --- |
| | | [Output Format Example (ONLY return this JSON object)]: |
| | | |
| | | [Output Format Example (ONLY return this JSON object)] |
| | | {{ |
| | | "title": "Story Title", |
| | | "logline": "One-sentence story outline", |
| | | "genre": ["genre1", "genre2"], |
| | | "mood": "Emotional tone", |
| | | "title": "Script Name", |
| | | "logline": "One-sentence story summary", |
| | | "genre": ["Genre 1", "Genre 2"], |
| | | "mood": "Emotional tone of the film", |
| | | "characters": [ |
| | | {{ |
| | | "name": "Full name of protagonist/major supporting character", |
| | | "description": "Appearance description, requirements see [Design Requirements]", |
| | | "description": "Appearance description, see [Design Requirements]", |
| | | "species": "Human or specific animal species" |
| | | }} |
| | | ], |
| | | "settings": [ |
| | | {{ |
| | | "name": "Specific Setting Name", |
| | | "description": "General setting description, requirements see [Design Requirements]" |
| | | "name": "Specific location name", |
| | | "description": "General setting description, see [Design Requirements]" |
| | | }} |
| | | ] |
| | | }} |
| | |
| | | |
| | | # Data Validation |
| | | pydantic>=2.0.0 |
| | | python-multipart>=0.0.6 |
| | | |
| | | # Environment Variables |
| | | python-dotenv>=1.0.0 |
| | |
| | | |
| | | # Image Processing |
| | | Pillow>=10.0.0 |
| | | python-docx |
| | | PyPDF2 |
| | | numpy>=1.24.0 |
| | | |
| | | # Document Processing |
| | | python-docx>=1.1.0 |
| | | |
| | | # AI/ML Clients |
| | | openai>=1.0.0 |
| | | dashscope>=1.10.0 |
| New file |
| | |
| | | # -*- coding: utf-8 -*- |
| | | import os |
| | | import logging |
| | | from typing import Optional |
| | | from docx import Document |
| | | |
| | | logger = logging.getLogger(__name__) |
| | | |
| | | class FileReader: |
| | | """ |
| | | 文档内容提取工具类 |
| | | """ |
| | | |
| | | @staticmethod |
| | | def extract_text(file_path: str) -> str: |
| | | """ |
| | | 根据文件后缀名,从文件中提取文本内容 |
| | | 支持 .docx, .txt, .md |
| | | :param file_path: 文件路径 |
| | | :return: 提取出的文本字符串 |
| | | """ |
| | | if not os.path.exists(file_path): |
| | | logger.error(f"文件不存在: {file_path}") |
| | | return "" |
| | | |
| | | ext = os.path.splitext(file_path)[1].lower() |
| | | |
| | | if ext in [".docx", ".doc"]: |
| | | return FileReader._extract_docx(file_path) |
| | | elif ext in [".txt", ".md"]: |
| | | return FileReader._extract_plain_text(file_path) |
| | | elif ext == ".pdf": |
| | | return FileReader._extract_pdf(file_path) |
| | | else: |
| | | logger.error(f"不支持的文件格式: {ext}") |
| | | return "" |
| | | |
| | | @staticmethod |
| | | def _extract_docx(file_path: str) -> str: |
| | | try: |
| | | doc = Document(file_path) |
| | | full_text = [] |
| | | |
| | | # 1. 提取所有段落内容 |
| | | for para in doc.paragraphs: |
| | | cleaned_text = para.text.strip() |
| | | if cleaned_text: |
| | | full_text.append(cleaned_text) |
| | | |
| | | # 2. 提取表格中的内容 |
| | | for table in doc.tables: |
| | | for row in table.rows: |
| | | for cell in row.cells: |
| | | cleaned_cell = cell.text.strip() |
| | | if cleaned_cell: |
| | | full_text.append(cleaned_cell) |
| | | |
| | | return "\n".join(full_text) |
| | | except Exception as e: |
| | | logger.error(f"解析 Word 文档失败: {e}") |
| | | return "" |
| | | |
| | | @staticmethod |
| | | def _extract_plain_text(file_path: str) -> str: |
| | | try: |
| | | # 尝试使用 multiple encodings |
| | | for encoding in ['utf-8', 'gbk', 'utf-16']: |
| | | try: |
| | | with open(file_path, 'r', encoding=encoding) as f: |
| | | return f.read() |
| | | except UnicodeDecodeError: |
| | | continue |
| | | return "" |
| | | except Exception as e: |
| | | logger.error(f"解析文本文件失败: {e}") |
| | | return "" |
| | | |
| | | @staticmethod |
| | | def _extract_pdf(file_path: str) -> str: |
| | | try: |
| | | import PyPDF2 |
| | | text = "" |
| | | with open(file_path, 'rb') as f: |
| | | reader = PyPDF2.PdfReader(f) |
| | | for page in reader.pages: |
| | | text += page.extract_text() + "\n" |
| | | return text.strip() |
| | | except ImportError: |
| | | logger.error("未安装 PyPDF2,无法解析 PDF 文件。请运行: pip install PyPDF2") |
| | | return "[错误: 后端未安装 PDF 解析插件]" |
| | | except Exception as e: |
| | | logger.error(f"解析 PDF 失败: {e}") |
| | | return "" |
| | | |
| | | @staticmethod |
| | | def format_as_prompt(filename: str, content: str) -> str: |
| | | """ |
| | | 将提取的内容格式化为 LLM Prompt 友好的字符串 |
| | | """ |
| | | if not content: |
| | | return "" |
| | | |
| | | return ( |
| | | f"\n--- [上传的文件内容开始] ---\n" |
| | | f"文件名: {filename}\n" |
| | | f"内容如下:\n" |
| | | f"{content}\n" |
| | | f"--- [上传的文件内容结束] ---\n" |
| | | ) |
| | |
| | | 'use client'; |
| | | |
| | | import React, { useState } from 'react'; |
| | | import { Sparkles, Play, Settings2, Clock, ArrowRight, Zap, CheckCircle, Trash2, X, Lock, Globe, ListOrdered } from 'lucide-react'; |
| | | import React, { useState, useRef } from 'react'; |
| | | import { Sparkles, Play, Settings2, Clock, ArrowRight, Zap, CheckCircle, Trash2, X, Lock, Globe, ListOrdered, Upload, Loader2 } from 'lucide-react'; |
| | | import clsx from 'clsx'; |
| | | import { PROMPT_EXAMPLES } from '@/config/examples'; |
| | | import { LLM_MODELS, T2I_MODELS, I2I_MODELS, VIDEO_MODELS, VLM_MODELS, STYLES, VIDEO_RATIOS, LLM_PROVIDERS, T2I_PROVIDERS, I2I_PROVIDERS, VIDEO_PROVIDERS, VLM_PROVIDERS, ProviderGroup } from '@/config/models'; |
| | |
| | | |
| | | export interface ProjectParams { |
| | | idea: string; |
| | | file_path?: string; // 上传的文件路径 (由后端返回的文件名) |
| | | style: string; |
| | | video_ratio: string; |
| | | llm_model: string; |
| | |
| | | const [episodes, setEpisodes] = useState(4); |
| | | const [showEpisodesPanel, setShowEpisodesPanel] = useState(false); |
| | | |
| | | // 上传相关状态 |
| | | const fileInputRef = useRef<HTMLInputElement>(null); |
| | | const [uploading, setUploading] = useState(false); |
| | | const [uploadedFile, setUploadedFile] = useState<{name: string, path: string} | null>(null); |
| | | |
| | | // 管理模式状态 |
| | | const [manageMode, setManageMode] = useState(false); |
| | | const [deleteTarget, setDeleteTarget] = useState<string | null>(null); |
| | |
| | | }; |
| | | |
| | | const handleStart = (auto?: boolean) => { |
| | | if (!idea.trim()) return; |
| | | if (!idea.trim() && !uploadedFile) return; |
| | | onStartProject({ |
| | | idea, |
| | | file_path: uploadedFile?.path, // 如果上传了文件,传给后端 |
| | | style: selectedStyle, |
| | | video_ratio: selectedRatio, |
| | | llm_model: selectedLLM, |
| | |
| | | |
| | | const handleExampleClick = (text: string) => { |
| | | setIdea(text); |
| | | }; |
| | | |
| | | const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => { |
| | | const file = e.target.files?.[0]; |
| | | if (!file) return; |
| | | |
| | | const allowedExtensions = ['.doc', '.docx', '.txt', '.md', '.pdf']; |
| | | const extension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase(); |
| | | |
| | | if (!allowedExtensions.includes(extension)) { |
| | | alert(`仅支持 ${allowedExtensions.join(', ')} 格式的文件`); |
| | | return; |
| | | } |
| | | |
| | | setUploading(true); |
| | | const formData = new FormData(); |
| | | formData.append('file', file); |
| | | |
| | | try { |
| | | const response = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8000'}/api/upload_file`, { |
| | | method: 'POST', |
| | | body: formData, |
| | | }); |
| | | |
| | | if (!response.ok) { |
| | | throw new Error('文件上传失败'); |
| | | } |
| | | |
| | | const data = await response.json(); |
| | | if (data.file_path) { |
| | | // 记录已上传的文件信息,不修改输入框 |
| | | setUploadedFile({ |
| | | name: file.name, |
| | | path: data.file_path |
| | | }); |
| | | } |
| | | } catch (error) { |
| | | console.error('上传错误:', error); |
| | | alert('上传提取内容失败,请重试'); |
| | | } finally { |
| | | setUploading(false); |
| | | // 清空 input 方便下次选择同一文件 |
| | | if (fileInputRef.current) fileInputRef.current.value = ''; |
| | | } |
| | | }; |
| | | |
| | | return ( |
| | |
| | | placeholder="描述你的视频创意... 例如:一只叫Luna的猫意外进入太空站,遇到一个孤独的宇航员" |
| | | className="w-full bg-transparent text-sm text-gray-800 placeholder-gray-400 resize-none outline-none min-h-[100px]" |
| | | onKeyDown={e => { |
| | | if (e.key === 'Enter' && !e.shiftKey && idea.trim()) { |
| | | if (e.key === 'Enter' && !e.shiftKey && (idea.trim() || uploadedFile)) { |
| | | e.preventDefault(); |
| | | handleStart(false); |
| | | } |
| | |
| | | </button> |
| | | </div> |
| | | <div className="flex items-center gap-2"> |
| | | {/* 隐藏的文件输入框 */} |
| | | <input |
| | | type="file" |
| | | ref={fileInputRef} |
| | | onChange={handleFileUpload} |
| | | accept=".doc,.docx,.txt,.md,.pdf" |
| | | className="hidden" |
| | | /> |
| | | <button |
| | | onClick={() => { |
| | | if (uploadedFile) { |
| | | setUploadedFile(null); // 已有文件则点击取消 |
| | | } else { |
| | | fileInputRef.current?.click(); |
| | | } |
| | | }} |
| | | disabled={uploading} |
| | | className={clsx( |
| | | 'flex items-center gap-2 px-5 py-2 rounded-xl text-sm font-medium transition-colors border shadow-sm relative', |
| | | uploading |
| | | ? 'bg-gray-50 text-gray-400 cursor-not-allowed border-gray-100' |
| | | : uploadedFile |
| | | ? 'bg-blue-50 text-blue-600 border-blue-100 hover:bg-blue-100' |
| | | : 'bg-white text-gray-600 hover:bg-gray-50 border-gray-200' |
| | | )} |
| | | title={uploadedFile ? `已选择: ${uploadedFile.name} (点击取消)` : "上传文档 (Word/TXT/MD)"} |
| | | > |
| | | {uploading ? ( |
| | | <Loader2 className="w-4 h-4 animate-spin" /> |
| | | ) : uploadedFile ? ( |
| | | <CheckCircle className="w-4 h-4" /> |
| | | ) : ( |
| | | <Upload className="w-4 h-4" /> |
| | | )} |
| | | {uploading ? '上传中...' : uploadedFile ? `已选: ${uploadedFile.name.length > 8 ? uploadedFile.name.substring(0, 8) + '...' : uploadedFile.name}` : '上传文件'} |
| | | {uploadedFile && ( |
| | | <div className="absolute -top-1 -right-1 bg-red-500 text-white rounded-full p-0.5"> |
| | | <X className="w-2.5 h-2.5" /> |
| | | </div> |
| | | )} |
| | | </button> |
| | | <button |
| | | onClick={() => handleStart(false)} |
| | | disabled={!idea.trim()} |
| | | disabled={!idea.trim() && !uploadedFile} |
| | | className={clsx( |
| | | 'flex items-center gap-2 px-5 py-2 rounded-xl text-sm font-medium transition-colors', |
| | | idea.trim() |
| | | (idea.trim() || uploadedFile) |
| | | ? 'bg-blue-500 text-white hover:bg-blue-600 shadow-sm' |
| | | : 'bg-gray-100 text-gray-400 cursor-not-allowed' |
| | | )} |
| | |
| | | </button> |
| | | <button |
| | | onClick={() => handleStart(true)} |
| | | disabled={!idea.trim()} |
| | | disabled={!idea.trim() && !uploadedFile} |
| | | className={clsx( |
| | | 'flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium transition-colors', |
| | | idea.trim() |
| | | (idea.trim() || uploadedFile) |
| | | ? 'bg-amber-500 text-white hover:bg-amber-600 shadow-sm' |
| | | : 'bg-gray-100 text-gray-400 cursor-not-allowed' |
| | | )} |
| | |
| | | try { |
| | | const result = await startProject({ |
| | | idea: params.idea, |
| | | file_path: params.file_path, // 修复:将上传的文件路径传给后端 |
| | | style: params.style, |
| | | video_ratio: params.video_ratio, |
| | | llm_model: params.llm_model, |
| | |
| | | |
| | | export async function startProject(params: { |
| | | idea: string; |
| | | file_path?: string; |
| | | style?: string; |
| | | video_ratio?: string; |
| | | llm_model?: string; |