Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,7 +5,7 @@ import pandas as pd
|
|
| 5 |
import json
|
| 6 |
from datetime import datetime
|
| 7 |
import torch
|
| 8 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 9 |
import spaces
|
| 10 |
from threading import Thread
|
| 11 |
|
|
@@ -17,8 +17,12 @@ class ModelManager:
|
|
| 17 |
def __init__(self):
|
| 18 |
self.tokenizer = None
|
| 19 |
self.model = None
|
| 20 |
-
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
@spaces.GPU
|
| 23 |
def setup_model(self):
|
| 24 |
try:
|
|
@@ -42,13 +46,320 @@ class ModelManager:
|
|
| 42 |
trust_remote_code=True,
|
| 43 |
low_cpu_mem_usage=True
|
| 44 |
)
|
| 45 |
-
self.model.eval()
|
| 46 |
print("λͺ¨λΈ λ‘λ© μλ£")
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
except Exception as e:
|
| 53 |
print(f"λͺ¨λΈ λ‘λ© μ€ μ€λ₯ λ°μ: {e}")
|
| 54 |
raise Exception(f"λͺ¨λΈ λ‘λ© μ€ν¨: {e}")
|
|
@@ -56,8 +367,8 @@ class ModelManager:
|
|
| 56 |
@spaces.GPU
|
| 57 |
def generate_response(self, messages, max_tokens=4000, temperature=0.7, top_p=0.9):
|
| 58 |
try:
|
| 59 |
-
|
| 60 |
-
|
| 61 |
|
| 62 |
# μ
λ ₯ ν
μ€νΈ μ€λΉ
|
| 63 |
prompt = ""
|
|
@@ -70,7 +381,7 @@ class ModelManager:
|
|
| 70 |
prompt += f"Human: {content}\n"
|
| 71 |
elif role == "assistant":
|
| 72 |
prompt += f"Assistant: {content}\n"
|
| 73 |
-
prompt += "Assistant: "
|
| 74 |
|
| 75 |
# μ
λ ₯ μΈμ½λ©
|
| 76 |
input_ids = self.tokenizer.encode(
|
|
@@ -92,7 +403,7 @@ class ModelManager:
|
|
| 92 |
num_return_sequences=1
|
| 93 |
)
|
| 94 |
|
| 95 |
-
# μλ΅ λμ½λ©
|
| 96 |
generated_text = self.tokenizer.decode(
|
| 97 |
output_ids[0][input_ids.shape[1]:],
|
| 98 |
skip_special_tokens=True
|
|
@@ -255,6 +566,9 @@ def chat(message, history, uploaded_file, system_message="", max_tokens=4000, te
|
|
| 255 |
μ΄ν΄λ₯Ό λκ² μ΅λλ€."""
|
| 256 |
|
| 257 |
try:
|
|
|
|
|
|
|
|
|
|
| 258 |
if uploaded_file:
|
| 259 |
content, file_type = read_uploaded_file(uploaded_file)
|
| 260 |
if file_type == "error":
|
|
|
|
| 5 |
import json
|
| 6 |
from datetime import datetime
|
| 7 |
import torch
|
| 8 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 9 |
import spaces
|
| 10 |
from threading import Thread
|
| 11 |
|
|
|
|
| 17 |
def __init__(self):
|
| 18 |
self.tokenizer = None
|
| 19 |
self.model = None
|
| 20 |
+
# μ΄κΈ°νλ 첫 μμ² μμ μν
|
| 21 |
|
| 22 |
+
def ensure_model_loaded(self):
|
| 23 |
+
if self.model is None or self.tokenizer is None:
|
| 24 |
+
self.setup_model()
|
| 25 |
+
|
| 26 |
@spaces.GPU
|
| 27 |
def setup_model(self):
|
| 28 |
try:
|
|
|
|
| 46 |
trust_remote_code=True,
|
| 47 |
low_cpu_mem_usage=True
|
| 48 |
)
|
| 49 |
+
self.model.eval()
|
| 50 |
print("λͺ¨λΈ λ‘λ© μλ£")
|
| 51 |
|
| 52 |
+
except Exception as e:
|
| 53 |
+
print(f"λͺ¨λΈ λ‘λ© μ€ μ€λ₯ λ°μ: {e}")
|
| 54 |
+
raise Exception(f"λͺ¨λΈ λ‘λ© μ€ν¨: {e}")
|
| 55 |
+
|
| 56 |
+
@spaces.GPU
|
| 57 |
+
def generate_response(self, messages, max_tokens=4000, temperature=0.7, top_p=0.9):
|
| 58 |
+
try:
|
| 59 |
+
# λͺ¨λΈμ΄ λ‘λλμ΄ μλμ§ νμΈ
|
| 60 |
+
self.ensure_model_loaded()
|
| 61 |
+
|
| 62 |
+
# μ
λ ₯ ν
μ€νΈ μ€λΉ
|
| 63 |
+
prompt = ""
|
| 64 |
+
for msg in messages:
|
| 65 |
+
role = msg["role"]
|
| 66 |
+
content = msg["content"]
|
| 67 |
+
if role == "system":
|
| 68 |
+
prompt += f"System: {content}\n"
|
| 69 |
+
elif role == "user":
|
| 70 |
+
prompt += f"Human: {content}\n"
|
| 71 |
+
elif role == "assistant":
|
| 72 |
+
prompt += f"Assistant: {content}\n"
|
| 73 |
+
prompt += "Assistant: "
|
| 74 |
+
|
| 75 |
+
# μ
λ ₯ μΈμ½λ©
|
| 76 |
+
input_ids = self.tokenizer.encode(
|
| 77 |
+
prompt,
|
| 78 |
+
return_tensors="pt",
|
| 79 |
+
add_special_tokens=True
|
| 80 |
+
).to(self.model.device)
|
| 81 |
+
|
| 82 |
+
# μλ΅ μμ±
|
| 83 |
+
with torch.no_grad():
|
| 84 |
+
output_ids = self.model.generate(
|
| 85 |
+
input_ids,
|
| 86 |
+
max_new_tokens=max_tokens,
|
| 87 |
+
do_sample=True,
|
| 88 |
+
temperature=temperature,
|
| 89 |
+
top_p=top_p,
|
| 90 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 91 |
+
eos_token_id=self.tokenizer.eos_token_id,
|
| 92 |
+
num_return_sequences=1
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
# μλ΅ λμ½λ©
|
| 96 |
+
generated_text = self.tokenizer.decode(
|
| 97 |
+
output_ids[0][input_ids.shape[1]:],
|
| 98 |
+
skip_special_tokens=True
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
# λ¨μ΄ λ¨μλ‘ μ€νΈλ¦¬λ°
|
| 102 |
+
words = generated_text.split()
|
| 103 |
+
for word in words:
|
| 104 |
+
yield type('Response', (), {
|
| 105 |
+
'choices': [type('Choice', (), {
|
| 106 |
+
'delta': {'content': word + " "}
|
| 107 |
+
})()]
|
| 108 |
+
})()
|
| 109 |
+
|
| 110 |
+
except Exception as e:
|
| 111 |
+
print(f"μλ΅ μμ± μ€ μ€λ₯ λ°μ: {e}")
|
| 112 |
+
raise Exception(f"μλ΅ μμ± μ€ν¨: {e}")
|
| 113 |
+
|
| 114 |
+
class ChatHistory:
|
| 115 |
+
def __init__(self):
|
| 116 |
+
self.history = []
|
| 117 |
+
self.history_file = "/tmp/chat_history.json"
|
| 118 |
+
self.load_history()
|
| 119 |
+
|
| 120 |
+
def add_conversation(self, user_msg: str, assistant_msg: str):
|
| 121 |
+
conversation = {
|
| 122 |
+
"timestamp": datetime.now().isoformat(),
|
| 123 |
+
"messages": [
|
| 124 |
+
{"role": "user", "content": user_msg},
|
| 125 |
+
{"role": "assistant", "content": assistant_msg}
|
| 126 |
+
]
|
| 127 |
+
}
|
| 128 |
+
self.history.append(conversation)
|
| 129 |
+
self.save_history()
|
| 130 |
+
|
| 131 |
+
def format_for_display(self):
|
| 132 |
+
formatted = []
|
| 133 |
+
for conv in self.history:
|
| 134 |
+
formatted.append([
|
| 135 |
+
conv["messages"][0]["content"],
|
| 136 |
+
conv["messages"][1]["content"]
|
| 137 |
+
])
|
| 138 |
+
return formatted
|
| 139 |
+
|
| 140 |
+
def get_messages_for_api(self):
|
| 141 |
+
messages = []
|
| 142 |
+
for conv in self.history:
|
| 143 |
+
messages.extend([
|
| 144 |
+
{"role": "user", "content": conv["messages"][0]["content"]},
|
| 145 |
+
{"role": "assistant", "content": conv["messages"][1]["content"]}
|
| 146 |
+
])
|
| 147 |
+
return messages
|
| 148 |
+
|
| 149 |
+
def clear_history(self):
|
| 150 |
+
self.history = []
|
| 151 |
+
self.save_history()
|
| 152 |
+
|
| 153 |
+
def save_history(self):
|
| 154 |
+
try:
|
| 155 |
+
with open(self.history_file, 'w', encoding='utf-8') as f:
|
| 156 |
+
json.dump(self.history, f, ensure_ascii=False, indent=2)
|
| 157 |
+
except Exception as e:
|
| 158 |
+
print(f"νμ€ν 리 μ μ₯ μ€ν¨: {e}")
|
| 159 |
+
|
| 160 |
+
def load_history(self):
|
| 161 |
+
try:
|
| 162 |
+
if os.path.exists(self.history_file):
|
| 163 |
+
with open(self.history_file, 'r', encoding='utf-8') as f:
|
| 164 |
+
self.history = json.load(f)
|
| 165 |
+
except Exception as e:
|
| 166 |
+
print(f"νμ€ν 리 λ‘λ μ€ν¨: {e}")
|
| 167 |
+
self.history = []
|
| 168 |
+
|
| 169 |
+
# μ μ μΈμ€ν΄μ€ μμ±
|
| 170 |
+
chat_history = ChatHistory()
|
| 171 |
+
model_manager = ModelManager()
|
| 172 |
+
|
| 173 |
+
def analyze_file_content(content, file_type):
|
| 174 |
+
"""Analyze file content and return structural summary"""
|
| 175 |
+
if file_type in ['parquet', 'csv']:
|
| 176 |
+
try:
|
| 177 |
+
lines = content.split('\n')
|
| 178 |
+
header = lines[0]
|
| 179 |
+
columns = header.count('|') - 1
|
| 180 |
+
rows = len(lines) - 3
|
| 181 |
+
return f"π λ°μ΄ν°μ
ꡬ쑰: {columns}κ° μ»¬λΌ, {rows}κ° λ°μ΄ν°"
|
| 182 |
+
except:
|
| 183 |
+
return "β λ°μ΄ν°μ
ꡬ쑰 λΆμ μ€ν¨"
|
| 184 |
+
|
| 185 |
+
lines = content.split('\n')
|
| 186 |
+
total_lines = len(lines)
|
| 187 |
+
non_empty_lines = len([line for line in lines if line.strip()])
|
| 188 |
+
|
| 189 |
+
if any(keyword in content.lower() for keyword in ['def ', 'class ', 'import ', 'function']):
|
| 190 |
+
functions = len([line for line in lines if 'def ' in line])
|
| 191 |
+
classes = len([line for line in lines if 'class ' in line])
|
| 192 |
+
imports = len([line for line in lines if 'import ' in line or 'from ' in line])
|
| 193 |
+
return f"π» μ½λ ꡬ쑰: {total_lines}μ€ (ν¨μ: {functions}, ν΄λμ€: {classes}, μν¬νΈ: {imports})"
|
| 194 |
+
|
| 195 |
+
paragraphs = content.count('\n\n') + 1
|
| 196 |
+
words = len(content.split())
|
| 197 |
+
return f"π λ¬Έμ ꡬ쑰: {total_lines}μ€, {paragraphs}λ¨λ½, μ½ {words}λ¨μ΄"
|
| 198 |
+
|
| 199 |
+
def read_uploaded_file(file):
|
| 200 |
+
if file is None:
|
| 201 |
+
return "", ""
|
| 202 |
+
try:
|
| 203 |
+
file_ext = os.path.splitext(file.name)[1].lower()
|
| 204 |
+
|
| 205 |
+
if file_ext == '.parquet':
|
| 206 |
+
df = pd.read_parquet(file.name, engine='pyarrow')
|
| 207 |
+
content = df.head(10).to_markdown(index=False)
|
| 208 |
+
return content, "parquet"
|
| 209 |
+
elif file_ext == '.csv':
|
| 210 |
+
encodings = ['utf-8', 'cp949', 'euc-kr', 'latin1']
|
| 211 |
+
for encoding in encodings:
|
| 212 |
+
try:
|
| 213 |
+
df = pd.read_csv(file.name, encoding=encoding)
|
| 214 |
+
content = f"π λ°μ΄ν° 미리보기:\n{df.head(10).to_markdown(index=False)}\n\n"
|
| 215 |
+
content += f"\nπ λ°μ΄ν° μ 보:\n"
|
| 216 |
+
content += f"- μ 체 ν μ: {len(df)}\n"
|
| 217 |
+
content += f"- μ 체 μ΄ μ: {len(df.columns)}\n"
|
| 218 |
+
content += f"- μ»¬λΌ λͺ©λ‘: {', '.join(df.columns)}\n"
|
| 219 |
+
content += f"\nπ μ»¬λΌ λ°μ΄ν° νμ
:\n"
|
| 220 |
+
for col, dtype in df.dtypes.items():
|
| 221 |
+
content += f"- {col}: {dtype}\n"
|
| 222 |
+
null_counts = df.isnull().sum()
|
| 223 |
+
if null_counts.any():
|
| 224 |
+
content += f"\nβ οΈ κ²°μΈ‘μΉ:\n"
|
| 225 |
+
for col, null_count in null_counts[null_counts > 0].items():
|
| 226 |
+
content += f"- {col}: {null_count}κ° λλ½\n"
|
| 227 |
+
return content, "csv"
|
| 228 |
+
except UnicodeDecodeError:
|
| 229 |
+
continue
|
| 230 |
+
raise UnicodeDecodeError(f"β μ§μλλ μΈμ½λ©μΌλ‘ νμΌμ μ½μ μ μμ΅λλ€ ({', '.join(encodings)})")
|
| 231 |
+
else:
|
| 232 |
+
encodings = ['utf-8', 'cp949', 'euc-kr', 'latin1']
|
| 233 |
+
for encoding in encodings:
|
| 234 |
+
try:
|
| 235 |
+
with open(file.name, 'r', encoding=encoding) as f:
|
| 236 |
+
content = f.read()
|
| 237 |
+
return content, "text"
|
| 238 |
+
except UnicodeDecodeError:
|
| 239 |
+
continue
|
| 240 |
+
raise UnicodeDecodeError(f"β μ§μλλ μΈμ½λ©μΌλ‘ νμΌμ μ½μ μ μμ΅λλ€ ({', '.join(encodings)})")
|
| 241 |
+
except Exception as e:
|
| 242 |
+
return f"β νμΌ μ½κΈ° μ€λ₯: {str(e)}", "error"
|
| 243 |
+
|
| 244 |
+
def chat(message, history, uploaded_file, system_message="", max_tokens=4000, temperature=0.7, top_p=0.9):
|
| 245 |
+
if not message:
|
| 246 |
+
return "", history
|
| 247 |
+
|
| 248 |
+
system_prefix = """μ λ μ¬λ¬λΆμ μΉκ·Όνκ³ μ§μ μΈ AI μ΄μμ€ν΄νΈ 'GiniGEN'μ
λλ€.. λ€μκ³Ό κ°μ μμΉμΌλ‘ μν΅νκ² μ΅λλ€:
|
| 249 |
+
1. π€ μΉκ·Όνκ³ κ³΅κ°μ μΈ νλλ‘ λν
|
| 250 |
+
2. π‘ λͺ
ννκ³ μ΄ν΄νκΈ° μ¬μ΄ μ€λͺ
μ 곡
|
| 251 |
+
3. π― μ§λ¬Έμ μλλ₯Ό μ νν νμ
νμ¬ λ§μΆ€ν λ΅λ³
|
| 252 |
+
4. π νμν κ²½μ° μ
λ‘λλ νμΌ λ΄μ©μ μ°Έκ³ νμ¬ κ΅¬μ²΄μ μΈ λμ μ 곡
|
| 253 |
+
5. β¨ μΆκ°μ μΈ ν΅μ°°κ³Ό μ μμ ν΅ν κ°μΉ μλ λν
|
| 254 |
+
νμ μμ λ°λ₯΄κ³ μΉμ νκ² μλ΅νλ©°, νμν κ²½μ° κ΅¬μ²΄μ μΈ μμλ μ€λͺ
μ μΆκ°νμ¬
|
| 255 |
+
μ΄ν΄λ₯Ό λκ² μ΅λλ€."""
|
| 256 |
+
|
| 257 |
+
try:
|
| 258 |
+
# 첫 λ©μμ§μΌ λ λͺ¨λΈ λ‘λ©
|
| 259 |
+
model_manager.ensure_model_loaded()
|
| 260 |
+
|
| 261 |
+
if uploaded_file:
|
| 262 |
+
content, file_type = read_uploaded_file(uploaded_file)
|
| 263 |
+
if file_type == "error":
|
| 264 |
+
error_message = content
|
| 265 |
+
chat_history.add_conversation(message, error_message)
|
| 266 |
+
return "", history + [[message, error_message]]
|
| 267 |
+
|
| 268 |
+
file_summary = analyze_file_content(content, file_type)
|
| 269 |
+
|
| 270 |
+
if file_type in ['parquet', 'csv']:
|
| 271 |
+
system_message += f"\n\nνμΌ λ΄μ©:\n```markdown\n{content}\n```"
|
| 272 |
+
else:
|
| 273 |
+
system_message += f"\n\nνμΌ λ΄μ©:\n```\n{content}\n```"
|
| 274 |
|
| 275 |
+
if message == "νμΌ λΆμμ μμν©λλ€...":
|
| 276 |
+
message = f"""[νμΌ κ΅¬μ‘° λΆμ] {file_summary}
|
| 277 |
+
λ€μ κ΄μ μμ λμμ λλ¦¬κ² μ΅λλ€:
|
| 278 |
+
1. π μ λ°μ μΈ λ΄μ© νμ
|
| 279 |
+
2. π‘ μ£Όμ νΉμ§ μ€λͺ
|
| 280 |
+
3. π― μ€μ©μ μΈ νμ© λ°©μ
|
| 281 |
+
4. β¨ κ°μ μ μ
|
| 282 |
+
5. π¬ μΆκ° μ§λ¬Έμ΄λ νμν μ€λͺ
"""
|
| 283 |
+
|
| 284 |
+
messages = [{"role": "system", "content": system_prefix + system_message}]
|
| 285 |
+
|
| 286 |
+
if history:
|
| 287 |
+
for user_msg, assistant_msg in history:
|
| 288 |
+
messages.append({"role": "user", "content": user_msg})
|
| 289 |
+
messages.append({"role": "assistant", "content": assistant_msg})
|
| 290 |
+
|
| 291 |
+
messages.append({"role": "user", "content": message})
|
| 292 |
+
|
| 293 |
+
partial_message = ""
|
| 294 |
+
|
| 295 |
+
for response in model_manager.generate_response(
|
| 296 |
+
messages,
|
| 297 |
+
max_tokens=max_tokens,
|
| 298 |
+
temperature=temperature,
|
| 299 |
+
top_p=top_p
|
| 300 |
+
):
|
| 301 |
+
token = response.choices[0].delta.get('content', '')
|
| 302 |
+
if token:
|
| 303 |
+
partial_message += token
|
| 304 |
+
current_history = history + [[message, partial_message]]
|
| 305 |
+
yield "", current_history
|
| 306 |
+
|
| 307 |
+
chat_history.add_conversation(message, partial_message)
|
| 308 |
+
|
| 309 |
+
except Exception as e:
|
| 310 |
+
error_msg = f"β μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}"
|
| 311 |
+
chat_history.add_conversation(message, error_msg)
|
| 312 |
+
yield "", history + [[message, error_msg]]import os
|
| 313 |
+
from dotenv import load_dotenv
|
| 314 |
+
import gradio as gr
|
| 315 |
+
import pandas as pd
|
| 316 |
+
import json
|
| 317 |
+
from datetime import datetime
|
| 318 |
+
import torch
|
| 319 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 320 |
+
import spaces
|
| 321 |
+
from threading import Thread
|
| 322 |
+
|
| 323 |
+
# νκ²½ λ³μ μ€μ
|
| 324 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 325 |
+
MODEL_ID = "CohereForAI/c4ai-command-r7b-12-2024"
|
| 326 |
+
|
| 327 |
+
class ModelManager:
|
| 328 |
+
def __init__(self):
|
| 329 |
+
self.tokenizer = None
|
| 330 |
+
self.model = None
|
| 331 |
+
# μ΄κΈ°νλ 첫 μμ² μμ μν
|
| 332 |
+
|
| 333 |
+
def ensure_model_loaded(self):
|
| 334 |
+
if self.model is None or self.tokenizer is None:
|
| 335 |
+
self.setup_model()
|
| 336 |
+
|
| 337 |
+
@spaces.GPU
|
| 338 |
+
def setup_model(self):
|
| 339 |
+
try:
|
| 340 |
+
print("ν ν¬λμ΄μ λ‘λ© μμ...")
|
| 341 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 342 |
+
MODEL_ID,
|
| 343 |
+
use_fast=True,
|
| 344 |
+
token=HF_TOKEN,
|
| 345 |
+
trust_remote_code=True
|
| 346 |
+
)
|
| 347 |
+
if not self.tokenizer.pad_token:
|
| 348 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 349 |
+
print("ν ν¬λμ΄μ λ‘λ© μλ£")
|
| 350 |
+
|
| 351 |
+
print("λͺ¨λΈ λ‘λ© μμ...")
|
| 352 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 353 |
+
MODEL_ID,
|
| 354 |
+
token=HF_TOKEN,
|
| 355 |
+
torch_dtype=torch.bfloat16,
|
| 356 |
+
device_map="auto",
|
| 357 |
+
trust_remote_code=True,
|
| 358 |
+
low_cpu_mem_usage=True
|
| 359 |
+
)
|
| 360 |
+
self.model.eval()
|
| 361 |
+
print("λͺ¨λΈ λ‘λ© μλ£")
|
| 362 |
+
|
| 363 |
except Exception as e:
|
| 364 |
print(f"λͺ¨λΈ λ‘λ© μ€ μ€λ₯ λ°μ: {e}")
|
| 365 |
raise Exception(f"λͺ¨λΈ λ‘λ© μ€ν¨: {e}")
|
|
|
|
| 367 |
@spaces.GPU
|
| 368 |
def generate_response(self, messages, max_tokens=4000, temperature=0.7, top_p=0.9):
|
| 369 |
try:
|
| 370 |
+
# λͺ¨λΈμ΄ λ‘λλμ΄ μλμ§ νμΈ
|
| 371 |
+
self.ensure_model_loaded()
|
| 372 |
|
| 373 |
# μ
λ ₯ ν
μ€νΈ μ€λΉ
|
| 374 |
prompt = ""
|
|
|
|
| 381 |
prompt += f"Human: {content}\n"
|
| 382 |
elif role == "assistant":
|
| 383 |
prompt += f"Assistant: {content}\n"
|
| 384 |
+
prompt += "Assistant: "
|
| 385 |
|
| 386 |
# μ
λ ₯ μΈμ½λ©
|
| 387 |
input_ids = self.tokenizer.encode(
|
|
|
|
| 403 |
num_return_sequences=1
|
| 404 |
)
|
| 405 |
|
| 406 |
+
# μλ΅ λμ½λ©
|
| 407 |
generated_text = self.tokenizer.decode(
|
| 408 |
output_ids[0][input_ids.shape[1]:],
|
| 409 |
skip_special_tokens=True
|
|
|
|
| 566 |
μ΄ν΄λ₯Ό λκ² μ΅λλ€."""
|
| 567 |
|
| 568 |
try:
|
| 569 |
+
# 첫 λ©μμ§μΌ λ λͺ¨λΈ λ‘λ©
|
| 570 |
+
model_manager.ensure_model_loaded()
|
| 571 |
+
|
| 572 |
if uploaded_file:
|
| 573 |
content, file_type = read_uploaded_file(uploaded_file)
|
| 574 |
if file_type == "error":
|