cutechicken commited on
Commit
9e9b867
โ€ข
1 Parent(s): cf528b4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -391
app.py CHANGED
@@ -1,403 +1,166 @@
1
- import os
2
- from dotenv import load_dotenv
3
- import gradio as gr
4
- 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
 
12
- # ํ™˜๊ฒฝ ๋ณ€์ˆ˜ ์„ค์ •
13
- HF_TOKEN = os.getenv("HF_TOKEN")
14
  MODEL_ID = "CohereForAI/c4ai-command-r7b-12-2024"
15
-
16
- class ModelManager:
17
- def __init__(self):
18
- self.tokenizer = None
19
- self.model = None
20
-
21
- def ensure_model_loaded(self):
22
- if self.model is None or self.tokenizer is None:
23
- self.setup_model()
24
-
25
- @spaces.GPU
26
- def setup_model(self):
27
- try:
28
- print("ํ† ํฌ๋‚˜์ด์ € ๋กœ๋”ฉ ์‹œ์ž‘...")
29
- self.tokenizer = AutoTokenizer.from_pretrained(
30
- MODEL_ID,
31
- use_fast=True,
32
- token=HF_TOKEN,
33
- trust_remote_code=True
34
- )
35
- if not self.tokenizer.pad_token:
36
- self.tokenizer.pad_token = self.tokenizer.eos_token
37
- print("ํ† ํฌ๋‚˜์ด์ € ๋กœ๋”ฉ ์™„๋ฃŒ")
38
-
39
- print("๋ชจ๋ธ ๋กœ๋”ฉ ์‹œ์ž‘...")
40
- self.model = AutoModelForCausalLM.from_pretrained(
41
- MODEL_ID,
42
- token=HF_TOKEN,
43
- torch_dtype=torch.float16,
44
- device_map="auto",
45
- trust_remote_code=True,
46
- low_cpu_mem_usage=True
47
- )
48
- print("๋ชจ๋ธ ๋กœ๋”ฉ ์™„๋ฃŒ")
49
-
50
- except Exception as e:
51
- print(f"๋ชจ๋ธ ๋กœ๋”ฉ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}")
52
- raise Exception(f"๋ชจ๋ธ ๋กœ๋”ฉ ์‹คํŒจ: {e}")
53
-
54
- @spaces.GPU
55
- def generate_response(self, messages, max_tokens=4000, temperature=0.7, top_p=0.9):
56
- try:
57
- # ๋ชจ๋ธ์ด ๋กœ๋“œ๋˜์–ด ์žˆ๋Š”์ง€ ํ™•์ธ
58
- self.ensure_model_loaded()
59
-
60
- # ์ž…๋ ฅ ํ…์ŠคํŠธ ์ค€๋น„
61
- prompt = ""
62
- for msg in messages:
63
- role = msg["role"]
64
- content = msg["content"]
65
- if role == "system":
66
- prompt += f"System: {content}\n"
67
- elif role == "user":
68
- prompt += f"Human: {content}\n"
69
- elif role == "assistant":
70
- prompt += f"Assistant: {content}\n"
71
- prompt += "Assistant: "
72
-
73
- # ํ† ํฌ๋‚˜์ด์ง• ๋ฐ device ์„ค์ •
74
- inputs = self.tokenizer(
75
- prompt,
76
- return_tensors="pt",
77
- padding=True,
78
- truncation=True,
79
- max_length=4096
80
- )
81
-
82
- # ๋ชจ๋“  ํ…์„œ๋ฅผ GPU๋กœ ์ด๋™
83
- input_ids = inputs.input_ids.to(self.model.device)
84
- attention_mask = inputs.attention_mask.to(self.model.device)
85
-
86
- # ์ƒ์„ฑ
87
- with torch.no_grad():
88
- outputs = self.model.generate(
89
- input_ids=input_ids,
90
- attention_mask=attention_mask,
91
- max_new_tokens=max_tokens,
92
- do_sample=True,
93
- temperature=temperature,
94
- top_p=top_p,
95
- pad_token_id=self.tokenizer.pad_token_id,
96
- eos_token_id=self.tokenizer.eos_token_id,
97
- num_return_sequences=1
98
- )
99
-
100
- # ๋””์ฝ”๋”ฉ ์ „์— CPU๋กœ ์ด๋™
101
- outputs = outputs.cpu()
102
- generated_text = self.tokenizer.decode(
103
- outputs[0][input_ids.shape[1]:],
104
- skip_special_tokens=True
105
- )
106
-
107
- # ๋‹จ์–ด ๋‹จ์œ„๋กœ ์ŠคํŠธ๋ฆฌ๋ฐ
108
- words = generated_text.split()
109
- for word in words:
110
- yield type('Response', (), {
111
- 'choices': [type('Choice', (), {
112
- 'delta': {'content': word + " "}
113
- })()]
114
- })()
115
-
116
- except Exception as e:
117
- print(f"์‘๋‹ต ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}")
118
- raise Exception(f"์‘๋‹ต ์ƒ์„ฑ ์‹คํŒจ: {e}")
119
-
120
- class ChatHistory:
121
- def __init__(self):
122
- self.history = []
123
- self.history_file = "/tmp/chat_history.json"
124
- self.load_history()
125
-
126
- def add_conversation(self, user_msg: str, assistant_msg: str):
127
- conversation = {
128
- "timestamp": datetime.now().isoformat(),
129
- "messages": [
130
- {"role": "user", "content": user_msg},
131
- {"role": "assistant", "content": assistant_msg}
132
- ]
133
- }
134
- self.history.append(conversation)
135
- self.save_history()
136
-
137
- def format_for_display(self):
138
- formatted = []
139
- for conv in self.history:
140
- formatted.append([
141
- conv["messages"][0]["content"],
142
- conv["messages"][1]["content"]
143
- ])
144
- return formatted
145
-
146
- def get_messages_for_api(self):
147
- messages = []
148
- for conv in self.history:
149
- messages.extend([
150
- {"role": "user", "content": conv["messages"][0]["content"]},
151
- {"role": "assistant", "content": conv["messages"][1]["content"]}
152
- ])
153
- return messages
154
-
155
- def clear_history(self):
156
- self.history = []
157
- self.save_history()
158
-
159
- def save_history(self):
160
- try:
161
- with open(self.history_file, 'w', encoding='utf-8') as f:
162
- json.dump(self.history, f, ensure_ascii=False, indent=2)
163
- except Exception as e:
164
- print(f"ํžˆ์Šคํ† ๋ฆฌ ์ €์žฅ ์‹คํŒจ: {e}")
165
-
166
- def load_history(self):
167
- try:
168
- if os.path.exists(self.history_file):
169
- with open(self.history_file, 'r', encoding='utf-8') as f:
170
- self.history = json.load(f)
171
- except Exception as e:
172
- print(f"ํžˆ์Šคํ† ๋ฆฌ ๋กœ๋“œ ์‹คํŒจ: {e}")
173
- self.history = []
174
-
175
- # ์ „์—ญ ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
176
- chat_history = ChatHistory()
177
- model_manager = ModelManager()
178
-
179
- def analyze_file_content(content, file_type):
180
- """Analyze file content and return structural summary"""
181
- if file_type in ['parquet', 'csv']:
182
- try:
183
- lines = content.split('\n')
184
- header = lines[0]
185
- columns = header.count('|') - 1
186
- rows = len(lines) - 3
187
- return f"๐Ÿ“Š ๋ฐ์ดํ„ฐ์…‹ ๊ตฌ์กฐ: {columns}๊ฐœ ์ปฌ๋Ÿผ, {rows}๊ฐœ ๋ฐ์ดํ„ฐ"
188
- except:
189
- return "โŒ ๋ฐ์ดํ„ฐ์…‹ ๊ตฌ์กฐ ๋ถ„์„ ์‹คํŒจ"
190
 
191
- lines = content.split('\n')
192
- total_lines = len(lines)
193
- non_empty_lines = len([line for line in lines if line.strip()])
194
-
195
- if any(keyword in content.lower() for keyword in ['def ', 'class ', 'import ', 'function']):
196
- functions = len([line for line in lines if 'def ' in line])
197
- classes = len([line for line in lines if 'class ' in line])
198
- imports = len([line for line in lines if 'import ' in line or 'from ' in line])
199
- return f"๐Ÿ’ป ์ฝ”๋“œ ๊ตฌ์กฐ: {total_lines}์ค„ (ํ•จ์ˆ˜: {functions}, ํด๋ž˜์Šค: {classes}, ์ž„ํฌํŠธ: {imports})"
 
 
 
 
200
 
201
- paragraphs = content.count('\n\n') + 1
202
- words = len(content.split())
203
- return f"๐Ÿ“ ๋ฌธ์„œ ๊ตฌ์กฐ: {total_lines}์ค„, {paragraphs}๋‹จ๋ฝ, ์•ฝ {words}๋‹จ์–ด"
204
-
205
- def read_uploaded_file(file):
206
- if file is None:
207
- return "", ""
208
- try:
209
- file_ext = os.path.splitext(file.name)[1].lower()
210
-
211
- if file_ext == '.parquet':
212
- df = pd.read_parquet(file.name, engine='pyarrow')
213
- content = df.head(10).to_markdown(index=False)
214
- return content, "parquet"
215
- elif file_ext == '.csv':
216
- encodings = ['utf-8', 'cp949', 'euc-kr', 'latin1']
217
- for encoding in encodings:
218
- try:
219
- df = pd.read_csv(file.name, encoding=encoding)
220
- content = f"๐Ÿ“Š ๋ฐ์ดํ„ฐ ๋ฏธ๋ฆฌ๋ณด๊ธฐ:\n{df.head(10).to_markdown(index=False)}\n\n"
221
- content += f"\n๐Ÿ“ˆ ๋ฐ์ดํ„ฐ ์ •๋ณด:\n"
222
- content += f"- ์ „์ฒด ํ–‰ ์ˆ˜: {len(df)}\n"
223
- content += f"- ์ „์ฒด ์—ด ์ˆ˜: {len(df.columns)}\n"
224
- content += f"- ์ปฌ๋Ÿผ ๋ชฉ๋ก: {', '.join(df.columns)}\n"
225
- content += f"\n๐Ÿ“‹ ์ปฌ๋Ÿผ ๋ฐ์ดํ„ฐ ํƒ€์ž…:\n"
226
- for col, dtype in df.dtypes.items():
227
- content += f"- {col}: {dtype}\n"
228
- null_counts = df.isnull().sum()
229
- if null_counts.any():
230
- content += f"\nโš ๏ธ ๊ฒฐ์ธก์น˜:\n"
231
- for col, null_count in null_counts[null_counts > 0].items():
232
- content += f"- {col}: {null_count}๊ฐœ ๋ˆ„๋ฝ\n"
233
- return content, "csv"
234
- except UnicodeDecodeError:
235
- continue
236
- raise UnicodeDecodeError(f"โŒ ์ง€์›๋˜๋Š” ์ธ์ฝ”๋”ฉ์œผ๋กœ ํŒŒ์ผ์„ ์ฝ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค ({', '.join(encodings)})")
237
- else:
238
- encodings = ['utf-8', 'cp949', 'euc-kr', 'latin1']
239
- for encoding in encodings:
240
- try:
241
- with open(file.name, 'r', encoding=encoding) as f:
242
- content = f.read()
243
- return content, "text"
244
- except UnicodeDecodeError:
245
- continue
246
- raise UnicodeDecodeError(f"โŒ ์ง€์›๋˜๋Š” ์ธ์ฝ”๋”ฉ์œผ๋กœ ํŒŒ์ผ์„ ์ฝ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค ({', '.join(encodings)})")
247
- except Exception as e:
248
- return f"โŒ ํŒŒ์ผ ์ฝ๊ธฐ ์˜ค๋ฅ˜: {str(e)}", "error"
249
-
250
- def chat(message, history, uploaded_file, system_message="", max_tokens=4000, temperature=0.7, top_p=0.9):
251
- if not message:
252
- return "", history
253
-
254
- system_prefix = """์ €๋Š” ์—ฌ๋Ÿฌ๋ถ„์˜ ์นœ๊ทผํ•˜๊ณ  ์ง€์ ์ธ AI ์–ด์‹œ์Šคํ„ดํŠธ 'GiniGEN'์ž…๋‹ˆ๋‹ค.. ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์›์น™์œผ๋กœ ์†Œํ†ตํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค:
255
- 1. ๐Ÿค ์นœ๊ทผํ•˜๊ณ  ๊ณต๊ฐ์ ์ธ ํƒœ๋„๋กœ ๋Œ€ํ™”
256
- 2. ๐Ÿ’ก ๋ช…ํ™•ํ•˜๊ณ  ์ดํ•ดํ•˜๊ธฐ ์‰ฌ์šด ์„ค๋ช… ์ œ๊ณต
257
- 3. ๐ŸŽฏ ์งˆ๋ฌธ์˜ ์˜๋„๋ฅผ ์ •ํ™•ํžˆ ํŒŒ์•…ํ•˜์—ฌ ๋งž์ถคํ˜• ๋‹ต๋ณ€
258
- 4. ๐Ÿ“š ํ•„์š”ํ•œ ๊ฒฝ์šฐ ์—…๋กœ๋“œ๋œ ํŒŒ์ผ ๋‚ด์šฉ์„ ์ฐธ๊ณ ํ•˜์—ฌ ๊ตฌ์ฒด์ ์ธ ๋„์›€ ์ œ๊ณต
259
- 5. โœจ ์ถ”๊ฐ€์ ์ธ ํ†ต์ฐฐ๊ณผ ์ œ์•ˆ์„ ํ†ตํ•œ ๊ฐ€์น˜ ์žˆ๋Š” ๋Œ€ํ™”
260
- ํ•ญ์ƒ ์˜ˆ์˜ ๋ฐ”๋ฅด๊ณ  ์นœ์ ˆํ•˜๊ฒŒ ์‘๋‹ตํ•˜๋ฉฐ, ํ•„์š”ํ•œ ๊ฒฝ์šฐ ๊ตฌ์ฒด์ ์ธ ์˜ˆ์‹œ๋‚˜ ์„ค๋ช…์„ ์ถ”๊ฐ€ํ•˜์—ฌ
261
- ์ดํ•ด๋ฅผ ๋•๊ฒ ์Šต๋‹ˆ๋‹ค."""
262
-
263
- try:
264
- # ์ฒซ ๋ฉ”์‹œ์ง€์ผ ๋•Œ ๋ชจ๋ธ ๋กœ๋”ฉ
265
- model_manager.ensure_model_loaded()
266
-
267
- if uploaded_file:
268
- content, file_type = read_uploaded_file(uploaded_file)
269
- if file_type == "error":
270
- error_message = content
271
- chat_history.add_conversation(message, error_message)
272
- return "", history + [[message, error_message]]
273
-
274
- file_summary = analyze_file_content(content, file_type)
275
-
276
- if file_type in ['parquet', 'csv']:
277
- system_message += f"\n\nํŒŒ์ผ ๋‚ด์šฉ:\n```markdown\n{content}\n```"
278
- else:
279
- system_message += f"\n\nํŒŒ์ผ ๋‚ด์šฉ:\n```\n{content}\n```"
280
-
281
- if message == "ํŒŒ์ผ ๋ถ„์„์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค...":
282
- message = f"""[ํŒŒ์ผ ๊ตฌ์กฐ ๋ถ„์„] {file_summary}
283
- ๋‹ค์Œ ๊ด€์ ์—์„œ ๋„์›€์„ ๋“œ๋ฆฌ๊ฒ ์Šต๋‹ˆ๋‹ค:
284
- 1. ๐Ÿ“‹ ์ „๋ฐ˜์ ์ธ ๋‚ด์šฉ ํŒŒ์•…
285
- 2. ๐Ÿ’ก ์ฃผ์š” ํŠน์ง• ์„ค๋ช…
286
- 3. ๐ŸŽฏ ์‹ค์šฉ์ ์ธ ํ™œ์šฉ ๋ฐฉ์•ˆ
287
- 4. โœจ ๊ฐœ์„  ์ œ์•ˆ
288
- 5. ๐Ÿ’ฌ ์ถ”๊ฐ€ ์งˆ๋ฌธ์ด๋‚˜ ํ•„์š”ํ•œ ์„ค๋ช…"""
289
-
290
- messages = [{"role": "system", "content": system_prefix + system_message}]
291
-
292
- if history:
293
- for user_msg, assistant_msg in history:
294
- messages.append({"role": "user", "content": user_msg})
295
- messages.append({"role": "assistant", "content": assistant_msg})
296
-
297
- messages.append({"role": "user", "content": message})
298
-
299
- partial_message = ""
300
-
301
- for response in model_manager.generate_response(
302
- messages,
303
- max_tokens=max_tokens,
304
- temperature=temperature,
305
- top_p=top_p
306
- ):
307
- token = response.choices[0].delta.get('content', '')
308
- if token:
309
- partial_message += token
310
- current_history = history + [[message, partial_message]]
311
- yield "", current_history
312
-
313
- chat_history.add_conversation(message, partial_message)
314
-
315
- except Exception as e:
316
- error_msg = f"โŒ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"
317
- chat_history.add_conversation(message, error_msg)
318
- yield "", history + [[message, error_msg]]
319
-
320
- with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", title="GiniGEN ๐Ÿค–") as demo:
321
- initial_history = chat_history.format_for_display()
322
- with gr.Row():
323
- with gr.Column(scale=2):
324
- chatbot = gr.Chatbot(
325
- value=initial_history,
326
- height=600,
327
- label="๋Œ€ํ™”์ฐฝ ๐Ÿ’ฌ",
328
- show_label=True
329
- )
330
-
331
- msg = gr.Textbox(
332
- label="๋ฉ”์‹œ์ง€ ์ž…๋ ฅ",
333
- show_label=False,
334
- placeholder="๋ฌด์—‡์ด๋“  ๋ฌผ์–ด๋ณด์„ธ์š”... ๐Ÿ’ญ",
335
- container=False
336
- )
337
- with gr.Row():
338
- clear = gr.ClearButton([msg, chatbot], value="๋Œ€ํ™”๋‚ด์šฉ ์ง€์šฐ๊ธฐ")
339
- send = gr.Button("๋ณด๋‚ด๊ธฐ ๐Ÿ“ค")
340
-
341
- with gr.Column(scale=1):
342
- gr.Markdown("### GiniGEN ๐Ÿค– [ํŒŒ์ผ ์—…๋กœ๋“œ] ๐Ÿ“\n์ง€์› ํ˜•์‹: ํ…์ŠคํŠธ, ์ฝ”๋“œ, CSV, Parquet ํŒŒ์ผ")
343
- file_upload = gr.File(
344
- label="ํŒŒ์ผ ์„ ํƒ",
345
- file_types=["text", ".csv", ".parquet"],
346
- type="filepath"
347
- )
348
-
349
- with gr.Accordion("๊ณ ๊ธ‰ ์„ค์ • โš™๏ธ", open=False):
350
- system_message = gr.Textbox(label="์‹œ์Šคํ…œ ๋ฉ”์‹œ์ง€ ๐Ÿ“", value="")
351
- max_tokens = gr.Slider(minimum=1, maximum=8000, value=4000, label="์ตœ๋Œ€ ํ† ํฐ ์ˆ˜ ๐Ÿ“Š")
352
- temperature = gr.Slider(minimum=0, maximum=1, value=0.7, label="์ฐฝ์˜์„ฑ ์ˆ˜์ค€ ๐ŸŒก๏ธ")
353
- top_p = gr.Slider(minimum=0, maximum=1, value=0.9, label="์‘๋‹ต ๋‹ค์–‘์„ฑ ๐Ÿ“ˆ")
354
-
355
- gr.Examples(
356
  examples=[
357
- ["์•ˆ๋…•ํ•˜์„ธ์š”! ์–ด๋–ค ๋„์›€์ด ํ•„์š”ํ•˜์‹ ๊ฐ€์š”? ๐Ÿค"],
358
- ["์ œ๊ฐ€ ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ์„ค๋ช…ํ•ด ์ฃผ์‹œ๊ฒ ์–ด์š”? ๐Ÿ“š"],
359
- ["์ด ๋‚ด์šฉ์„ ์‹ค์ œ๋กœ ์–ด๋–ป๊ฒŒ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ์„๊นŒ์š”? ๐ŸŽฏ"],
360
- ["์ถ”๊ฐ€๋กœ ์กฐ์–ธํ•ด ์ฃผ์‹ค ๋‚ด์šฉ์ด ์žˆ์œผ์‹ ๊ฐ€์š”? โœจ"],
361
- ["๊ถ๊ธˆํ•œ ์ ์ด ๋” ์žˆ๋Š”๋ฐ ์—ฌ์ญค๋ด๋„ ๋ ๊นŒ์š”? ๐Ÿค”"],
 
 
 
 
 
 
362
  ],
363
- inputs=msg,
364
- )
365
-
366
- def clear_chat():
367
- chat_history.clear_history()
368
- return None, None
369
-
370
- msg.submit(
371
- chat,
372
- inputs=[msg, chatbot, file_upload, system_message, max_tokens, temperature, top_p],
373
- outputs=[msg, chatbot]
374
- )
375
-
376
- send.click(
377
- chat,
378
- inputs=[msg, chatbot, file_upload, system_message, max_tokens, temperature, top_p],
379
- outputs=[msg, chatbot]
380
- )
381
-
382
- clear.click(
383
- clear_chat,
384
- outputs=[msg, chatbot]
385
- )
386
-
387
- file_upload.change(
388
- lambda: "ํŒŒ์ผ ๋ถ„์„์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค...",
389
- outputs=msg
390
- ).then(
391
- chat,
392
- inputs=[msg, chatbot, file_upload, system_message, max_tokens, temperature, top_p],
393
- outputs=[msg, chatbot]
394
  )
395
 
396
  if __name__ == "__main__":
397
- demo.launch(
398
- share=False,
399
- show_error=True,
400
- server_name="0.0.0.0",
401
- server_port=7860,
402
- max_threads=1
403
- )
 
 
 
 
 
 
 
1
  import torch
2
+ import gradio as gr
3
  import spaces
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
5
+ import os
6
  from threading import Thread
7
+ import random
8
+ from datasets import load_dataset
9
 
10
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
 
11
  MODEL_ID = "CohereForAI/c4ai-command-r7b-12-2024"
12
+ MODELS = os.environ.get("MODELS")
13
+ MODEL_NAME = MODEL_ID.split("/")[-1]
14
+
15
+ TITLE = "<h1><center>์ƒˆ๋กœ์šด ์ผ๋ณธ์–ด LLM ๋ชจ๋ธ ์›น UI</center></h1>"
16
+
17
+ DESCRIPTION = f"""
18
+ <h3>๋ชจ๋ธ: <a href="https://huggingface.co/CohereForAI/c4ai-command-r7b-12-2024">CohereForAI/c4ai-command-r7b-12-2024</a></h3>
19
+ <center>
20
+ <p>
21
+ <br>
22
+ cc-by-nc
23
+ </p>
24
+ </center>
25
+ """
26
+
27
+ CSS = """
28
+ .duplicate-button {
29
+ margin: auto !important;
30
+ color: white !important;
31
+ background: black !important;
32
+ border-radius: 100vh !important;
33
+ }
34
+ h3 {
35
+ text-align: center;
36
+ }
37
+ .chatbox .messages .message.user {
38
+ background-color: #e1f5fe;
39
+ }
40
+ .chatbox .messages .message.bot {
41
+ background-color: #eeeeee;
42
+ }
43
+ """
44
+
45
+ # ๋ชจ๋ธ๊ณผ ํ† ํฌ๋‚˜์ด์ € ๋กœ๋“œ
46
+ model = AutoModelForCausalLM.from_pretrained(
47
+ MODEL_ID,
48
+ torch_dtype=torch.bfloat16,
49
+ device_map="auto",
50
+ )
51
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
52
+
53
+ # ๋ฐ์ดํ„ฐ์…‹ ๋กœ๋“œ
54
+ dataset = load_dataset("elyza/ELYZA-tasks-100")
55
+ print(dataset)
56
+
57
+ split_name = "train" if "train" in dataset else "test"
58
+ examples_list = list(dataset[split_name])
59
+ examples = random.sample(examples_list, 50)
60
+ example_inputs = [[example['input']] for example in examples]
61
+
62
+ @spaces.GPU
63
+ def stream_chat(message: str, history: list, temperature: float, max_new_tokens: int, top_p: float, top_k: int, penalty: float):
64
+ print(f'message is - {message}')
65
+ print(f'history is - {history}')
66
+ conversation = []
67
+ for prompt, answer in history:
68
+ conversation.extend([{"role": "user", "content": prompt}, {"role": "assistant", "content": answer}])
69
+ conversation.append({"role": "user", "content": message})
70
+
71
+ input_ids = tokenizer.apply_chat_template(conversation, tokenize=False, add_generation_prompt=True)
72
+ inputs = tokenizer(input_ids, return_tensors="pt").to(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
+ streamer = TextIteratorStreamer(tokenizer, timeout=10., skip_prompt=True, skip_special_tokens=True)
75
+
76
+ generate_kwargs = dict(
77
+ inputs,
78
+ streamer=streamer,
79
+ top_k=top_k,
80
+ top_p=top_p,
81
+ repetition_penalty=penalty,
82
+ max_new_tokens=max_new_tokens,
83
+ do_sample=True,
84
+ temperature=temperature,
85
+ eos_token_id=[255001],
86
+ )
87
 
88
+ thread = Thread(target=model.generate, kwargs=generate_kwargs)
89
+ thread.start()
90
+
91
+ buffer = ""
92
+ for new_text in streamer:
93
+ buffer += new_text
94
+ yield buffer
95
+
96
+ chatbot = gr.Chatbot(height=500)
97
+
98
+ with gr.Blocks(css=CSS) as demo:
99
+ gr.HTML(TITLE)
100
+ gr.HTML(DESCRIPTION)
101
+ gr.ChatInterface(
102
+ fn=stream_chat,
103
+ chatbot=chatbot,
104
+ fill_height=True,
105
+ theme="soft",
106
+ additional_inputs_accordion=gr.Accordion(label="โš™๏ธ ๋งค๊ฐœ๋ณ€์ˆ˜", open=False, render=False),
107
+ additional_inputs=[
108
+ gr.Slider(
109
+ minimum=0,
110
+ maximum=1,
111
+ step=0.1,
112
+ value=0.8,
113
+ label="์˜จ๋„",
114
+ render=False,
115
+ ),
116
+ gr.Slider(
117
+ minimum=128,
118
+ maximum=1000000,
119
+ step=1,
120
+ value=100000,
121
+ label="์ตœ๋Œ€ ํ† ํฐ ์ˆ˜",
122
+ render=False,
123
+ ),
124
+ gr.Slider(
125
+ minimum=0.0,
126
+ maximum=1.0,
127
+ step=0.1,
128
+ value=0.8,
129
+ label="์ƒ์œ„ ํ™•๋ฅ ",
130
+ render=False,
131
+ ),
132
+ gr.Slider(
133
+ minimum=1,
134
+ maximum=20,
135
+ step=1,
136
+ value=20,
137
+ label="์ƒ์œ„ K",
138
+ render=False,
139
+ ),
140
+ gr.Slider(
141
+ minimum=0.0,
142
+ maximum=2.0,
143
+ step=0.1,
144
+ value=1.0,
145
+ label="๋ฐ˜๋ณต ํŒจ๋„ํ‹ฐ",
146
+ render=False,
147
+ ),
148
+ ],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  examples=[
150
+ ["์•„์ด์˜ ์—ฌ๋ฆ„๋ฐฉํ•™ ๊ณผํ•™ ํ”„๋กœ์ ํŠธ๋ฅผ ์œ„ํ•œ 5๊ฐ€์ง€ ์•„์ด๋””์–ด๋ฅผ ์ฃผ์„ธ์š”."],
151
+ ["๋งˆํฌ๋‹ค์šด์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ธŒ๋ ˆ์ดํฌ์•„์›ƒ ๊ฒŒ์ž„ ๋งŒ๋“ค๊ธฐ ํŠœํ† ๋ฆฌ์–ผ์„ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”."],
152
+ ["์ดˆ๋Šฅ๋ ฅ์„ ๊ฐ€์ง„ ์ฃผ์ธ๊ณต์˜ SF ์ด์•ผ๊ธฐ ์‹œ๋‚˜๋ฆฌ์˜ค๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”. ๋ณต์„  ์„ค์ •, ํ…Œ๋งˆ์™€ ๋กœ๊ทธ๋ผ์ธ์„ ๋…ผ๋ฆฌ์ ์œผ๋กœ ์‚ฌ์šฉํ•ด์ฃผ์„ธ์š”"],
153
+ ["์•„์ด์˜ ์—ฌ๋ฆ„๋ฐฉํ•™ ์ž์œ ์—ฐ๊ตฌ๋ฅผ ์œ„ํ•œ 5๊ฐ€์ง€ ์•„์ด๋””์–ด์™€ ๊ทธ ๋ฐฉ๋ฒ•์„ ๊ฐ„๋‹จํžˆ ์•Œ๋ ค์ฃผ์„ธ์š”."],
154
+ ["ํผ์ฆ ๊ฒŒ์ž„ ์Šคํฌ๋ฆฝํŠธ ์ž‘์„ฑ์„ ์œ„ํ•œ ์กฐ์–ธ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค"],
155
+ ["๋งˆํฌ๋‹ค์šด ํ˜•์‹์œผ๋กœ ๋ธ”๋ก ๊นจ๊ธฐ ๊ฒŒ์ž„ ์ œ์ž‘ ๊ต๊ณผ์„œ๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”"],
156
+ ["์‹ค๋ฒ„ ๅทๆŸณ๋ฅผ ์ƒ๊ฐํ•ด์ฃผ์„ธ์š”"],
157
+ ["์ผ๋ณธ์–ด ๊ด€์šฉ๊ตฌ, ์†๋‹ด์— ๊ด€ํ•œ ์‹œํ—˜ ๋ฌธ์ œ๋ฅผ ๋งŒ๋“ค์–ด์ฃผ์„ธ์š”"],
158
+ ["๋„๋ผ์—๋ชฝ์˜ ๋“ฑ์žฅ์ธ๋ฌผ์„ ์•Œ๋ ค์ฃผ์„ธ์š”"],
159
+ ["์˜ค์ฝ”๋…ธ๋ฏธ์•ผํ‚ค ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์„ ์•Œ๋ ค์ฃผ์„ธ์š”"],
160
+ ["๋ฌธ์ œ 9.11๊ณผ 9.9 ์ค‘ ์–ด๋Š ๊ฒƒ์ด ๋” ํฐ๊ฐ€์š”? step by step์œผ๋กœ ๋…ผ๋ฆฌ์ ์œผ๋กœ ์ƒ๊ฐํ•ด์ฃผ์„ธ์š”."],
161
  ],
162
+ cache_examples=False,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  )
164
 
165
  if __name__ == "__main__":
166
+ demo.launch()