Spaces:
Sleeping
Sleeping
File size: 5,919 Bytes
e4b106f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | """
Gemini ์ฑ๋ด - Gradio ๋ฒ์
Google Search๋ก ์ต์ ์ ๋ณด๋ฅผ ๊ฒ์ํ๋ AI ์ฑ๋ด
"""
import os
import json
import datetime
from google import genai
from google.genai import types
import gradio as gr
# ============================================================
# 1. Gemini์๊ฒ ๋ฉ์์ง ๋ณด๋ด๊ธฐ
# ============================================================
def send_message(user_message, chat_history, api_key, system_prompt, use_search):
"""์ฌ์ฉ์ ๋ฉ์์ง๋ฅผ Gemini์๊ฒ ๋ณด๋ด๊ณ ์๋ต์ ๋ฐ์ต๋๋ค."""
# API Key ํ์ธ
if not api_key or not api_key.strip():
chat_history.append({"role": "user", "content": user_message})
chat_history.append({"role": "assistant", "content": "โ ๏ธ API Key๋ฅผ ์
๋ ฅํด์ฃผ์ธ์."})
return "", chat_history
# ๋น ๋ฉ์์ง ํ์ธ
if not user_message or not user_message.strip():
return "", chat_history
# ํด๋ผ์ด์ธํธ ์์ฑ
client = genai.Client(api_key=api_key.strip())
# ํ์ฌ ๋ ์ง๋ฅผ ์์คํ
ํ๋กฌํํธ์ ์ถ๊ฐ
today = datetime.date.today().strftime("%Y-%m-%d")
base_instruction = f"์ค๋ ๋ ์ง๋ {today}์
๋๋ค. ์ต์ ์ ๋ณด๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ต๋ณํ์ธ์."
if system_prompt and system_prompt.strip():
full_instruction = f"{base_instruction}\n{system_prompt.strip()}"
else:
full_instruction = base_instruction
# ๋๊ตฌ ์ค์ (Google Search)
tools = []
if use_search:
tools = [types.Tool(google_search=types.GoogleSearch())]
# ์ค์
config = types.GenerateContentConfig(
system_instruction=full_instruction,
tools=tools if tools else None,
)
# ๋ํ ๊ธฐ๋ก์ Gemini ํ์์ผ๋ก ๋ณํ
contents = []
for msg in chat_history:
# Gradio 6์์ content๊ฐ ๋ฆฌ์คํธ๋ก ์ฌ ์ ์์
content = msg["content"]
if isinstance(content, list):
content = "".join(part["text"] for part in content if "text" in part)
role = "user" if msg["role"] == "user" else "model"
contents.append(types.Content(role=role, parts=[types.Part(text=content)]))
contents.append(types.Content(role="user", parts=[types.Part(text=user_message)]))
# ๋ฉ์์ง ์ ์ก
try:
response = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents=contents,
config=config,
)
reply = response.text
except Exception as e:
reply = f"โ ์ค๋ฅ ๋ฐ์: {str(e)}"
# ๋ํ ๊ธฐ๋ก์ ์ถ๊ฐ
chat_history.append({"role": "user", "content": user_message})
chat_history.append({"role": "assistant", "content": reply})
return "", chat_history
# ============================================================
# 2. ๋ํ ๊ธฐ๋ก ์ ์ฅ
# ============================================================
def save_chat(chat_history):
"""๋ํ ๊ธฐ๋ก์ JSON ํ์ผ๋ก ์ ์ฅํฉ๋๋ค."""
if not chat_history:
return gr.update(value=None)
now = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"chat_{now}.json"
filepath = os.path.join("saved_chats", filename)
os.makedirs("saved_chats", exist_ok=True)
with open(filepath, "w", encoding="utf-8") as f:
json.dump(chat_history, f, ensure_ascii=False, indent=2)
return gr.update(value=filepath)
def clear_chat():
"""๋ํ ๊ธฐ๋ก์ ์ด๊ธฐํํฉ๋๋ค."""
return []
# ============================================================
# 3. Gradio UI ๋ง๋ค๊ธฐ
# ============================================================
with gr.Blocks(
title="Gemini ์ฑ๋ด",
) as app:
gr.Markdown("# Gemini ์ฑ๋ด")
gr.Markdown("Google Gemini API๋ฅผ ์ฌ์ฉํ๋ AI ์ฑ๋ด์
๋๋ค.")
with gr.Row():
# --- ์ผ์ชฝ: ์ค์ ํจ๋ ---
with gr.Column(scale=1):
gr.Markdown("## ์ค์ ")
api_key = gr.Textbox(
label="Gemini API Key",
placeholder="API Key๋ฅผ ์
๋ ฅํ์ธ์",
type="password",
)
system_prompt = gr.Textbox(
label="์์คํ
ํ๋กฌํํธ",
placeholder="์: ๋น์ ์ ์น์ ํ ํ๊ตญ์ด AI ๋น์์
๋๋ค.",
lines=3,
)
use_search = gr.Checkbox(
label="Google Search ์ฌ์ฉ",
value=True,
)
gr.Markdown("---")
gr.Markdown("## ๋ํ ๊ด๋ฆฌ")
save_btn = gr.Button("๋ํ ์ ์ฅ", variant="secondary")
save_output = gr.File(label="์ ์ฅ๋ ํ์ผ")
# --- ์ค๋ฅธ์ชฝ: ์ฑํ
์์ญ ---
with gr.Column(scale=3):
chatbot = gr.Chatbot(
label="๋ํ",
height=500,
)
with gr.Row():
msg = gr.Textbox(
label="๋ฉ์์ง ์
๋ ฅ",
placeholder="๋ฉ์์ง๋ฅผ ์
๋ ฅํ์ธ์...",
scale=4,
show_label=False,
)
send_btn = gr.Button("์ ์ก", variant="primary", scale=1)
clear_btn = gr.Button("๋ํ ์ด๊ธฐํ")
# --- ์ด๋ฒคํธ ์ฐ๊ฒฐ ---
send_btn.click(
fn=send_message,
inputs=[msg, chatbot, api_key, system_prompt, use_search],
outputs=[msg, chatbot],
)
msg.submit(
fn=send_message,
inputs=[msg, chatbot, api_key, system_prompt, use_search],
outputs=[msg, chatbot],
)
clear_btn.click(fn=clear_chat, outputs=[chatbot])
save_btn.click(fn=save_chat, inputs=[chatbot], outputs=[save_output])
# ============================================================
# 4. ์ฑ ์คํ
# ============================================================
if __name__ == "__main__":
app.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Soft())
|