Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import google.generativeai as genai
|
|
|
|
| 3 |
from groq import Groq
|
| 4 |
import os
|
| 5 |
import json
|
|
@@ -14,14 +15,13 @@ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
|
| 14 |
|
| 15 |
# Hugging Face SpacesのSecretsに設定されているかチェック
|
| 16 |
if not GEMINI_API_KEY or not GROQ_API_KEY:
|
| 17 |
-
# ローカルでの実行のために、環境変数が設定されていない場合はダミー値を設定
|
| 18 |
print("警告: APIキーがSecretsに設定されていません。")
|
| 19 |
# 実行を止めないようにダミーを設定(デプロイ時はSecrets設定が必須)
|
| 20 |
GEMINI_API_KEY = "your_gemini_api_key_here"
|
| 21 |
GROQ_API_KEY = "your_groq_api_key_here"
|
| 22 |
|
| 23 |
genai.configure(api_key=GEMINI_API_KEY)
|
| 24 |
-
gemini_model = genai.GenerativeModel('gemini-
|
| 25 |
groq_client = Groq(api_key=GROQ_API_KEY)
|
| 26 |
|
| 27 |
print("日本語感情分析モデルをロード中...")
|
|
@@ -72,6 +72,10 @@ def detect_scene_change(history, message):
|
|
| 72 |
"""
|
| 73 |
try:
|
| 74 |
response = gemini_model.generate_content(prompt, generation_config={"temperature": 0.0})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
scene_name = response.text.strip().lower()
|
| 76 |
if scene_name != "none" and re.match(r'^[a-z0-9_]+$', scene_name):
|
| 77 |
return scene_name
|
|
@@ -104,6 +108,7 @@ def generate_scene_instruction_with_groq(affection, stage_name, scene, previous_
|
|
| 104 |
print(f"指示書生成エラー(Groq): {e}")
|
| 105 |
return None
|
| 106 |
|
|
|
|
| 107 |
def generate_dialogue_with_gemini(history, message, affection, stage_name, scene_params, instruction=None):
|
| 108 |
history_text = "\n".join([f"ユーザー: {u}\n麻理: {m}" for u, m in history])
|
| 109 |
task_prompt = f"指示: {instruction}" if instruction else f"ユーザー: {message}"
|
|
@@ -124,10 +129,32 @@ def generate_dialogue_with_gemini(history, message, affection, stage_name, scene
|
|
| 124 |
麻理:
|
| 125 |
"""
|
| 126 |
print(f"Geminiに応答生成をリクエストします (モード: {'シーン遷移' if instruction else '通常会話'})")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
try:
|
| 128 |
generation_config = genai.types.GenerationConfig(max_output_tokens=200, temperature=0.95)
|
| 129 |
-
response = gemini_model.generate_content(
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
except Exception as e:
|
| 132 |
print(f"応答生成エラー(Gemini): {e}")
|
| 133 |
return "(ごめんなさい、ちょっと考えがまとまらない……)"
|
|
@@ -175,7 +202,6 @@ def respond(message, chat_history, affection, history, scene_params):
|
|
| 175 |
|
| 176 |
theme_name = final_scene_params.get("theme", "default")
|
| 177 |
|
| 178 |
-
# 背景レイヤーのHTMLコンテンツをクラス名付きで生成
|
| 179 |
background_html = f'<div class="chat-background {theme_name}"></div>'
|
| 180 |
|
| 181 |
return "", chat_history, new_affection, stage_name, new_affection, new_history, final_scene_params, background_html
|
|
@@ -190,18 +216,14 @@ with gr.Blocks(css="style.css", theme=gr.themes.Soft(primary_hue="rose", seconda
|
|
| 190 |
gr.Markdown("# 麻理チャット")
|
| 191 |
with gr.Row():
|
| 192 |
with gr.Column(scale=2):
|
| 193 |
-
# チャットボットと背景を重ねるためのコンテナ
|
| 194 |
with gr.Column(elem_id="chat_container"):
|
| 195 |
-
# 背景レイヤー
|
| 196 |
background_display = gr.HTML(
|
| 197 |
f'<div class="chat-background {DEFAULT_SCENE_PARAMS["theme"]}"></div>',
|
| 198 |
elem_id="background_container"
|
| 199 |
)
|
| 200 |
-
# チャットボット
|
| 201 |
chatbot = gr.Chatbot(
|
| 202 |
label="麻理との会話", bubble_full_width=False, elem_id="chat_area", show_label=False
|
| 203 |
)
|
| 204 |
-
|
| 205 |
msg_input = gr.Textbox(
|
| 206 |
label="あなたのメッセージ",
|
| 207 |
placeholder="「水族館はどう?」と聞いた後、「いいね、行こう!」のように返してみてください",
|
|
@@ -212,13 +234,11 @@ with gr.Blocks(css="style.css", theme=gr.themes.Soft(primary_hue="rose", seconda
|
|
| 212 |
stage_display = gr.Textbox(label="現在の関係ステージ", interactive=False, value=get_relationship_stage(30))
|
| 213 |
affection_gauge = gr.Slider(minimum=0, maximum=100, label="麻理の好感度", value=30, interactive=False)
|
| 214 |
|
| 215 |
-
# 応答関数とUIコンポーネントの接続を更新
|
| 216 |
msg_input.submit(
|
| 217 |
respond,
|
| 218 |
[msg_input, chatbot, affection_state, history_state, scene_state],
|
| 219 |
[msg_input, chatbot, affection_gauge, stage_display, affection_state, history_state, scene_state, background_display]
|
| 220 |
)
|
| 221 |
-
# ページロード時に初期ステージを表示
|
| 222 |
demo.load(lambda affection: get_relationship_stage(affection), affection_state, stage_display)
|
| 223 |
|
| 224 |
if __name__ == "__main__":
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import google.generativeai as genai
|
| 3 |
+
from google.generativeai.types import HarmCategory, HarmBlockThreshold
|
| 4 |
from groq import Groq
|
| 5 |
import os
|
| 6 |
import json
|
|
|
|
| 15 |
|
| 16 |
# Hugging Face SpacesのSecretsに設定されているかチェック
|
| 17 |
if not GEMINI_API_KEY or not GROQ_API_KEY:
|
|
|
|
| 18 |
print("警告: APIキーがSecretsに設定されていません。")
|
| 19 |
# 実行を止めないようにダミーを設定(デプロイ時はSecrets設定が必須)
|
| 20 |
GEMINI_API_KEY = "your_gemini_api_key_here"
|
| 21 |
GROQ_API_KEY = "your_groq_api_key_here"
|
| 22 |
|
| 23 |
genai.configure(api_key=GEMINI_API_KEY)
|
| 24 |
+
gemini_model = genai.GenerativeModel('gemini-1.5-flash')
|
| 25 |
groq_client = Groq(api_key=GROQ_API_KEY)
|
| 26 |
|
| 27 |
print("日本語感情分析モデルをロード中...")
|
|
|
|
| 72 |
"""
|
| 73 |
try:
|
| 74 |
response = gemini_model.generate_content(prompt, generation_config={"temperature": 0.0})
|
| 75 |
+
# ★ 安全性チェックを追加
|
| 76 |
+
if not response.candidates or response.candidates[0].finish_reason not in {1, 'STOP'}:
|
| 77 |
+
print(f"シーン検出LLMで応答がブロックされました: {response.prompt_feedback}")
|
| 78 |
+
return None
|
| 79 |
scene_name = response.text.strip().lower()
|
| 80 |
if scene_name != "none" and re.match(r'^[a-z0-9_]+$', scene_name):
|
| 81 |
return scene_name
|
|
|
|
| 108 |
print(f"指示書生成エラー(Groq): {e}")
|
| 109 |
return None
|
| 110 |
|
| 111 |
+
# ★★★★★ ここが重要な修正点 ★★★★★
|
| 112 |
def generate_dialogue_with_gemini(history, message, affection, stage_name, scene_params, instruction=None):
|
| 113 |
history_text = "\n".join([f"ユーザー: {u}\n麻理: {m}" for u, m in history])
|
| 114 |
task_prompt = f"指示: {instruction}" if instruction else f"ユーザー: {message}"
|
|
|
|
| 129 |
麻理:
|
| 130 |
"""
|
| 131 |
print(f"Geminiに応答生成をリクエストします (モード: {'シーン遷移' if instruction else '通常会話'})")
|
| 132 |
+
|
| 133 |
+
# ★ ぶっきらぼうなキャラ設定のため、安全設定を調整
|
| 134 |
+
safety_settings = {
|
| 135 |
+
HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,
|
| 136 |
+
HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
|
| 137 |
+
HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
|
| 138 |
+
HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
try:
|
| 142 |
generation_config = genai.types.GenerationConfig(max_output_tokens=200, temperature=0.95)
|
| 143 |
+
response = gemini_model.generate_content(
|
| 144 |
+
system_prompt,
|
| 145 |
+
generation_config=generation_config,
|
| 146 |
+
safety_settings=safety_settings # ★ 安全設定を適用
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
# ★ 応答が正常に生成されたかを確認してから .text にアクセスする
|
| 150 |
+
if response.candidates and response.candidates[0].finish_reason in {1, 'STOP'}:
|
| 151 |
+
return response.text.strip()
|
| 152 |
+
else:
|
| 153 |
+
# 安全フィルターなどでブロックされた場合のフォールバック
|
| 154 |
+
print(f"応答生成が途中で終了しました。理由: {response.candidates[0].finish_reason if response.candidates else 'N/A'}")
|
| 155 |
+
print(f"Prompt Feedback: {response.prompt_feedback}")
|
| 156 |
+
return "(……何か言おうとしたけど、言葉に詰まった)"
|
| 157 |
+
|
| 158 |
except Exception as e:
|
| 159 |
print(f"応答生成エラー(Gemini): {e}")
|
| 160 |
return "(ごめんなさい、ちょっと考えがまとまらない……)"
|
|
|
|
| 202 |
|
| 203 |
theme_name = final_scene_params.get("theme", "default")
|
| 204 |
|
|
|
|
| 205 |
background_html = f'<div class="chat-background {theme_name}"></div>'
|
| 206 |
|
| 207 |
return "", chat_history, new_affection, stage_name, new_affection, new_history, final_scene_params, background_html
|
|
|
|
| 216 |
gr.Markdown("# 麻理チャット")
|
| 217 |
with gr.Row():
|
| 218 |
with gr.Column(scale=2):
|
|
|
|
| 219 |
with gr.Column(elem_id="chat_container"):
|
|
|
|
| 220 |
background_display = gr.HTML(
|
| 221 |
f'<div class="chat-background {DEFAULT_SCENE_PARAMS["theme"]}"></div>',
|
| 222 |
elem_id="background_container"
|
| 223 |
)
|
|
|
|
| 224 |
chatbot = gr.Chatbot(
|
| 225 |
label="麻理との会話", bubble_full_width=False, elem_id="chat_area", show_label=False
|
| 226 |
)
|
|
|
|
| 227 |
msg_input = gr.Textbox(
|
| 228 |
label="あなたのメッセージ",
|
| 229 |
placeholder="「水族館はどう?」と聞いた後、「いいね、行こう!」のように返してみてください",
|
|
|
|
| 234 |
stage_display = gr.Textbox(label="現在の関係ステージ", interactive=False, value=get_relationship_stage(30))
|
| 235 |
affection_gauge = gr.Slider(minimum=0, maximum=100, label="麻理の好感度", value=30, interactive=False)
|
| 236 |
|
|
|
|
| 237 |
msg_input.submit(
|
| 238 |
respond,
|
| 239 |
[msg_input, chatbot, affection_state, history_state, scene_state],
|
| 240 |
[msg_input, chatbot, affection_gauge, stage_display, affection_state, history_state, scene_state, background_display]
|
| 241 |
)
|
|
|
|
| 242 |
demo.load(lambda affection: get_relationship_stage(affection), affection_state, stage_display)
|
| 243 |
|
| 244 |
if __name__ == "__main__":
|