File size: 18,667 Bytes
5c52ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce55546
5c52ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce55546
5c52ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb2d730
5c52ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb2d730
5c52ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb2d730
 
5c52ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce55546
5c52ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce55546
5c52ea1
 
 
ce55546
5c52ea1
 
 
 
ce55546
5c52ea1
 
 
fb2d730
5c52ea1
 
 
fb2d730
 
 
 
 
5c52ea1
 
 
ce55546
 
5c52ea1
ce55546
5c52ea1
ce55546
 
 
 
 
 
 
 
 
5c52ea1
 
 
 
 
 
ce55546
5c52ea1
 
 
 
 
 
 
 
 
ce55546
 
 
 
 
5c52ea1
 
ce55546
5c52ea1
 
ce55546
 
 
 
 
 
 
 
 
 
5c52ea1
 
 
ce55546
5c52ea1
 
 
 
 
ce55546
 
 
 
 
 
5c52ea1
 
 
 
ce55546
 
5c52ea1
 
 
ce55546
5c52ea1
 
 
 
 
 
 
 
 
 
ce55546
5c52ea1
ce55546
5c52ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb2d730
5c52ea1
 
 
 
 
 
 
 
 
ce55546
5c52ea1
 
ce55546
5c52ea1
 
fb2d730
 
 
 
 
 
5c52ea1
 
 
 
 
 
 
 
 
 
 
 
fb2d730
5c52ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb2d730
 
5c52ea1
 
 
 
 
 
 
fb2d730
5c52ea1
fb2d730
 
5c52ea1
fb2d730
5c52ea1
fb2d730
 
 
5c52ea1
 
 
 
ce55546
5c52ea1
 
 
ce55546
 
 
 
5c52ea1
 
 
 
 
ce55546
 
 
 
5c52ea1
 
ce55546
5c52ea1
 
 
 
 
 
fb2d730
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
import gradio as gr
import spaces
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer
from threading import Thread
import re
import json
from datetime import datetime
import math
import os

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# ๐Ÿ”ง ๋ชจ๋ธ ๋กœ๋”ฉ
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

MODEL_ID = "zai-org/GLM-4.7-Flash"

print(f"[Init] Loading tokenizer from {MODEL_ID}...")
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)

model = None

def get_model():
    global model
    if model is None:
        print("[Model] Loading model with bfloat16...")
        model = AutoModelForCausalLM.from_pretrained(
            MODEL_ID,
            torch_dtype=torch.bfloat16,
            device_map="auto",
            trust_remote_code=True,
            low_cpu_mem_usage=True,
        )
        print(f"[Model] Model loaded on {model.device}")
    return model

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# ๐Ÿ“„ ํŒŒ์ผ ์ฒ˜๋ฆฌ ํ•จ์ˆ˜
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

def extract_text_from_pdf(file_path: str) -> str:
    """PDF ํŒŒ์ผ์—์„œ ํ…์ŠคํŠธ ์ถ”์ถœ"""
    try:
        import fitz
        doc = fitz.open(file_path)
        text_parts = []
        for page_num, page in enumerate(doc, 1):
            text = page.get_text()
            if text.strip():
                text_parts.append(f"[ํŽ˜์ด์ง€ {page_num}]\n{text}")
        doc.close()
        return "\n\n".join(text_parts) if text_parts else "[PDF์—์„œ ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค]"
    except ImportError:
        try:
            from pypdf import PdfReader
            reader = PdfReader(file_path)
            text_parts = []
            for page_num, page in enumerate(reader.pages, 1):
                text = page.extract_text()
                if text and text.strip():
                    text_parts.append(f"[ํŽ˜์ด์ง€ {page_num}]\n{text}")
            return "\n\n".join(text_parts) if text_parts else "[PDF์—์„œ ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค]"
        except Exception as e:
            return f"[PDF ์ฝ๊ธฐ ์˜ค๋ฅ˜: {str(e)}]"
    except Exception as e:
        return f"[PDF ์ฝ๊ธฐ ์˜ค๋ฅ˜: {str(e)}]"

def extract_text_from_docx(file_path: str) -> str:
    """DOCX ํŒŒ์ผ์—์„œ ํ…์ŠคํŠธ ์ถ”์ถœ"""
    try:
        from docx import Document
        doc = Document(file_path)
        text_parts = []
        for para in doc.paragraphs:
            if para.text.strip():
                text_parts.append(para.text)
        for table_idx, table in enumerate(doc.tables, 1):
            table_text = [f"\n[ํ‘œ {table_idx}]"]
            for row in table.rows:
                row_text = " | ".join(cell.text.strip() for cell in row.cells)
                if row_text.strip():
                    table_text.append(row_text)
            if len(table_text) > 1:
                text_parts.append("\n".join(table_text))
        return "\n\n".join(text_parts) if text_parts else "[DOCX์—์„œ ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค]"
    except Exception as e:
        return f"[DOCX ์ฝ๊ธฐ ์˜ค๋ฅ˜: {str(e)}]"

def extract_text_from_txt(file_path: str) -> str:
    """TXT ํŒŒ์ผ์—์„œ ํ…์ŠคํŠธ ์ถ”์ถœ"""
    try:
        encodings = ['utf-8', 'cp949', 'euc-kr', 'latin-1']
        for encoding in encodings:
            try:
                with open(file_path, 'r', encoding=encoding) as f:
                    return f.read()
            except UnicodeDecodeError:
                continue
        return "[ํ…์ŠคํŠธ ํŒŒ์ผ ์ธ์ฝ”๋”ฉ์„ ์ธ์‹ํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค]"
    except Exception as e:
        return f"[TXT ์ฝ๊ธฐ ์˜ค๋ฅ˜: {str(e)}]"

def process_uploaded_file(file) -> tuple:
    """์—…๋กœ๋“œ๋œ ํŒŒ์ผ ์ฒ˜๋ฆฌ"""
    if file is None:
        return "", ""
    
    file_path = file.name if hasattr(file, 'name') else str(file)
    file_name = os.path.basename(file_path)
    file_ext = os.path.splitext(file_name)[1].lower()
    
    if file_ext == '.pdf':
        content = extract_text_from_pdf(file_path)
    elif file_ext == '.docx':
        content = extract_text_from_docx(file_path)
    elif file_ext in ['.txt', '.md', '.py', '.js', '.html', '.css', '.json', '.xml', '.csv']:
        content = extract_text_from_txt(file_path)
    else:
        content = f"[์ง€์›ํ•˜์ง€ ์•Š๋Š” ํŒŒ์ผ ํ˜•์‹: {file_ext}]"
    
    max_chars = 50000
    if len(content) > max_chars:
        content = content[:max_chars] + f"\n\n... [ํ…์ŠคํŠธ๊ฐ€ {max_chars}์ž๋กœ ์ž˜๋ ธ์Šต๋‹ˆ๋‹ค]"
    
    return file_name, content

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# ๐Ÿ› ๏ธ Tool Definitions
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

def execute_tool(tool_name: str, arguments: dict) -> str:
    """๋„๊ตฌ ์‹คํ–‰"""
    try:
        if tool_name == "calculator":
            expr = arguments.get("expression", "")
            allowed_names = {
                "abs": abs, "round": round, "min": min, "max": max,
                "sum": sum, "pow": pow, "sqrt": math.sqrt,
                "sin": math.sin, "cos": math.cos, "tan": math.tan,
                "log": math.log, "log10": math.log10, "exp": math.exp,
                "pi": math.pi, "e": math.e,
                "floor": math.floor, "ceil": math.ceil,
            }
            expr = re.sub(r'[^0-9+\-*/().a-zA-Z_ ]', '', expr)
            result = eval(expr, {"__builtins__": {}}, allowed_names)
            return f"๊ณ„์‚ฐ ๊ฒฐ๊ณผ: {expr} = {result}"
        
        elif tool_name == "get_current_time":
            tz = arguments.get("timezone", "UTC")
            now = datetime.now()
            return f"ํ˜„์žฌ ์‹œ๊ฐ„ ({tz}): {now.strftime('%Y-%m-%d %H:%M:%S')}"
        
        elif tool_name == "unit_converter":
            value = arguments.get("value", 0)
            from_unit = arguments.get("from_unit", "").lower()
            to_unit = arguments.get("to_unit", "").lower()
            
            conversions = {
                ("km", "m"): lambda x: x * 1000,
                ("m", "km"): lambda x: x / 1000,
                ("kg", "g"): lambda x: x * 1000,
                ("g", "kg"): lambda x: x / 1000,
                ("c", "f"): lambda x: x * 9/5 + 32,
                ("f", "c"): lambda x: (x - 32) * 5/9,
                ("km", "mile"): lambda x: x * 0.621371,
                ("mile", "km"): lambda x: x * 1.60934,
                ("kg", "lb"): lambda x: x * 2.20462,
                ("lb", "kg"): lambda x: x * 0.453592,
            }
            
            key = (from_unit, to_unit)
            if key in conversions:
                result = conversions[key](value)
                return f"๋ณ€ํ™˜ ๊ฒฐ๊ณผ: {value} {from_unit} = {result:.4f} {to_unit}"
            else:
                return f"์ง€์›ํ•˜์ง€ ์•Š๋Š” ๋‹จ์œ„ ๋ณ€ํ™˜: {from_unit} -> {to_unit}"
        
        elif tool_name == "code_executor":
            code = arguments.get("code", "")
            local_vars = {}
            safe_builtins = {"print": print, "range": range, "len": len, "str": str, "int": int, "float": float, "list": list, "dict": dict}
            exec(code, {"__builtins__": safe_builtins}, local_vars)
            if "result" in local_vars:
                return f"์‹คํ–‰ ๊ฒฐ๊ณผ: {local_vars['result']}"
            return "์ฝ”๋“œ ์‹คํ–‰ ์™„๋ฃŒ"
        
        else:
            return f"์•Œ ์ˆ˜ ์—†๋Š” ๋„๊ตฌ: {tool_name}"
    
    except Exception as e:
        return f"๋„๊ตฌ ์‹คํ–‰ ์˜ค๋ฅ˜: {str(e)}"

def parse_tool_calls(response: str) -> list:
    """์‘๋‹ต์—์„œ ๋„๊ตฌ ํ˜ธ์ถœ ํŒŒ์‹ฑ"""
    tool_calls = []
    patterns = [
        r'<\|tool_call\|>(\{.*?\})<\|/tool_call\|>',
        r'```json\s*(\{[^`]*"name"[^`]*\})\s*```',
        r'\{"name":\s*"(\w+)",\s*"arguments":\s*(\{[^}]+\})\}',
    ]
    for pattern in patterns:
        matches = re.findall(pattern, response, re.DOTALL)
        for match in matches:
            try:
                if isinstance(match, tuple):
                    tool_call = {"name": match[0], "arguments": json.loads(match[1])}
                else:
                    tool_call = json.loads(match)
                tool_calls.append(tool_call)
            except:
                continue
    return tool_calls

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# ๐Ÿ’ฌ ์ŠคํŠธ๋ฆฌ๋ฐ ์ฑ„ํŒ… ํ•จ์ˆ˜ (Gradio 6.0 messages format)
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

file_context = {"name": "", "content": ""}

@spaces.GPU(duration=120)
def chat_streaming(
    message: str,
    history: list,
    system_prompt: str,
    max_tokens: int,
    temperature: float,
    top_p: float,
    enable_thinking: bool,
    enable_tools: bool,
):
    """์ŠคํŠธ๋ฆฌ๋ฐ ์ฑ„ํŒ… ์ƒ์„ฑ - Gradio 6.0 messages format"""
    global file_context
    
    if not message.strip():
        yield history
        return
    
    model = get_model()
    
    # ์‹œ์Šคํ…œ ํ”„๋กฌํ”„ํŠธ ๊ตฌ์„ฑ
    sys_content = system_prompt if system_prompt.strip() else "You are a helpful AI assistant."
    
    if file_context["content"]:
        sys_content += f"\n\n[์—…๋กœ๋“œ๋œ ํŒŒ์ผ: {file_context['name']}]\nํŒŒ์ผ ๋‚ด์šฉ:\n---\n{file_context['content']}\n---"
    
    if enable_tools:
        tool_desc = """
You have access to these tools:
1. calculator: Math calculations - {"name": "calculator", "arguments": {"expression": "..."}}
2. get_current_time: Current time - {"name": "get_current_time", "arguments": {}}
3. unit_converter: Unit conversion - {"name": "unit_converter", "arguments": {"value": N, "from_unit": "...", "to_unit": "..."}}
4. code_executor: Run Python - {"name": "code_executor", "arguments": {"code": "..."}}
"""
        sys_content += f"\n\n{tool_desc}"
    
    # ๋ชจ๋ธ์šฉ ๋ฉ”์‹œ์ง€ ๊ตฌ์„ฑ
    messages = [{"role": "system", "content": sys_content}]
    
    # ํžˆ์Šคํ† ๋ฆฌ ๋ณ€ํ™˜ (Gradio 6.0 format -> ๋ชจ๋ธ format)
    for h in history:
        if isinstance(h, dict):
            messages.append({"role": h["role"], "content": h["content"]})
        elif isinstance(h, (list, tuple)) and len(h) == 2:
            if h[0]:
                messages.append({"role": "user", "content": h[0]})
            if h[1]:
                messages.append({"role": "assistant", "content": h[1]})
    
    # ํ˜„์žฌ ๋ฉ”์‹œ์ง€
    user_content = message
    if enable_thinking:
        user_content = f"<think>\nLet me think step by step.\n</think>\n\n{message}"
    
    messages.append({"role": "user", "content": user_content})
    
    # ํ† ํฌ๋‚˜์ด์ฆˆ
    try:
        inputs = tokenizer.apply_chat_template(
            messages,
            add_generation_prompt=True,
            tokenize=True,
            return_dict=True,
            return_tensors="pt",
        ).to(model.device)
    except Exception as e:
        new_history = history + [
            {"role": "user", "content": message},
            {"role": "assistant", "content": f"ํ† ํฌ๋‚˜์ด์ฆˆ ์˜ค๋ฅ˜: {str(e)}"}
        ]
        yield new_history
        return
    
    # ์ŠคํŠธ๋ฆฌ๋จธ ์„ค์ •
    streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
    
    # GenerationConfig ์‚ฌ์šฉ
    from transformers import GenerationConfig
    gen_config = GenerationConfig(
        max_new_tokens=max_tokens,
        temperature=temperature if temperature > 0 else 0.01,
        top_p=top_p,
        do_sample=temperature > 0,
        pad_token_id=tokenizer.pad_token_id or tokenizer.eos_token_id,
    )
    
    generation_kwargs = {
        **inputs,
        "streamer": streamer,
        "generation_config": gen_config,
    }
    
    thread = Thread(target=model.generate, kwargs=generation_kwargs)
    thread.start()
    
    # Gradio 6.0 messages format์œผ๋กœ ํžˆ์Šคํ† ๋ฆฌ ๊ตฌ์„ฑ
    new_history = history + [
        {"role": "user", "content": message},
        {"role": "assistant", "content": ""}
    ]
    
    partial_response = ""
    
    for new_token in streamer:
        partial_response += new_token
        new_history[-1]["content"] = partial_response
        yield new_history
    
    thread.join()
    
    # Tool ํ˜ธ์ถœ ์ฒ˜๋ฆฌ
    if enable_tools:
        tool_calls = parse_tool_calls(partial_response)
        if tool_calls:
            tool_results = []
            for tc in tool_calls:
                result = execute_tool(tc.get("name", ""), tc.get("arguments", {}))
                tool_results.append(result)
            
            if tool_results:
                final_response = partial_response + "\n\n๐Ÿ“Œ **๋„๊ตฌ ์‹คํ–‰ ๊ฒฐ๊ณผ:**\n" + "\n".join(tool_results)
                new_history[-1]["content"] = final_response
    
    yield new_history

def handle_file_upload(file):
    """ํŒŒ์ผ ์—…๋กœ๋“œ ์ฒ˜๋ฆฌ"""
    global file_context
    
    if file is None:
        file_context = {"name": "", "content": ""}
        return "๐Ÿ“‚ ํŒŒ์ผ์ด ์ œ๊ฑฐ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."
    
    file_name, content = process_uploaded_file(file)
    
    if content.startswith("[") and "์˜ค๋ฅ˜" in content:
        file_context = {"name": "", "content": ""}
        return f"โŒ {content}"
    
    file_context = {"name": file_name, "content": content}
    
    preview = content[:500] + "..." if len(content) > 500 else content
    char_count = len(content)
    
    return f"โœ… **ํŒŒ์ผ ๋กœ๋“œ ์™„๋ฃŒ: {file_name}**\n- ๋ฌธ์ž ์ˆ˜: {char_count:,}์ž\n\n๋ฏธ๋ฆฌ๋ณด๊ธฐ:\n```\n{preview}\n```"

def clear_file():
    """ํŒŒ์ผ ์ปจํ…์ŠคํŠธ ์ดˆ๊ธฐํ™”"""
    global file_context
    file_context = {"name": "", "content": ""}
    return None, "๐Ÿ“‚ ํŒŒ์ผ์ด ์ œ๊ฑฐ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."

def clear_chat():
    """์ฑ„ํŒ… ์ดˆ๊ธฐํ™”"""
    return []

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# ๐ŸŽจ Gradio UI (6.0 ํ˜ธํ™˜ - messages format)
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

with gr.Blocks(title="GLM-4.7-Flash Chatbot") as demo:
    gr.Markdown("""
    # ๐Ÿค– GLM-4.7-Flash Chatbot
    **30B-A3B MoE ๋ชจ๋ธ ๊ธฐ๋ฐ˜ ์ŠคํŠธ๋ฆฌ๋ฐ ์ฑ—๋ด‡** | ๋ฌธ์„œ ๋ถ„์„ | Tool Calling
    
    ๐Ÿ“„ PDF | ๐Ÿ“ DOCX | ๐Ÿ“ƒ TXT | ๐Ÿงฎ ๊ณ„์‚ฐ๊ธฐ | ๐Ÿ• ์‹œ๊ฐ„์กฐํšŒ | ๐Ÿ“ ๋‹จ์œ„๋ณ€ํ™˜ | ๐Ÿ ์ฝ”๋“œ์‹คํ–‰
    """)
    
    with gr.Row():
        with gr.Column(scale=3):
            chatbot = gr.Chatbot(
                label="๋Œ€ํ™”",
                height=500,
            )
            
            with gr.Row():
                message = gr.Textbox(
                    label="๋ฉ”์‹œ์ง€ ์ž…๋ ฅ",
                    placeholder="๋ฉ”์‹œ์ง€๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”...",
                    lines=3,
                    scale=4,
                )
                submit_btn = gr.Button("์ „์†ก ๐Ÿ“ค", variant="primary", scale=1)
            
            with gr.Row():
                clear_btn = gr.Button("๋Œ€ํ™” ์ดˆ๊ธฐํ™” ๐Ÿ—‘๏ธ")
                stop_btn = gr.Button("์ƒ์„ฑ ์ค‘์ง€ โน๏ธ")
            
            with gr.Accordion("๐Ÿ“ ๋ฌธ์„œ ์—…๋กœ๋“œ (PDF / DOCX / TXT)", open=True):
                file_upload = gr.File(
                    label="ํŒŒ์ผ ์„ ํƒ",
                    file_types=[".pdf", ".docx", ".txt", ".md", ".py", ".js", ".html", ".css", ".json", ".xml", ".csv"],
                    file_count="single",
                )
                file_status = gr.Markdown("๐Ÿ“‚ ํŒŒ์ผ์„ ์—…๋กœ๋“œํ•˜๋ฉด ๋‚ด์šฉ์„ ๋ถ„์„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.")
                clear_file_btn = gr.Button("๐Ÿ“‚ ํŒŒ์ผ ์ œ๊ฑฐ", size="sm")
        
        with gr.Column(scale=1):
            gr.Markdown("### โš™๏ธ ์„ค์ •")
            
            system_prompt = gr.Textbox(
                label="์‹œ์Šคํ…œ ํ”„๋กฌํ”„ํŠธ",
                value="You are a helpful AI assistant. Answer in the same language as the user.",
                lines=3,
            )
            
            max_tokens = gr.Slider(64, 4096, value=1024, step=64, label="์ตœ๋Œ€ ํ† ํฐ ์ˆ˜")
            temperature = gr.Slider(0, 2, value=0.7, step=0.1, label="Temperature")
            top_p = gr.Slider(0.1, 1.0, value=0.9, step=0.05, label="Top-P")
            
            enable_thinking = gr.Checkbox(label="๐Ÿง  Thinking ๋ชจ๋“œ", value=False)
            enable_tools = gr.Checkbox(label="๐Ÿ› ๏ธ Tool Calling", value=True)
            
            gr.Markdown("### ๐Ÿ“ ์˜ˆ์‹œ")
            gr.Examples(
                examples=[
                    ["์•ˆ๋…•ํ•˜์„ธ์š”!"],
                    ["์—…๋กœ๋“œํ•œ ๋ฌธ์„œ๋ฅผ ์š”์•ฝํ•ด์ค˜"],
                    ["123 * 456์„ ๊ณ„์‚ฐํ•ด์ค˜"],
                    ["ํ˜„์žฌ ์‹œ๊ฐ„์€?"],
                    ["100km๋Š” ๋ช‡ ๋งˆ์ผ?"],
                ],
                inputs=message,
            )
    
    # ์ด๋ฒคํŠธ - Gradio 6.0์—์„œ๋Š” chatbot๋งŒ output
    submit_event = submit_btn.click(
        fn=chat_streaming,
        inputs=[message, chatbot, system_prompt, max_tokens, temperature, top_p, enable_thinking, enable_tools],
        outputs=[chatbot],
    ).then(
        fn=lambda: "",
        outputs=[message],
    )
    
    message.submit(
        fn=chat_streaming,
        inputs=[message, chatbot, system_prompt, max_tokens, temperature, top_p, enable_thinking, enable_tools],
        outputs=[chatbot],
    ).then(
        fn=lambda: "",
        outputs=[message],
    )
    
    clear_btn.click(fn=clear_chat, outputs=[chatbot])
    stop_btn.click(fn=None, cancels=[submit_event])
    
    file_upload.change(fn=handle_file_upload, inputs=[file_upload], outputs=[file_status])
    clear_file_btn.click(fn=clear_file, outputs=[file_upload, file_status])

if __name__ == "__main__":
    demo.queue().launch(server_name="0.0.0.0", server_port=7860)