Leo Liu commited on
Commit
49f2ed6
·
verified ·
1 Parent(s): 96702ff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -19
app.py CHANGED
@@ -11,26 +11,46 @@ def img2text(url):
11
 
12
  # text2story
13
  def text2story(text):
14
- pipe = pipeline("text-generation", model="pranavpsv/genre-story-generator-v2")
15
- # 构造 prompt,但只用于内部生成,不让模型在最终输出中重复 prompt
16
- prompt = (
17
- f"Write a complete fairy tale story for children aged 3-10. "
18
- f"The story should be engaging, imaginative, and written in clear simple language. "
19
- f"Make sure the story is between 50 and 150 words. "
20
- f"Use the following scene description as inspiration: {text}"
21
- )
22
- # 通过 return_full_text=False,避免将 prompt 原样拼接在输出里
23
- # 同时使用 max_new_tokens 控制生成长度,防止生成被截断或过长
24
- story_text = pipe(
25
- prompt,
26
- max_new_tokens=250, # 根据需要可适当调大,以保证字数
27
- min_new_tokens=50, # 保证至少生成一定长度
 
 
 
 
 
28
  do_sample=True,
29
- top_p=0.95,
30
- temperature=0.8,
31
- return_full_text=False
32
- )[0]['generated_text']
33
- return story_text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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