Leo Liu commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -11,26 +11,46 @@ def img2text(url):
|
|
| 11 |
|
| 12 |
# text2story
|
| 13 |
def text2story(text):
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
do_sample=True,
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
|
| 36 |
# text2audio
|
|
|
|
| 11 |
|
| 12 |
# text2story
|
| 13 |
def text2story(text):
|
| 14 |
+
# 结构化prompt模板(强制模型遵循起承转合)
|
| 15 |
+
prompt = f"""Write a COMPLETE fairy tale for children aged 3-10. Follow these rules:
|
| 16 |
+
[STORY STRUCTURE]
|
| 17 |
+
1. BEGINNING: Introduce characters and setting (20-30 words)
|
| 18 |
+
2. MIDDLE: Describe a magical problem (40-60 words)
|
| 19 |
+
3. ENDING: Show how kindness/courage solves it (30-40 words)
|
| 20 |
+
|
| 21 |
+
[EXAMPLE]
|
| 22 |
+
Input: "a forest with glowing mushrooms"
|
| 23 |
+
Output: "Little fox Luna found glowing mushrooms deep in the forest. They were fairy homes! When a storm threatened to destroy them, Luna bravely built a leaf umbrella to protect the tiny homes. The grateful fairies made her forest guardian, and they danced under moonbeams every night."
|
| 24 |
+
|
| 25 |
+
[INPUT SCENE]: {text}
|
| 26 |
+
[STORY]:""" # 用方括号明确区分指令和内容
|
| 27 |
+
|
| 28 |
+
pipe = pipeline(
|
| 29 |
+
"text-generation",
|
| 30 |
+
model="pranavpsv/genre-story-generator-v2",
|
| 31 |
+
max_new_tokens=300, # 预留冗余空间
|
| 32 |
+
min_new_tokens=100,
|
| 33 |
do_sample=True,
|
| 34 |
+
temperature=0.65, # 降低随机性
|
| 35 |
+
top_p=0.85,
|
| 36 |
+
top_k=30, # 加速生成
|
| 37 |
+
repetition_penalty=1.3,
|
| 38 |
+
no_repeat_ngram_size=3, # 防止重复短语
|
| 39 |
+
early_stopping=False # 避免提前终止
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
# 生成并后处理
|
| 43 |
+
raw_output = pipe(prompt, return_full_text=False)[0]['generated_text']
|
| 44 |
+
|
| 45 |
+
# 提取核心内容(适配模型输出模式)
|
| 46 |
+
if "[STORY]:" in raw_output:
|
| 47 |
+
story = raw_output.split("[STORY]:")[-1].strip()
|
| 48 |
+
else:
|
| 49 |
+
story = raw_output
|
| 50 |
+
|
| 51 |
+
# 智能截断机制
|
| 52 |
+
target_length = min(max(len(story.split()), 150) # 动态适配
|
| 53 |
+
return " ".join(story.split()[:target_length])
|
| 54 |
|
| 55 |
|
| 56 |
# text2audio
|