sirochild commited on
Commit
87a7987
·
verified ·
1 Parent(s): 276c941
Files changed (3) hide show
  1. app.py +200 -0
  2. requirements.txt +7 -0
  3. style.css +40 -0
app.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import google.generativeai as genai
3
+ from groq import Groq
4
+ import os
5
+ import json
6
+ from dotenv import load_dotenv
7
+ from transformers import pipeline
8
+ import re
9
+
10
+ # --- 1. 初期設定とAPIクライアントの初期化 ---
11
+ # Hugging Face SpacesのSecretsからAPIキーを読み込む
12
+ load_dotenv()
13
+
14
+ # Geminiクライアント
15
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
16
+ if not GEMINI_API_KEY:
17
+ raise ValueError("SecretsにGEMINI_API_KEYが見つかりません。")
18
+ genai.configure(api_key=GEMINI_API_KEY)
19
+ gemini_model = genai.GenerativeModel('gemini-1.5-flash-latest')
20
+
21
+ # Groqクライアント
22
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
23
+ if not GROQ_API_KEY:
24
+ raise ValueError("SecretsにGROQ_API_KEYが見つかりません。")
25
+ groq_client = Groq(api_key=GROQ_API_KEY)
26
+
27
+ # 感情分析モデル
28
+ print("日本語感情分析モデルをロード中...")
29
+ try:
30
+ sentiment_analyzer = pipeline("sentiment-analysis", model="koheiduck/bert-japanese-finetuned-sentiment")
31
+ print("モデルのロード完了。")
32
+ except Exception as e:
33
+ sentiment_analyzer = None
34
+ print(f"モデルのロードエラー: {e}")
35
+
36
+ DEFAULT_SCENE_PARAMS = {
37
+ "theme": "default",
38
+ "personality_mod": "ストレートな感情表現をするが、少しぶっきらぼう。優しさと冷たさが混在している。",
39
+ "tone": "普通のトーン。",
40
+ "constraints": ["キャラクター設定から逸脱しない"]
41
+ }
42
+
43
+ # --- 2. LLMによる役割分担システム ---
44
+
45
+ def detect_scene_change(history, message):
46
+ history_text = "\n".join([f"ユーザー: {u}\n麻理: {m}" for u, m in history[-4:]])
47
+ prompt = f"""
48
+ あなたは会話の流れを分析するエキスパートです。以下のタスクを厳密に実行してください。
49
+ # タスク
50
+ 直近の会話履歴と最後のユーザー発言を分析し、**会話の結果として登場人物がどこか特定の場所へ行くことに合意したか**を判断してください。
51
+ # 判断基準
52
+ 1. 会話の中で具体的な場所(例:水族館、カフェ、神社)が提案されているか?
53
+ 2. 最後のユーザー発言が、その提案に対する明確な同意(例:「行こう」「いいね」「そうしよう」など)を示しているか?
54
+ # 出力形式
55
+ - 合意が成立した場合:その場所の英語キーワード(例: "aquarium_night", "cafe_afternoon")を一つだけ出力してください。
56
+ - 合意に至らなかった場合:「none」とだけ出力してください。
57
+ ---
58
+ # 分析対象の会話
59
+ {history_text}
60
+ ユーザー: {message}
61
+ ---
62
+ # 出力
63
+ """
64
+ try:
65
+ response = gemini_model.generate_content(prompt, generation_config={"temperature": 0.0})
66
+ scene_name = response.text.strip().lower()
67
+ if scene_name != "none" and re.match(r'^[a-z0-9_]+$', scene_name):
68
+ print(f"シーン変更を検出: {scene_name}")
69
+ return scene_name
70
+ return None
71
+ except Exception as e:
72
+ print(f"シーン検出LLMエラー: {e}")
73
+ return None
74
+
75
+ def generate_scene_instruction_with_groq(affection, stage_name, scene, previous_topic):
76
+ print("Groq/Llama3に「指示書」生成をリクエストします...")
77
+ prompt_template = f"""
78
+ あなたは会話アプリの演出AIです。以下の条件に基づき、演出プランをJSON形式で生成してください。
79
+ 【条件】
80
+ 好感度:{affection}
81
+ 関係段階:「{stage_name}」
82
+ シーン名:「{scene}」
83
+ 直前の話題:「{previous_topic}」
84
+ 【指示】
85
+ - `initial_dialogue_instruction`には、麻理が言うべき最初のセリフの内容や感情の指示を日本語で記述してください。実際のセリフは絶対に生成しないでください。
86
+ - `personality_mod`と`tone`は、シーンと現在の関係性を反映した簡潔なものにしてください。
87
+ - 必ず、以下のJSON形式のみを出力してください。説明文は不要です。
88
+ {{
89
+ "theme": "{scene}",
90
+ "personality_mod": "(シーンと関係段階に応じた性格設定)",
91
+ "tone": "(シーンと好感度に応じた口調や感情トーン)",
92
+ "initial_dialogue_instruction": "(例:少し戸惑いながらも、提案された場所への期待感を滲ませる)",
93
+ "constraints": ["(出力時の制約1)", "(制約2)"]
94
+ }}
95
+ """
96
+ try:
97
+ chat_completion = groq_client.chat.completions.create(
98
+ messages=[{"role": "user", "content": prompt_template}],
99
+ model="llama3-8b-8192", temperature=0.7, response_format={"type": "json_object"},
100
+ )
101
+ params = json.loads(chat_completion.choices[0].message.content)
102
+ print("生成された指示書JSON:", params)
103
+ return params
104
+ except Exception as e:
105
+ print(f"指示書生成エラー(Groq): {e}")
106
+ return None
107
+
108
+ def generate_dialogue_with_gemini(history, message, affection, stage_name, scene_params, instruction=None):
109
+ history_text = "\n".join([f"ユーザー: {u}\n麻理: {m}" for u, m in history])
110
+ task_prompt = f"指示: {instruction}" if instruction else f"ユーザー: {message}"
111
+ system_prompt = f"""
112
+ あなたはAIキャラクター「麻理」です。以下の設定とタスクに従ってください。
113
+ # 設定
114
+ - 基本人格: ストレートで媚びない。ぶっきらぼうだが根は優しい。
115
+ - 現在の好感度: {affection}
116
+ - 現在の関係ステージ: {stage_name}
117
+ - 性格(ロールプレイ): {scene_params["personality_mod"]}
118
+ - 話し方のトーン: {scene_params["tone"]}
119
+ - 制約事項: {", ".join(scene_params["constraints"])}
120
+ # 会話履歴
121
+ {history_text}
122
+ ---
123
+ # タスク
124
+ {task_prompt}
125
+ 麻理:
126
+ """
127
+ try:
128
+ response = gemini_model.generate_content(system_prompt)
129
+ return response.text
130
+ except Exception as e:
131
+ print(f"応答生成エラー(Gemini): {e}")
132
+ return "(ごめんなさい、ちょっと考えがまとまらない……)"
133
+
134
+ def get_relationship_stage(affection):
135
+ if affection < 40: return "ステージ1:会話成立"
136
+ if affection < 60: return "ステージ2:親密化"
137
+ if affection < 80: return "ステージ3:信頼"
138
+ return "ステージ4:最親密"
139
+
140
+ def update_affection(message, affection):
141
+ if not sentiment_analyzer: return affection
142
+ try:
143
+ result = sentiment_analyzer(message)[0]
144
+ if result['label'] == 'positive': return min(100, affection + 5)
145
+ if result['label'] == 'negative': return max(0, affection - 5)
146
+ except Exception: return affection
147
+ return affection
148
+
149
+ def respond(message, chat_history, affection, history, scene_params):
150
+ new_affection = update_affection(message, affection)
151
+ stage_name = get_relationship_stage(new_affection)
152
+ new_scene_name = detect_scene_change(history, message)
153
+ if new_scene_name:
154
+ new_params_base = generate_scene_instruction_with_groq(new_affection, stage_name, new_scene_name, message)
155
+ if new_params_base:
156
+ final_scene_params = new_params_base
157
+ instruction = final_scene_params.get("initial_dialogue_instruction")
158
+ bot_message = generate_dialogue_with_gemini(history, message, new_affection, stage_name, final_scene_params, instruction=instruction)
159
+ else:
160
+ final_scene_params = scene_params
161
+ bot_message = generate_dialogue_with_gemini(history, message, new_affection, stage_name, final_scene_params)
162
+ else:
163
+ final_scene_params = scene_params
164
+ bot_message = generate_dialogue_with_gemini(history, message, new_affection, stage_name, final_scene_params)
165
+ new_history = history + [(message, bot_message)]
166
+ chat_history.append((message, bot_message))
167
+ theme_name = final_scene_params.get("theme", "default")
168
+ js_script = f"""
169
+ <script>
170
+ setTimeout(() => {{
171
+ const body = document.body;
172
+ const themes = ["theme-default", "theme-room_night", "theme-beach_sunset", "theme-festival_night", "theme-shrine_day", "theme-cafe_afternoon", "theme-aquarium_night"];
173
+ body.classList.remove(...themes);
174
+ body.classList.add("theme-{theme_name}");
175
+ }}, 100);
176
+ </script>
177
+ """
178
+ return "", chat_history, new_affection, stage_name, new_affection, new_history, final_scene_params, js_script
179
+
180
+ with gr.Blocks(css="style.css", theme=None) as demo:
181
+ affection_state = gr.State(30)
182
+ history_state = gr.State([])
183
+ scene_state = gr.State(DEFAULT_SCENE_PARAMS)
184
+ gr.Markdown("# 麻理チャット")
185
+ with gr.Row():
186
+ with gr.Column(scale=2):
187
+ chatbot = gr.Chatbot(label="麻理との会話", height=500)
188
+ msg_input = gr.Textbox(label="あなたのメッセージ", placeholder="「水族館はどう?」と聞いた後、「いいね、行こう!」のように返してみてください")
189
+ with gr.Column(scale=1):
190
+ stage_display = gr.Textbox(label="現在の関係ステージ", interactive=False)
191
+ affection_gauge = gr.Slider(minimum=0, maximum=100, label="麻理の好感度", interactive=False)
192
+ js_runner = gr.HTML(visible=False)
193
+ msg_input.submit(
194
+ respond,
195
+ [msg_input, chatbot, affection_state, history_state, scene_state],
196
+ [msg_input, chatbot, affection_gauge, stage_display, affection_state, history_state, scene_state, js_runner]
197
+ )
198
+
199
+ if __name__ == "__main__":
200
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio
2
+ google-generativeai
3
+ groq
4
+ python-dotenv
5
+ transformers
6
+ torch
7
+ sentencepiece
style.css ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* GradioのUI全体をラップするコンテナを指定 */
2
+ body #main_container {
3
+ transition: background-image 1s ease-in-out;
4
+ background-image: var(--background-image, url('https://i.ibb.co/XzP6K2Y/room-day.png')) !important;
5
+ background-size: cover !important;
6
+ background-position: center !important;
7
+ }
8
+
9
+ /* 各テーマの定義 */
10
+ body #main_container.theme-default {
11
+ --background-image: url('https://i.ibb.co/XzP6K2Y/room-day.png');
12
+ }
13
+ body #main_container.theme-room_night {
14
+ --background-image: url('https://i.ibb.co/d5m821p/room-night.png');
15
+ }
16
+ body #main_container.theme-beach_sunset {
17
+ --background-image: url('https://i.ibb.co/Q9r56s4/beach-sunset.png');
18
+ }
19
+ body #main_container.theme-festival_night {
20
+ --background-image: url('https://i.ibb.co/3zdJ6Bw/festival-night.png');
21
+ }
22
+ body #main_container.theme-shrine_day {
23
+ --background-image: url('https://i.ibb.co/L51Jd3x/shrine-day.png');
24
+ }
25
+ body #main_container.theme-cafe_afternoon {
26
+ --background-image: url('https://i.ibb.co/yQxG4vs/cafe-afternoon.png');
27
+ }
28
+ body #main_container.theme-aquarium_night {
29
+ --background-image: url('https://i.ibb.co/dK5r5rc/aquarium-night.png');
30
+ }
31
+
32
+ /* チャットウィンドウなどのスタイル */
33
+ #main_container .gradio-chatbot .chatbot {
34
+ background-color: rgba(255, 255, 255, 0.7) !important;
35
+ backdrop-filter: blur(5px);
36
+ }
37
+ #main_container .gradio-textbox, #main_container .gradio-slider {
38
+ background-color: rgba(255, 255, 255, 0.85) !important;
39
+ border-radius: 10px !important;
40
+ }