RAGOndevice / app.py
cutechicken's picture
Update app.py
f4a0f87 verified
raw
history blame
13.9 kB
import os
from dotenv import load_dotenv
import gradio as gr
from huggingface_hub import InferenceClient
import pandas as pd
import json
from datetime import datetime
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
# ํ™˜๊ฒฝ ๋ณ€์ˆ˜ ์„ค์ •
HF_TOKEN = os.getenv("HF_TOKEN")
MODEL_ID = "CohereForAI/c4ai-command-r7b-12-2024"
from transformers import pipeline
class ModelManager:
def __init__(self):
self.pipe = None
self.setup_pipeline()
def setup_pipeline(self):
try:
print("ํŒŒ์ดํ”„๋ผ์ธ ์ดˆ๊ธฐํ™” ์‹œ์ž‘...")
self.pipe = pipeline(
"text-generation",
model=MODEL_ID,
token=HF_TOKEN,
device_map="auto",
torch_dtype=torch.float16
)
print("ํŒŒ์ดํ”„๋ผ์ธ ์ดˆ๊ธฐํ™” ์™„๋ฃŒ")
except Exception as e:
print(f"ํŒŒ์ดํ”„๋ผ์ธ ์ดˆ๊ธฐํ™” ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}")
raise Exception(f"ํŒŒ์ดํ”„๋ผ์ธ ์ดˆ๊ธฐํ™” ์‹คํŒจ: {e}")
def generate_response(self, messages, max_tokens=4000, temperature=0.7, top_p=0.9):
try:
# ๋ฉ”์‹œ์ง€ ํ˜•์‹ ๋ณ€ํ™˜
prompt = ""
for msg in messages:
role = msg["role"]
content = msg["content"]
if role == "system":
prompt += f"System: {content}\n"
elif role == "user":
prompt += f"User: {content}\n"
elif role == "assistant":
prompt += f"Assistant: {content}\n"
# ์‘๋‹ต ์ƒ์„ฑ
response = self.pipe(
prompt,
max_new_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
do_sample=True,
num_return_sequences=1,
pad_token_id=self.pipe.tokenizer.eos_token_id
)
# ์‘๋‹ต ํ…์ŠคํŠธ ์ถ”์ถœ ๋ฐ ์ŠคํŠธ๋ฆฌ๋ฐ ์‹œ๋ฎฌ๋ ˆ์ด์…˜
generated_text = response[0]['generated_text'][len(prompt):].strip()
words = generated_text.split()
# ๋‹จ์–ด ๋‹จ์œ„๋กœ ์ŠคํŠธ๋ฆฌ๋ฐ
partial_response = ""
for word in words:
partial_response += word + " "
yield type('Response', (), {
'choices': [type('Choice', (), {
'delta': {'content': word + " "}
})()]
})()
except Exception as e:
raise Exception(f"์‘๋‹ต ์ƒ์„ฑ ์‹คํŒจ: {e}")
class ChatHistory:
def __init__(self):
self.history = []
self.history_file = "/tmp/chat_history.json"
self.load_history()
def add_conversation(self, user_msg: str, assistant_msg: str):
conversation = {
"timestamp": datetime.now().isoformat(),
"messages": [
{"role": "user", "content": user_msg},
{"role": "assistant", "content": assistant_msg}
]
}
self.history.append(conversation)
self.save_history()
def format_for_display(self):
formatted = []
for conv in self.history:
formatted.append([
conv["messages"][0]["content"],
conv["messages"][1]["content"]
])
return formatted
def get_messages_for_api(self):
messages = []
for conv in self.history:
messages.extend([
{"role": "user", "content": conv["messages"][0]["content"]},
{"role": "assistant", "content": conv["messages"][1]["content"]}
])
return messages
def clear_history(self):
self.history = []
self.save_history()
def save_history(self):
try:
with open(self.history_file, 'w', encoding='utf-8') as f:
json.dump(self.history, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"ํžˆ์Šคํ† ๋ฆฌ ์ €์žฅ ์‹คํŒจ: {e}")
def load_history(self):
try:
if os.path.exists(self.history_file):
with open(self.history_file, 'r', encoding='utf-8') as f:
self.history = json.load(f)
except Exception as e:
print(f"ํžˆ์Šคํ† ๋ฆฌ ๋กœ๋“œ ์‹คํŒจ: {e}")
self.history = []
# ์ „์—ญ ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
chat_history = ChatHistory()
model_manager = ModelManager()
def get_client():
return InferenceClient(MODEL_ID, token=HF_TOKEN)
def analyze_file_content(content, file_type):
"""Analyze file content and return structural summary"""
if file_type in ['parquet', 'csv']:
try:
lines = content.split('\n')
header = lines[0]
columns = header.count('|') - 1
rows = len(lines) - 3
return f"๐Ÿ“Š ๋ฐ์ดํ„ฐ์…‹ ๊ตฌ์กฐ: {columns}๊ฐœ ์ปฌ๋Ÿผ, {rows}๊ฐœ ๋ฐ์ดํ„ฐ"
except:
return "โŒ ๋ฐ์ดํ„ฐ์…‹ ๊ตฌ์กฐ ๋ถ„์„ ์‹คํŒจ"
lines = content.split('\n')
total_lines = len(lines)
non_empty_lines = len([line for line in lines if line.strip()])
if any(keyword in content.lower() for keyword in ['def ', 'class ', 'import ', 'function']):
functions = len([line for line in lines if 'def ' in line])
classes = len([line for line in lines if 'class ' in line])
imports = len([line for line in lines if 'import ' in line or 'from ' in line])
return f"๐Ÿ’ป ์ฝ”๋“œ ๊ตฌ์กฐ: {total_lines}์ค„ (ํ•จ์ˆ˜: {functions}, ํด๋ž˜์Šค: {classes}, ์ž„ํฌํŠธ: {imports})"
paragraphs = content.count('\n\n') + 1
words = len(content.split())
return f"๐Ÿ“ ๋ฌธ์„œ ๊ตฌ์กฐ: {total_lines}์ค„, {paragraphs}๋‹จ๋ฝ, ์•ฝ {words}๋‹จ์–ด"
def read_uploaded_file(file):
if file is None:
return "", ""
try:
file_ext = os.path.splitext(file.name)[1].lower()
if file_ext == '.parquet':
df = pd.read_parquet(file.name, engine='pyarrow')
content = df.head(10).to_markdown(index=False)
return content, "parquet"
elif file_ext == '.csv':
encodings = ['utf-8', 'cp949', 'euc-kr', 'latin1']
for encoding in encodings:
try:
df = pd.read_csv(file.name, encoding=encoding)
content = f"๐Ÿ“Š ๋ฐ์ดํ„ฐ ๋ฏธ๋ฆฌ๋ณด๊ธฐ:\n{df.head(10).to_markdown(index=False)}\n\n"
content += f"\n๐Ÿ“ˆ ๋ฐ์ดํ„ฐ ์ •๋ณด:\n"
content += f"- ์ „์ฒด ํ–‰ ์ˆ˜: {len(df)}\n"
content += f"- ์ „์ฒด ์—ด ์ˆ˜: {len(df.columns)}\n"
content += f"- ์ปฌ๋Ÿผ ๋ชฉ๋ก: {', '.join(df.columns)}\n"
content += f"\n๐Ÿ“‹ ์ปฌ๋Ÿผ ๋ฐ์ดํ„ฐ ํƒ€์ž…:\n"
for col, dtype in df.dtypes.items():
content += f"- {col}: {dtype}\n"
null_counts = df.isnull().sum()
if null_counts.any():
content += f"\nโš ๏ธ ๊ฒฐ์ธก์น˜:\n"
for col, null_count in null_counts[null_counts > 0].items():
content += f"- {col}: {null_count}๊ฐœ ๋ˆ„๋ฝ\n"
return content, "csv"
except UnicodeDecodeError:
continue
raise UnicodeDecodeError(f"โŒ ์ง€์›๋˜๋Š” ์ธ์ฝ”๋”ฉ์œผ๋กœ ํŒŒ์ผ์„ ์ฝ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค ({', '.join(encodings)})")
else:
encodings = ['utf-8', 'cp949', 'euc-kr', 'latin1']
for encoding in encodings:
try:
with open(file.name, 'r', encoding=encoding) as f:
content = f.read()
return content, "text"
except UnicodeDecodeError:
continue
raise UnicodeDecodeError(f"โŒ ์ง€์›๋˜๋Š” ์ธ์ฝ”๋”ฉ์œผ๋กœ ํŒŒ์ผ์„ ์ฝ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค ({', '.join(encodings)})")
except Exception as e:
return f"โŒ ํŒŒ์ผ ์ฝ๊ธฐ ์˜ค๋ฅ˜: {str(e)}", "error"
def chat(message, history, uploaded_file, system_message="", max_tokens=4000, temperature=0.7, top_p=0.9):
if not message:
return "", history
system_prefix = """์ €๋Š” ์—ฌ๋Ÿฌ๋ถ„์˜ ์นœ๊ทผํ•˜๊ณ  ์ง€์ ์ธ AI ์–ด์‹œ์Šคํ„ดํŠธ 'GiniGEN'์ž…๋‹ˆ๋‹ค.. ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์›์น™์œผ๋กœ ์†Œํ†ตํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค:
1. ๐Ÿค ์นœ๊ทผํ•˜๊ณ  ๊ณต๊ฐ์ ์ธ ํƒœ๋„๋กœ ๋Œ€ํ™”
2. ๐Ÿ’ก ๋ช…ํ™•ํ•˜๊ณ  ์ดํ•ดํ•˜๊ธฐ ์‰ฌ์šด ์„ค๋ช… ์ œ๊ณต
3. ๐ŸŽฏ ์งˆ๋ฌธ์˜ ์˜๋„๋ฅผ ์ •ํ™•ํžˆ ํŒŒ์•…ํ•˜์—ฌ ๋งž์ถคํ˜• ๋‹ต๋ณ€
4. ๐Ÿ“š ํ•„์š”ํ•œ ๊ฒฝ์šฐ ์—…๋กœ๋“œ๋œ ํŒŒ์ผ ๋‚ด์šฉ์„ ์ฐธ๊ณ ํ•˜์—ฌ ๊ตฌ์ฒด์ ์ธ ๋„์›€ ์ œ๊ณต
5. โœจ ์ถ”๊ฐ€์ ์ธ ํ†ต์ฐฐ๊ณผ ์ œ์•ˆ์„ ํ†ตํ•œ ๊ฐ€์น˜ ์žˆ๋Š” ๋Œ€ํ™”
ํ•ญ์ƒ ์˜ˆ์˜ ๋ฐ”๋ฅด๊ณ  ์นœ์ ˆํ•˜๊ฒŒ ์‘๋‹ตํ•˜๋ฉฐ, ํ•„์š”ํ•œ ๊ฒฝ์šฐ ๊ตฌ์ฒด์ ์ธ ์˜ˆ์‹œ๋‚˜ ์„ค๋ช…์„ ์ถ”๊ฐ€ํ•˜์—ฌ
์ดํ•ด๋ฅผ ๋•๊ฒ ์Šต๋‹ˆ๋‹ค."""
try:
if uploaded_file:
content, file_type = read_uploaded_file(uploaded_file)
if file_type == "error":
error_message = content
chat_history.add_conversation(message, error_message)
return "", history + [[message, error_message]]
file_summary = analyze_file_content(content, file_type)
if file_type in ['parquet', 'csv']:
system_message += f"\n\nํŒŒ์ผ ๋‚ด์šฉ:\n```markdown\n{content}\n```"
else:
system_message += f"\n\nํŒŒ์ผ ๋‚ด์šฉ:\n```\n{content}\n```"
if message == "ํŒŒ์ผ ๋ถ„์„์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค...":
message = f"""[ํŒŒ์ผ ๊ตฌ์กฐ ๋ถ„์„] {file_summary}
๋‹ค์Œ ๊ด€์ ์—์„œ ๋„์›€์„ ๋“œ๋ฆฌ๊ฒ ์Šต๋‹ˆ๋‹ค:
1. ๐Ÿ“‹ ์ „๋ฐ˜์ ์ธ ๋‚ด์šฉ ํŒŒ์•…
2. ๐Ÿ’ก ์ฃผ์š” ํŠน์ง• ์„ค๋ช…
3. ๐ŸŽฏ ์‹ค์šฉ์ ์ธ ํ™œ์šฉ ๋ฐฉ์•ˆ
4. โœจ ๊ฐœ์„  ์ œ์•ˆ
5. ๐Ÿ’ฌ ์ถ”๊ฐ€ ์งˆ๋ฌธ์ด๋‚˜ ํ•„์š”ํ•œ ์„ค๋ช…"""
messages = [{"role": "system", "content": system_prefix + system_message}]
if history:
for user_msg, assistant_msg in history:
messages.append({"role": "user", "content": user_msg})
messages.append({"role": "assistant", "content": assistant_msg})
messages.append({"role": "user", "content": message})
client = get_client()
partial_message = ""
for msg in client.chat_completion(
messages,
max_tokens=max_tokens,
stream=True,
temperature=temperature,
top_p=top_p,
):
token = msg.choices[0].delta.get('content', None)
if token:
partial_message += token
current_history = history + [[message, partial_message]]
yield "", current_history
chat_history.add_conversation(message, partial_message)
except Exception as e:
error_msg = f"โŒ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"
chat_history.add_conversation(message, error_msg)
yield "", history + [[message, error_msg]]
with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", title="GiniGEN ๐Ÿค–") as demo:
initial_history = chat_history.format_for_display()
with gr.Row():
with gr.Column(scale=2):
chatbot = gr.Chatbot(
value=initial_history,
height=600,
label="๋Œ€ํ™”์ฐฝ ๐Ÿ’ฌ",
show_label=True
)
msg = gr.Textbox(
label="๋ฉ”์‹œ์ง€ ์ž…๋ ฅ",
show_label=False,
placeholder="๋ฌด์—‡์ด๋“  ๋ฌผ์–ด๋ณด์„ธ์š”... ๐Ÿ’ญ",
container=False
)
with gr.Row():
clear = gr.ClearButton([msg, chatbot], value="๋Œ€ํ™”๋‚ด์šฉ ์ง€์šฐ๊ธฐ")
send = gr.Button("๋ณด๋‚ด๊ธฐ ๐Ÿ“ค")
with gr.Column(scale=1):
gr.Markdown("### GiniGEN ๐Ÿค– [ํŒŒ์ผ ์—…๋กœ๋“œ] ๐Ÿ“\n์ง€์› ํ˜•์‹: ํ…์ŠคํŠธ, ์ฝ”๋“œ, CSV, Parquet ํŒŒ์ผ")
file_upload = gr.File(
label="ํŒŒ์ผ ์„ ํƒ",
file_types=["text", ".csv", ".parquet"],
type="filepath"
)
with gr.Accordion("๊ณ ๊ธ‰ ์„ค์ • โš™๏ธ", open=False):
system_message = gr.Textbox(label="์‹œ์Šคํ…œ ๋ฉ”์‹œ์ง€ ๐Ÿ“", value="")
max_tokens = gr.Slider(minimum=1, maximum=8000, value=4000, label="์ตœ๋Œ€ ํ† ํฐ ์ˆ˜ ๐Ÿ“Š")
temperature = gr.Slider(minimum=0, maximum=1, value=0.7, label="์ฐฝ์˜์„ฑ ์ˆ˜์ค€ ๐ŸŒก๏ธ")
top_p = gr.Slider(minimum=0, maximum=1, value=0.9, label="์‘๋‹ต ๋‹ค์–‘์„ฑ ๐Ÿ“ˆ")
gr.Examples(
examples=[
["์•ˆ๋…•ํ•˜์„ธ์š”! ์–ด๋–ค ๋„์›€์ด ํ•„์š”ํ•˜์‹ ๊ฐ€์š”? ๐Ÿค"],
["์ œ๊ฐ€ ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ์„ค๋ช…ํ•ด ์ฃผ์‹œ๊ฒ ์–ด์š”? ๐Ÿ“š"],
["์ด ๋‚ด์šฉ์„ ์‹ค์ œ๋กœ ์–ด๋–ป๊ฒŒ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ์„๊นŒ์š”? ๐ŸŽฏ"],
["์ถ”๊ฐ€๋กœ ์กฐ์–ธํ•ด ์ฃผ์‹ค ๋‚ด์šฉ์ด ์žˆ์œผ์‹ ๊ฐ€์š”? โœจ"],
["๊ถ๊ธˆํ•œ ์ ์ด ๋” ์žˆ๋Š”๋ฐ ์—ฌ์ญค๋ด๋„ ๋ ๊นŒ์š”? ๐Ÿค”"],
],
inputs=msg,
)
def clear_chat():
chat_history.clear_history()
return None, None
msg.submit(
chat,
inputs=[msg, chatbot, file_upload, system_message, max_tokens, temperature, top_p],
outputs=[msg, chatbot]
)
send.click(
chat,
inputs=[msg, chatbot, file_upload, system_message, max_tokens, temperature, top_p],
outputs=[msg, chatbot]
)
clear.click(
clear_chat,
outputs=[msg, chatbot]
)
file_upload.change(
lambda: "ํŒŒ์ผ ๋ถ„์„์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค...",
outputs=msg
).then(
chat,
inputs=[msg, chatbot, file_upload, system_message, max_tokens, temperature, top_p],
outputs=[msg, chatbot]
)
if __name__ == "__main__":
demo.launch()