File size: 11,671 Bytes
4f7e18c |
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 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
import torch
import gradio as gr
import spaces
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
import os, gc, logging
from threading import Thread
import random
from datasets import load_dataset
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
from typing import List, Tuple, Iterator
import json
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor
from functools import lru_cache
import pyarrow.parquet as pq
import pypdf
from pdfminer.high_level import extract_text
from pdfminer.layout import LAParams
from tabulate import tabulate
from pydantic import BaseModel
import unittest
# ๋ก๊น
์ค์
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('app.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# ์ค์ ํด๋์ค
class Config:
def __init__(self):
self.MODEL_ID = "CohereForAI/c4ai-command-r7b-12-2024"
self.MAX_HISTORY = 10
self.MAX_TOKENS = 4096
self.DEFAULT_TEMPERATURE = 0.8
self.HF_TOKEN = os.environ.get("HF_TOKEN", None)
self.MODELS = os.environ.get("MODELS")
config = Config()
# ์ปค์คํ
์์ธ ํด๋์ค
class FileProcessingError(Exception):
pass
# ์๋ต ๋ชจ๋ธ
class ChatResponse(BaseModel):
message: str
status: str
timestamp: datetime
# ํ์ผ ์ฒ๋ฆฌ ํด๋์ค
class FileProcessor:
@staticmethod
def process_pdf(file_path):
try:
with ThreadPoolExecutor() as executor:
pdf_reader = pypdf.PdfReader(file_path)
text = extract_text(
file_path,
laparams=LAParams(
line_margin=0.5,
word_margin=0.1,
char_margin=2.0,
all_texts=True
)
)
return text
except Exception as e:
raise FileProcessingError(f"PDF processing error: {str(e)}")
@staticmethod
def process_csv(file_path):
try:
encodings = ['utf-8', 'cp949', 'euc-kr', 'latin1']
for encoding in encodings:
try:
return pd.read_csv(file_path, encoding=encoding)
except UnicodeDecodeError:
continue
raise FileProcessingError("Unable to read CSV with supported encodings")
except Exception as e:
raise FileProcessingError(f"CSV processing error: {str(e)}")
# ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ
@torch.no_grad()
def clear_cuda_memory():
if torch.cuda.is_available():
torch.cuda.empty_cache()
gc.collect()
# ๋ชจ๋ธ ๋ก๋
@spaces.GPU
def load_model():
try:
model = AutoModelForCausalLM.from_pretrained(
config.MODEL_ID,
torch_dtype=torch.bfloat16,
device_map="auto",
)
return model
except Exception as e:
logger.error(f"Model loading error: {str(e)}")
raise
# ์ปจํ
์คํธ ๊ฒ์
@lru_cache(maxsize=100)
def find_relevant_context(query, top_k=3):
try:
query_vector = vectorizer.transform([query])
similarities = (query_vector * question_vectors.T).toarray()[0]
top_indices = np.argsort(similarities)[-top_k:][::-1]
relevant_contexts = []
for idx in top_indices:
if similarities[idx] > 0:
relevant_contexts.append({
'question': questions[idx],
'answer': wiki_dataset['train']['answer'][idx],
'similarity': similarities[idx]
})
return relevant_contexts
except Exception as e:
logger.error(f"Context search error: {str(e)}")
return []
# ์คํธ๋ฆฌ๋ฐ ์ฑํ
@spaces.GPU
def stream_chat(message: str, history: list, uploaded_file, temperature: float,
max_new_tokens: int, top_p: float, top_k: int, penalty: float) -> Iterator[Tuple[str, list]]:
"""
์คํธ๋ฆฌ๋ฐ ์ฑํ
์๋ต์ ์์ฑํฉ๋๋ค.
Args:
message (str): ์ฌ์ฉ์ ์
๋ ฅ ๋ฉ์์ง
history (list): ๋ํ ํ์คํ ๋ฆฌ
uploaded_file: ์
๋ก๋๋ ํ์ผ
temperature (float): ์์ฑ ์จ๋
max_new_tokens (int): ์ต๋ ํ ํฐ ์
top_p (float): ์์ p ์ํ๋ง
top_k (int): ์์ k ์ํ๋ง
penalty (float): ๋ฐ๋ณต ํ๋ํฐ
Returns:
Iterator[Tuple[str, list]]: ์์ฑ๋ ์๋ต๊ณผ ์
๋ฐ์ดํธ๋ ํ์คํ ๋ฆฌ
"""
global model, current_file_context
try:
if model is None:
model = load_model()
logger.info(f'Processing message: {message}')
logger.debug(f'History length: {len(history)}')
# ํ์ผ ์ฒ๋ฆฌ
file_context = ""
if uploaded_file:
try:
file_ext = os.path.splitext(uploaded_file.name)[1].lower()
if file_ext == '.pdf':
content = FileProcessor.process_pdf(uploaded_file.name)
elif file_ext == '.csv':
content = FileProcessor.process_csv(uploaded_file.name)
else:
content = safe_file_read(uploaded_file.name)
file_context = analyze_file_content(content, file_ext)
current_file_context = file_context
except Exception as e:
logger.error(f"File processing error: {str(e)}")
file_context = f"\n\nโ File analysis error: {str(e)}"
# ์ปจํ
์คํธ ๊ฒ์ ๋ฐ ํ๋กฌํํธ ๊ตฌ์ฑ
relevant_contexts = find_relevant_context(message)
wiki_context = "\n\n๊ด๋ จ ์ํคํผ๋์ ์ ๋ณด:\n" + "\n".join([
f"Q: {ctx['question']}\nA: {ctx['answer']}\n์ ์ฌ๋: {ctx['similarity']:.3f}"
for ctx in relevant_contexts
])
# ํ ํฐํ ๋ฐ ์์ฑ
conversation = [
{"role": "user" if i % 2 == 0 else "assistant", "content": msg}
for hist in history[-config.MAX_HISTORY:]
for i, msg in enumerate(hist)
]
final_message = f"{file_context}{wiki_context}\nํ์ฌ ์ง๋ฌธ: {message}"
conversation.append({"role": "user", "content": final_message})
inputs = tokenizer(
tokenizer.apply_chat_template(conversation, tokenize=False, add_generation_prompt=True),
return_tensors="pt"
).to("cuda")
streamer = TextIteratorStreamer(tokenizer, timeout=10., skip_prompt=True, skip_special_tokens=True)
generate_kwargs = dict(
inputs,
streamer=streamer,
top_k=top_k,
top_p=top_p,
repetition_penalty=penalty,
max_new_tokens=min(max_new_tokens, 2048),
do_sample=True,
temperature=temperature,
eos_token_id=[255001],
)
clear_cuda_memory()
thread = Thread(target=model.generate, kwargs=generate_kwargs)
thread.start()
buffer = ""
for new_text in streamer:
buffer += new_text
yield "", history + [[message, buffer]]
clear_cuda_memory()
except Exception as e:
logger.error(f"Stream chat error: {str(e)}")
yield "", history + [[message, f"Error: {str(e)}"]]
clear_cuda_memory()
# UI ์์ฑ
def create_demo():
with gr.Blocks(css=UPDATED_CSS) as demo:
# UI ์ปดํฌ๋ํธ ๊ตฌ์ฑ
with gr.Column(elem_classes="markdown-style"):
gr.Markdown("""
# ๐ค RAGOndevice
#### ๐ RAG: Upload and Analyze Files (TXT, CSV, PDF, Parquet files)
Upload your files for data analysis and learning
""")
chatbot = gr.Chatbot(
value=[],
height=600,
label="GiniGEN AI Assistant",
elem_classes="chat-container"
)
# ์
๋ ฅ ์ปดํฌ๋ํธ
with gr.Row(elem_classes="input-container"):
with gr.Column(scale=1, min_width=70):
file_upload = gr.File(
type="filepath",
elem_classes="file-upload-icon",
scale=1,
container=True,
interactive=True,
show_label=False
)
with gr.Column(scale=3):
msg = gr.Textbox(
show_label=False,
placeholder="Type your message here... ๐ญ",
container=False,
elem_classes="input-textbox",
scale=1
)
with gr.Column(scale=1, min_width=70):
send = gr.Button(
"Send",
elem_classes="send-button custom-button",
scale=1
)
with gr.Column(scale=1, min_width=70):
clear = gr.Button(
"Clear",
elem_classes="clear-button custom-button",
scale=1
)
# ๊ณ ๊ธ ์ค์
with gr.Accordion("๐ฎ Advanced Settings", open=False):
with gr.Row():
with gr.Column(scale=1):
temperature = gr.Slider(
minimum=0, maximum=1, step=0.1, value=config.DEFAULT_TEMPERATURE,
label="Creativity Level ๐จ"
)
max_new_tokens = gr.Slider(
minimum=128, maximum=8000, step=1, value=4000,
label="Maximum Token Count ๐"
)
with gr.Column(scale=1):
top_p = gr.Slider(
minimum=0.0, maximum=1.0, step=0.1, value=0.8,
label="Diversity Control ๐ฏ"
)
top_k = gr.Slider(
minimum=1, maximum=20, step=1, value=20,
label="Selection Range ๐"
)
penalty = gr.Slider(
minimum=0.0, maximum=2.0, step=0.1, value=1.0,
label="Repetition Penalty ๐"
)
# ์ด๋ฒคํธ ๋ฐ์ธ๋ฉ
msg.submit(stream_chat, [msg, chatbot, file_upload, temperature, max_new_tokens, top_p, top_k, penalty], [msg, chatbot])
send.click(stream_chat, [msg, chatbot, file_upload, temperature, max_new_tokens, top_p, top_k, penalty], [msg, chatbot])
clear.click(lambda: ([], None, ""), outputs=[chatbot, file_upload, msg])
return demo
# ๋ฉ์ธ ์คํ
if __name__ == "__main__":
# ์ํคํผ๋์ ๋ฐ์ดํฐ์
๋ก๋
wiki_dataset = load_dataset("lcw99/wikipedia-korean-20240501-1million-qna")
logger.info("Wikipedia dataset loaded")
# TF-IDF ๋ฒกํฐ๋ผ์ด์ ์ด๊ธฐํ
questions = wiki_dataset['train']['question'][:10000]
vectorizer = TfidfVectorizer(max_features=1000)
question_vectors = vectorizer.fit_transform(questions)
logger.info("TF-IDF vectorization completed")
# UI ์คํ
demo = create_demo()
demo.launch()
# ํ
์คํธ ์ฝ๋
class TestChatBot(unittest.TestCase):
def test_file_processing(self):
# ํ
์คํธ ๊ตฌํ
pass
def test_context_search(self):
# ํ
์คํธ ๊ตฌํ
pass
|