Leo Liu
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -15,9 +15,45 @@ def img2text(url):
|
|
15 |
|
16 |
# text2story
|
17 |
def text2story(text):
|
18 |
-
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
|
23 |
# text2audio
|
|
|
15 |
|
16 |
# text2story
|
17 |
def text2story(text):
|
18 |
+
# 定义提示词模板(包含变量占位符)
|
19 |
+
prompt_template = f"""Write a children's story for ages 3-10 based on: {text}
|
20 |
+
Requirements:
|
21 |
+
- Use simple words
|
22 |
+
- Include a happy ending
|
23 |
+
"""
|
24 |
+
|
25 |
+
# 填充模板中的变量
|
26 |
+
full_prompt = prompt_template.format(text=text)
|
27 |
+
|
28 |
+
# 初始化生成管道
|
29 |
+
pipe = pipeline(
|
30 |
+
"text-generation",
|
31 |
+
model="pranavpsv/genre-story-generator-v2",
|
32 |
+
max_new_tokens=180,
|
33 |
+
min_new_tokens=130,
|
34 |
+
temperature=0.7
|
35 |
+
)
|
36 |
+
|
37 |
+
# 生成原始文本
|
38 |
+
raw_output = pipe(full_prompt, return_full_text=False)[0]['generated_text']
|
39 |
+
|
40 |
+
# 增强版提示词移除功能
|
41 |
+
def clean_output(generated_text, prompt):
|
42 |
+
# 方法1:精确匹配移除
|
43 |
+
if generated_text.startswith(prompt):
|
44 |
+
return generated_text[len(prompt):].strip()
|
45 |
+
|
46 |
+
# 方法2:正则表达式模糊匹配
|
47 |
+
import re
|
48 |
+
pattern = re.compile(r'Write a children\'s story.*?based on:.*?\n', re.DOTALL)
|
49 |
+
cleaned = re.sub(pattern, '', generated_text, count=1)
|
50 |
+
|
51 |
+
# 移除残留的提示词片段
|
52 |
+
cleaned = cleaned.split("Requirements:")[0].strip()
|
53 |
+
return cleaned
|
54 |
+
|
55 |
+
# 返回处理后的干净文本
|
56 |
+
return clean_output(raw_output, full_prompt)
|
57 |
|
58 |
|
59 |
# text2audio
|