sofiamak commited on
Commit
85a989b
·
verified ·
1 Parent(s): 27420bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -220
app.py CHANGED
@@ -1,272 +1,97 @@
1
- import os, html, random
2
  import gradio as gr
3
  from openai import OpenAI
4
 
5
- # ==== 基础配置 ====
6
  API_KEY = os.getenv("OPENAI_API_KEY")
7
  MODEL_NAME = "gpt-4o-mini"
8
  client = OpenAI(api_key=API_KEY)
9
 
10
- # ==== 系统提示:可爱名字 + 真实名言,灵感优先 ====
11
  SYSTEM_PROMPT = """You are a playful, high-creativity pet name generator.
12
  Goal: Produce EXACTLY ONE cute, kid-pronounceable pet name + one authentic quote line.
13
-
14
- Creative balance:
15
- - Inspiration source (山海经 / 迪士尼 / 哈利波特 / 生活) drives the concept (~70%).
16
- - User inputs (species/appearance/personality/gender) refine the vibe (~30%).
17
- - Keep outputs imaginative; do NOT overfit to traits.
18
-
19
- NAME rules (must be easy for kids):
20
- - Keep it cute, round, and easy to call.
21
- - Length guidance by language:
22
- • Chinese: 1–2 simple characters (avoid rare characters).
23
- • English: 1–2 syllables (e.g., “Momo”, “Pip”, “Nori”).
24
- • Japanese: 2–3 mora, open vowels preferred (e.g., “Momo”, “Koko”).
25
- • Korean: 2 simple syllables (e.g., “Bori”, “Toto”).
26
- • French: 1–2 syllables with soft endings (-ou, -i, -ette).
27
- - You MAY coin a new word if it sounds cute and natural.
28
- - Output in the requested language (Chinese/English/Japanese/Korean/French).
29
- - Provide ONE short meaning/explanation (≤12 words), theme-first, traits-second.
30
- - No numbers; no long phrases.
31
-
32
- QUOTE rules (must be real):
33
- - After the name line, provide ONE short, warm, authentic quote about animals/love/companionship/playfulness.
34
- - Use a real, verifiable author/work/proverb; include attribution (e.g., — Anatole France).
35
- - Translate the quote text into the requested language if needed, attribution kept in Latin script.
36
-
37
- STRICT OUTPUT (exactly two lines):
38
- Name — short meaning
39
- Quote: “...” — Attribution
40
  """
41
 
42
  def build_prompt(species, look, personality, gender, language, inspiration):
43
  return f"""
44
  Requested language: {language}
45
  Primary inspiration source: {inspiration}
46
- Secondary refinements (may be empty):
47
  - Species: {species or '(unspecified)'}
48
  - Appearance: {look or '(unspecified)'}
49
  - Personality: {personality or '(unspecified)'}
50
  - Gender: {gender}
51
-
52
  Task:
53
- 1) Create EXACTLY ONE cute, kid-pronounceable pet name (≤12-word meaning).
54
- 2) Then output ONE authentic, warm animal-related quote with attribution.
55
- Remember: inspiration first (~70%), traits second (~30%); keep both lines in {language}.
56
  """
57
 
58
- # ---- 名言兜底(真实名言的多语言版本) ----
59
- FALLBACK_QUOTES = {
60
- "English": [
61
- ('"Until one has loved an animal, a part of one\'s soul remains unawakened."', "Anatole France"),
62
- ('"An animal\'s eyes have the power to speak a great language."', "Martin Buber"),
63
- ('"Animals are such agreeable friends—they ask no questions; they pass no criticisms."', "George Eliot"),
64
- ],
65
- "中文": [
66
- ('“一个人若未曾爱过动物,他的灵魂尚未苏醒。”', "Anatole France"),
67
- ('“动物的眼睛自有它们的语言。”', "Martin Buber"),
68
- ('“动物是极好的朋友——它们不发问,也不挑剔。”', "George Eliot"),
69
- ],
70
- "日本語": [
71
- ('「動物を愛したことのない者の魂は、まだ目覚めていない。」', "Anatole France"),
72
- ('「動物の瞳は偉大な言葉を語る力を持つ。」', "Martin Buber"),
73
- ('「動物は実に快い友である——問いも批判もない。」', "George Eliot"),
74
- ],
75
- "한국어": [
76
- ('“동물을 사랑해 보지 않은 영혼은 아직 깨어나지 않았다.”', "Anatole France"),
77
- ('“동물의 눈에는 위대한 언어가 담겨 있다.”', "Martin Buber"),
78
- ('“동물은 참으로 상냥한 친구다—묻지도 비난하지도 않는다.”', "George Eliot"),
79
- ],
80
- "Français": [
81
- ("« Jusqu'à ce qu'on ait aimé un animal, une partie de notre âme reste endormie. »", "Anatole France"),
82
- ("« Les yeux d’un animal ont le pouvoir de parler un grand langage. »", "Martin Buber"),
83
- ("« Les animaux sont de si agréables amis — ils ne posent aucune question et ne font aucune critique. »", "George Eliot"),
84
- ],
85
- }
86
-
87
- def get_fallback_quote(language: str):
88
- lang = language if language in FALLBACK_QUOTES else "English"
89
- text, author = random.choice(FALLBACK_QUOTES[lang])
90
- return f'Quote: {text} — {author}'
91
-
92
- def ensure_two_lines_and_split(content: str, language: str):
93
- if not content:
94
- return None, None
95
- lines = [ln.strip() for ln in content.splitlines() if ln.strip()]
96
- name_line = lines[0] if lines else ""
97
- quote_line = None
98
- for ln in lines[1:]:
99
- if ln.lower().startswith("quote:"):
100
- quote_line = ln
101
- break
102
- if not quote_line:
103
- quote_line = get_fallback_quote(language)
104
- return name_line, quote_line
105
-
106
- def render_result_html(name_line: str, quote_line: str) -> str:
107
- name_safe = html.escape(name_line or "")
108
- quote_safe = html.escape(quote_line or "")
109
- return f"""
110
- <div class="pm-result-card">
111
- <div class="pm-name">{name_safe}</div>
112
- <div class="pm-quote">{quote_safe}</div>
113
- </div>
114
- """
115
-
116
  def generate_name(species, look, personality, gender, language, inspiration):
117
  try:
118
- prompt = build_prompt(
119
- (species or "").strip(),
120
- (look or "").strip(),
121
- (personality or "").strip(),
122
- gender, language, inspiration
123
- )
124
  resp = client.chat.completions.create(
125
  model=MODEL_NAME,
126
- temperature=0.95,
127
- top_p=0.95,
128
  max_tokens=280,
129
  messages=[
130
  {"role": "system", "content": SYSTEM_PROMPT},
131
- {"role": "user", "content": prompt}
132
  ]
133
  )
134
  raw = (resp.choices[0].message.content or "").strip()
135
- name_line, quote_line = ensure_two_lines_and_split(raw, language)
136
- if not (name_line and quote_line):
137
- html_card = render_result_html("(没有生成内容,请稍后再试)", "")
138
- return html_card, ""
139
- html_card = render_result_html(name_line, quote_line)
140
- plain_text = (name_line + "\n" + quote_line).strip()
141
- return html_card, plain_text
142
  except Exception as e:
143
- return render_result_html(f"⚠️ 出错:{html.escape(str(e))}", ""), ""
144
 
145
- # ======= 主题与样式 =======
146
- theme = gr.themes.Soft(
147
- primary_hue="pink",
148
- secondary_hue="cyan",
149
- neutral_hue="slate"
150
- )
151
 
152
- CUSTOM_CSS = """
153
- :root{
154
- --pm-bg:#faf7fb;
155
- --pm-surface:#ffffff;
156
- --pm-border:#eddcf3;
157
- --pm-text:#111;
158
- --pm-muted:#6b7280;
159
- }
160
- body, .gradio-container{ background:var(--pm-bg) !important; }
161
-
162
- /* 顶栏 */
163
- .pm-topbar{
164
- display:flex; align-items:center; justify-content:space-between;
165
- padding:12px 12px; background:linear-gradient(90deg,#ffe8f3,#e8fbff);
166
- border:1px solid var(--pm-border); border-radius:12px;
167
- }
168
- .pm-brand{ display:flex; align-items:center; gap:10px; }
169
- .pm-logo{ font-size:24px; }
170
- .pm-title{ font-weight:800; font-size:20px; color:var(--pm-text); }
171
- .pm-sub{ color:var(--pm-muted); font-size:12px; }
172
-
173
- /* 卡片 */
174
- .pm-card{
175
- background:var(--pm-surface); border:1px solid var(--pm-border); border-radius:12px;
176
- box-shadow:0 4px 18px rgba(17,17,17,0.04); padding:16px;
177
- }
178
-
179
- /* 结果卡片 */
180
- .pm-result-card{
181
- background:var(--pm-surface);
182
- border:1px solid var(--pm-border);
183
- border-radius:14px; padding:18px;
184
- box-shadow:0 10px 26px rgba(255,79,163,0.08);
185
- }
186
- .pm-name{
187
- font-weight:800; font-size:24px; color:var(--pm-text); margin-bottom:10px;
188
- }
189
- .pm-quote{
190
- font-weight:600; font-size:14px; color:#374151; opacity:.95;
191
- }
192
-
193
- .pm-footer{
194
- text-align:center; color:var(--pm-muted); font-size:12px; margin-top:10px;
195
- }
196
- """
197
-
198
- # ======= 界面布局 =======
199
- with gr.Blocks(title="Pawfect Match", theme=theme, css=CUSTOM_CSS) as demo:
200
- # 顶栏
201
  gr.HTML("""
202
- <div class="pm-topbar">
203
- <div class="pm-brand">
204
- <div class="pm-logo">🐾</div>
205
- <div>
206
- <div class="pm-title">Pawfect Match</div>
207
- <div class="pm-sub">Cute pet naming • Inspired by myth & magic</div>
208
- </div>
209
  </div>
210
- <div class="pm-sub">v1.4</div>
211
  </div>
212
  """)
213
 
214
- with gr.Row():
215
- # 左侧:输入卡
216
- with gr.Column(scale=6):
217
- with gr.Group(elem_classes=["pm-card"]):
218
- gr.Markdown("#### 基本信息")
219
- species = gr.Textbox(label="宠物种类", placeholder="例:金毛 / 英短 / 仓鼠 / 鹦鹉(可留空)", autofocus=True)
220
- look = gr.Textbox(label="外表特征", placeholder="例:橘色短毛,大眼睛,白爪(可留空)")
221
- personality = gr.Textbox(label="性格特点", placeholder="例:粘人、活泼、聪明(可留空)")
222
- with gr.Row():
223
- gender = gr.Radio(["male","female"], value="male", label="宠物性别")
224
- language = gr.Radio(["中文","English","日本語","한국어","Français"], value="English", label="输出语言")
225
-
226
- with gr.Group(elem_classes=["pm-card"]):
227
- gr.Markdown("#### 灵感来源")
228
- inspiration = gr.Radio(["山海经","迪士尼","哈利波特","生活"], value="生活", label="", info="决定整体风格(主题优先)")
229
-
230
- with gr.Group(elem_classes=["pm-card"]):
231
- gr.Markdown("#### 操作")
232
- btn = gr.Button("✨ 起名", variant="primary")
233
- clear_btn = gr.Button("清空", variant="secondary")
234
 
235
- with gr.Accordion("快速示例(点击自动填充)", open=False):
236
- gr.Examples(
237
- examples=[
238
- ["英短猫","银渐层,圆脸,绿眼睛","高冷但会撒娇","female","中文","迪士尼"],
239
- ["柯基犬","短腿、红白毛、笑脸","亲人、活泼、贪吃","male","English","生活"],
240
- ["狸花猫","虎斑、黄眼睛","机灵好奇","male","日本語","山海经"],
241
- ["小型犬","白色卷毛","温柔、爱撒娇","female","Français","哈利波特"],
242
- ],
243
- inputs=[species, look, personality, gender, language, inspiration],
244
- )
245
-
246
- # 右侧:结果卡 + 可复制文本框
247
- with gr.Column(scale=6):
248
- with gr.Group(elem_classes=["pm-card"]):
249
- gr.Markdown("#### 结果")
250
- out_html = gr.HTML(value="""
251
- <div class="pm-result-card">
252
- <div class="pm-name">(点击「✨ 起名」后显示)</div>
253
- <div class="pm-quote"></div>
254
- </div>
255
- """)
256
- out_plain = gr.Textbox(label="复制结果(点右侧复制图标)", value="", interactive=False, show_copy_button=True, lines=3)
257
 
258
- gr.HTML('<div class="pm-footer">© Pawfect Match</div>')
 
259
 
260
- # 交互
261
  btn.click(
262
  generate_name,
263
  inputs=[species, look, personality, gender, language, inspiration],
264
- outputs=[out_html, out_plain]
 
 
 
 
 
 
 
 
 
 
265
  )
266
 
267
  clear_btn.click(
268
- lambda: ("","","","male","English","生活",""),
269
- outputs=[species, look, personality, gender, language, inspiration, out_plain]
270
  )
271
 
272
  if __name__ == "__main__":
 
1
+ import os, html
2
  import gradio as gr
3
  from openai import OpenAI
4
 
 
5
  API_KEY = os.getenv("OPENAI_API_KEY")
6
  MODEL_NAME = "gpt-4o-mini"
7
  client = OpenAI(api_key=API_KEY)
8
 
 
9
  SYSTEM_PROMPT = """You are a playful, high-creativity pet name generator.
10
  Goal: Produce EXACTLY ONE cute, kid-pronounceable pet name + one authentic quote line.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  """
12
 
13
  def build_prompt(species, look, personality, gender, language, inspiration):
14
  return f"""
15
  Requested language: {language}
16
  Primary inspiration source: {inspiration}
17
+ Secondary refinements:
18
  - Species: {species or '(unspecified)'}
19
  - Appearance: {look or '(unspecified)'}
20
  - Personality: {personality or '(unspecified)'}
21
  - Gender: {gender}
 
22
  Task:
23
+ 1) Generate one cute pet name
24
+ 2) Provide one authentic quote
 
25
  """
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  def generate_name(species, look, personality, gender, language, inspiration):
28
  try:
29
+ prompt = build_prompt(species, look, personality, gender, language, inspiration)
 
 
 
 
 
30
  resp = client.chat.completions.create(
31
  model=MODEL_NAME,
32
+ temperature=0.9,
 
33
  max_tokens=280,
34
  messages=[
35
  {"role": "system", "content": SYSTEM_PROMPT},
36
+ {"role": "user", "content": prompt}
37
  ]
38
  )
39
  raw = (resp.choices[0].message.content or "").strip()
40
+ return raw
 
 
 
 
 
 
41
  except Exception as e:
42
+ return f"⚠️ 出错:{html.escape(str(e))}"
43
 
44
+ theme = gr.themes.Soft(primary_hue="pink", secondary_hue="cyan", neutral_hue="slate")
 
 
 
 
 
45
 
46
+ with gr.Blocks(title="Pawfect Match", theme=theme) as demo:
47
+ # 顶栏(只保留标题,没有副标题)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  gr.HTML("""
49
+ <div style="display:flex;align-items:center;justify-content:space-between;
50
+ padding:12px;background:linear-gradient(90deg,#ffe8f3,#e8fbff);
51
+ border-radius:12px;border:1px solid #eddcf3;">
52
+ <div style="display:flex;align-items:center;gap:10px;">
53
+ <div style="font-size:24px;">🐾</div>
54
+ <div style="font-weight:800;font-size:20px;color:#111;">Pawfect Match</div>
 
55
  </div>
56
+ <div style="color:#6b7280;font-size:12px;">v1.6</div>
57
  </div>
58
  """)
59
 
60
+ with gr.Group():
61
+ species = gr.Textbox(label="宠物种类")
62
+ look = gr.Textbox(label="外表特征")
63
+ personality = gr.Textbox(label="性格特点")
64
+ with gr.Row():
65
+ gender = gr.Radio(["male","female"], value="male", label="宠物性别")
66
+ language = gr.Radio(["中文","English","日本語","한국어","Français"], value="English", label="输出语言")
67
+ inspiration = gr.Radio(["山海经","迪士尼","哈利波特","生活"], value="生活", label="灵感来源")
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
+ with gr.Row():
70
+ btn = gr.Button("✨ 起名", variant="primary")
71
+ clear_btn = gr.Button("清空", variant="secondary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
+ # 点击生成后,不输出到文本框,而是触发前端弹窗
74
+ out = gr.Textbox(visible=False)
75
 
 
76
  btn.click(
77
  generate_name,
78
  inputs=[species, look, personality, gender, language, inspiration],
79
+ outputs=out,
80
+ js="""
81
+ (result) => {
82
+ if (result) {
83
+ alert(result);
84
+ } else {
85
+ alert("没有生成结果,请重试。");
86
+ }
87
+ return result;
88
+ }
89
+ """
90
  )
91
 
92
  clear_btn.click(
93
+ lambda: ("","","","male","English","生活"),
94
+ outputs=[species, look, personality, gender, language, inspiration]
95
  )
96
 
97
  if __name__ == "__main__":