Spaces:
Running
on
Zero
Running
on
Zero
import torch | |
import gradio as gr | |
import spaces | |
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer | |
import os | |
from threading import Thread | |
import random | |
from datasets import load_dataset | |
from sentence_transformers import SentenceTransformer | |
from sklearn.metrics.pairwise import cosine_similarity | |
import numpy as np | |
# GPU ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ | |
torch.cuda.empty_cache() | |
HF_TOKEN = os.environ.get("HF_TOKEN", None) | |
MODEL_ID = "CohereForAI/c4ai-command-r7b-12-2024" | |
MODELS = os.environ.get("MODELS") | |
MODEL_NAME = MODEL_ID.split("/")[-1] | |
# ์๋ฒ ๋ฉ ๋ชจ๋ธ ๋ก๋ | |
embedding_model = SentenceTransformer('sentence-transformers/xlm-r-100langs-bert-base-nli-stsb-mean-tokens') | |
# ์ํคํผ๋์ ๋ฐ์ดํฐ์ ๋ก๋ | |
wiki_dataset = load_dataset("lcw99/wikipedia-korean-20240501-1million-qna") | |
print("Wikipedia dataset loaded:", wiki_dataset) | |
# ๋ฐ์ดํฐ์ ์ ์ง๋ฌธ๋ค์ ์๋ฒ ๋ฉ | |
questions = wiki_dataset['train']['question'][:10000] # ์ฒ์ 10000๊ฐ๋ง ์ฌ์ฉ | |
question_embeddings = embedding_model.encode(questions, convert_to_tensor=True) | |
def find_relevant_context(query, top_k=3): | |
# ์ฟผ๋ฆฌ ์๋ฒ ๋ฉ | |
query_embedding = embedding_model.encode(query, convert_to_tensor=True) | |
# ์ฝ์ฌ์ธ ์ ์ฌ๋ ๊ณ์ฐ | |
similarities = cosine_similarity( | |
query_embedding.cpu().numpy().reshape(1, -1), | |
question_embeddings.cpu().numpy() | |
)[0] | |
# ๊ฐ์ฅ ์ ์ฌํ ์ง๋ฌธ๋ค์ ์ธ๋ฑ์ค | |
top_indices = np.argsort(similarities)[-top_k:][::-1] | |
# ๊ด๋ จ ์ปจํ ์คํธ ์ถ์ถ | |
relevant_contexts = [] | |
for idx in top_indices: | |
relevant_contexts.append({ | |
'question': questions[idx], | |
'answer': wiki_dataset['train']['answer'][idx] | |
}) | |
return relevant_contexts | |
def stream_chat(message: str, history: list, temperature: float, max_new_tokens: int, top_p: float, top_k: int, penalty: float): | |
print(f'message is - {message}') | |
print(f'history is - {history}') | |
# RAG: ๊ด๋ จ ์ปจํ ์คํธ ์ฐพ๊ธฐ | |
relevant_contexts = find_relevant_context(message) | |
context_prompt = "\n\n๊ด๋ จ ์ฐธ๊ณ ์ ๋ณด:\n" | |
for ctx in relevant_contexts: | |
context_prompt += f"Q: {ctx['question']}\nA: {ctx['answer']}\n\n" | |
# ๋ํ ํ์คํ ๋ฆฌ ๊ตฌ์ฑ | |
conversation = [] | |
for prompt, answer in history: | |
conversation.extend([ | |
{"role": "user", "content": prompt}, | |
{"role": "assistant", "content": answer} | |
]) | |
# ์ปจํ ์คํธ๋ฅผ ํฌํจํ ์ต์ข ํ๋กฌํํธ ๊ตฌ์ฑ | |
final_message = context_prompt + "\nํ์ฌ ์ง๋ฌธ: " + message | |
conversation.append({"role": "user", "content": final_message}) | |
input_ids = tokenizer.apply_chat_template(conversation, tokenize=False, add_generation_prompt=True) | |
inputs = tokenizer(input_ids, return_tensors="pt").to(0) | |
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=max_new_tokens, | |
do_sample=True, | |
temperature=temperature, | |
eos_token_id=[255001], | |
) | |
thread = Thread(target=model.generate, kwargs=generate_kwargs) | |
thread.start() | |
buffer = "" | |
for new_text in streamer: | |
buffer += new_text | |
yield buffer | |
chatbot = gr.Chatbot(height=500) | |
CSS = """ | |
/* ์ ์ฒด ํ์ด์ง ์คํ์ผ๋ง */ | |
body { | |
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); | |
min-height: 100vh; | |
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; | |
} | |
/* ๋ฉ์ธ ์ปจํ ์ด๋ */ | |
.container { | |
max-width: 1200px; | |
margin: 0 auto; | |
padding: 2rem; | |
background: rgba(255, 255, 255, 0.95); | |
border-radius: 20px; | |
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1); | |
backdrop-filter: blur(10px); | |
transform: perspective(1000px) translateZ(0); | |
transition: all 0.3s ease; | |
} | |
/* ์ ๋ชฉ ์คํ์ผ๋ง */ | |
h1 { | |
color: #2d3436; | |
font-size: 2.5rem; | |
text-align: center; | |
margin-bottom: 2rem; | |
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1); | |
transform: perspective(1000px) translateZ(20px); | |
} | |
h3 { | |
text-align: center; | |
color: #2d3436; | |
font-size: 1.5rem; | |
margin: 1rem 0; | |
} | |
/* ์ฑํ ๋ฐ์ค ์คํ์ผ๋ง */ | |
.chatbox { | |
background: white; | |
border-radius: 15px; | |
box-shadow: 0 8px 32px rgba(31, 38, 135, 0.15); | |
backdrop-filter: blur(4px); | |
border: 1px solid rgba(255, 255, 255, 0.18); | |
padding: 1rem; | |
margin: 1rem 0; | |
transform: translateZ(0); | |
transition: all 0.3s ease; | |
} | |
/* ๋ฉ์์ง ์คํ์ผ๋ง */ | |
.chatbox .messages .message.user { | |
background: linear-gradient(145deg, #e1f5fe, #bbdefb); | |
border-radius: 15px; | |
padding: 1rem; | |
margin: 0.5rem; | |
box-shadow: 5px 5px 15px rgba(0, 0, 0, 0.05); | |
transform: translateZ(10px); | |
animation: messageIn 0.3s ease-out; | |
} | |
.chatbox .messages .message.bot { | |
background: linear-gradient(145deg, #f5f5f5, #eeeeee); | |
border-radius: 15px; | |
padding: 1rem; | |
margin: 0.5rem; | |
box-shadow: 5px 5px 15px rgba(0, 0, 0, 0.05); | |
transform: translateZ(10px); | |
animation: messageIn 0.3s ease-out; | |
} | |
/* ๋ฒํผ ์คํ์ผ๋ง */ | |
.duplicate-button { | |
background: linear-gradient(145deg, #24292e, #1a1e22) !important; | |
color: white !important; | |
border-radius: 100vh !important; | |
padding: 0.8rem 1.5rem !important; | |
box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.2) !important; | |
transition: all 0.3s ease !important; | |
border: none !important; | |
cursor: pointer !important; | |
} | |
.duplicate-button:hover { | |
transform: translateY(-2px) !important; | |
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3) !important; | |
} | |
/* ์ ๋ ฅ ํ๋ ์คํ์ผ๋ง */ | |
""" | |
with gr.Blocks(css=CSS) as demo: | |
gr.ChatInterface( | |
fn=stream_chat, | |
chatbot=chatbot, | |
fill_height=True, | |
theme="soft", | |
additional_inputs_accordion=gr.Accordion(label="โ๏ธ ์ต์ ์ ", open=False, render=False), | |
additional_inputs=[ | |
gr.Slider( | |
minimum=0, | |
maximum=1, | |
step=0.1, | |
value=0.8, | |
label="์จ๋", | |
render=False, | |
), | |
gr.Slider( | |
minimum=128, | |
maximum=8000, | |
step=1, | |
value=4000, | |
label="์ต๋ ํ ํฐ ์", | |
render=False, | |
), | |
gr.Slider( | |
minimum=0.0, | |
maximum=1.0, | |
step=0.1, | |
value=0.8, | |
label="์์ ํ๋ฅ ", | |
render=False, | |
), | |
gr.Slider( | |
minimum=1, | |
maximum=20, | |
step=1, | |
value=20, | |
label="์์ K", | |
render=False, | |
), | |
gr.Slider( | |
minimum=0.0, | |
maximum=2.0, | |
step=0.1, | |
value=1.0, | |
label="๋ฐ๋ณต ํจ๋ํฐ", | |
render=False, | |
), | |
], | |
examples=[ | |
["์์ด์ ์ฌ๋ฆ๋ฐฉํ ๊ณผํ ํ๋ก์ ํธ๋ฅผ ์ํ 5๊ฐ์ง ์์ด๋์ด๋ฅผ ์ฃผ์ธ์."], | |
["๋งํฌ๋ค์ด์ ์ฌ์ฉํ์ฌ ๋ธ๋ ์ดํฌ์์ ๊ฒ์ ๋ง๋ค๊ธฐ ํํ ๋ฆฌ์ผ์ ์์ฑํด์ฃผ์ธ์."], | |
["์ด๋ฅ๋ ฅ์ ๊ฐ์ง ์ฃผ์ธ๊ณต์ SF ์ด์ผ๊ธฐ ์๋๋ฆฌ์ค๋ฅผ ์์ฑํด์ฃผ์ธ์. ๋ณต์ ์ค์ , ํ ๋ง์ ๋ก๊ทธ๋ผ์ธ์ ๋ ผ๋ฆฌ์ ์ผ๋ก ์ฌ์ฉํด์ฃผ์ธ์"], | |
["์์ด์ ์ฌ๋ฆ๋ฐฉํ ์์ ์ฐ๊ตฌ๋ฅผ ์ํ 5๊ฐ์ง ์์ด๋์ด์ ๊ทธ ๋ฐฉ๋ฒ์ ๊ฐ๋จํ ์๋ ค์ฃผ์ธ์."], | |
["ํผ์ฆ ๊ฒ์ ์คํฌ๋ฆฝํธ ์์ฑ์ ์ํ ์กฐ์ธ ๋ถํ๋๋ฆฝ๋๋ค"], | |
["๋งํฌ๋ค์ด ํ์์ผ๋ก ๋ธ๋ก ๊นจ๊ธฐ ๊ฒ์ ์ ์ ๊ต๊ณผ์๋ฅผ ์์ฑํด์ฃผ์ธ์"], | |
["์ค๋ฒ ๅทๆณ๋ฅผ ์๊ฐํด์ฃผ์ธ์"], | |
["์ผ๋ณธ์ด ๊ด์ฉ๊ตฌ, ์๋ด์ ๊ดํ ์ํ ๋ฌธ์ ๋ฅผ ๋ง๋ค์ด์ฃผ์ธ์"], | |
["๋๋ผ์๋ชฝ์ ๋ฑ์ฅ์ธ๋ฌผ์ ์๋ ค์ฃผ์ธ์"], | |
["์ค์ฝ๋ ธ๋ฏธ์ผํค ๋ง๋๋ ๋ฐฉ๋ฒ์ ์๋ ค์ฃผ์ธ์"], | |
["๋ฌธ์ 9.11๊ณผ 9.9 ์ค ์ด๋ ๊ฒ์ด ๋ ํฐ๊ฐ์? step by step์ผ๋ก ๋ ผ๋ฆฌ์ ์ผ๋ก ์๊ฐํด์ฃผ์ธ์."], | |
], | |
cache_examples=False, | |
) | |
if __name__ == "__main__": | |
demo.launch() |