File size: 8,515 Bytes
f9b9d56
83ee74c
574f73e
705c5b5
83ee74c
f9b9d56
ad9db85
 
 
7ddfb78
 
 
ad9db85
 
 
 
f9b9d56
2af89cf
da20c1b
99d94e0
da20c1b
99d94e0
 
 
 
 
da20c1b
 
 
2af89cf
da20c1b
2af89cf
 
 
 
da20c1b
2af89cf
 
da20c1b
 
 
 
 
 
2af89cf
705c5b5
0997082
2af89cf
705c5b5
99d94e0
 
 
705c5b5
2af89cf
 
99d94e0
 
 
 
 
 
 
 
705c5b5
99d94e0
 
2af89cf
705c5b5
2af89cf
0997082
d57197f
 
 
 
 
 
 
 
ad9db85
da20c1b
 
 
 
 
99d94e0
 
da20c1b
99d94e0
da20c1b
 
705c5b5
7ffca43
2af89cf
 
da20c1b
 
2af89cf
da20c1b
2af89cf
7ffca43
99d94e0
7ffca43
 
da20c1b
7ffca43
 
da20c1b
2af89cf
da20c1b
 
 
 
 
 
 
705c5b5
 
d57197f
0997082
705c5b5
0997082
ad9db85
da20c1b
 
ad9db85
f2c0975
 
83ee74c
0997082
 
83ee74c
7ffca43
705c5b5
da20c1b
 
 
0997082
7ffca43
da20c1b
705c5b5
7b3fa19
7ffca43
7b3fa19
 
63c5e29
 
 
ad9db85
7ffca43
 
 
 
 
 
63c5e29
 
 
2af89cf
ad9db85
 
 
 
 
 
7ffca43
99d94e0
 
d57197f
7ffca43
63c5e29
 
 
 
 
 
 
 
7ffca43
 
ad9db85
da20c1b
 
 
 
 
 
7ffca43
 
 
 
 
ad9db85
da20c1b
 
7ffca43
63c5e29
 
 
 
da20c1b
 
 
 
 
 
63c5e29
 
 
f9b9d56
 
63c5e29
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
import gradio as gr
from huggingface_hub import InferenceClient
import os
import pandas as pd
from typing import List, Tuple

# LLM ๋ชจ๋ธ ์ •์˜
LLM_MODELS = {
    "Default": "CohereForAI/c4ai-command-r-plus-08-2024",  # ๊ธฐ๋ณธ ๋ชจ๋ธ
    "Meta": "meta-llama/Llama-3.3-70B-Instruct",    
    "Mistral": "mistralai/Mistral-Nemo-Instruct-2407",
    "Alibaba": "Qwen/QwQ-32B-Preview"
}

def get_client(model_name):
    return InferenceClient(LLM_MODELS[model_name], token=os.getenv("HF_TOKEN"))

def analyze_file_content(content, file_type):
    """ํŒŒ์ผ ๋‚ด์šฉ์„ ๋ถ„์„ํ•˜์—ฌ ๊ตฌ์กฐ์  ์š”์•ฝ์„ ๋ฐ˜ํ™˜"""
    if file_type in ['parquet', 'csv']:
        try:
            # ๋ฐ์ดํ„ฐ์…‹ ๊ตฌ์กฐ ๋ถ„์„
            lines = content.split('\n')
            header = lines[0]
            columns = header.count('|') - 1
            rows = len(lines) - 3  # ํ—ค๋”์™€ ๊ตฌ๋ถ„์„  ์ œ์™ธ
            return f"๋ฐ์ดํ„ฐ์…‹ ๊ตฌ์กฐ: {columns}๊ฐœ ์ปฌ๋Ÿผ, {rows}๊ฐœ ๋ฐ์ดํ„ฐ ์ƒ˜ํ”Œ"
        except:
            return "๋ฐ์ดํ„ฐ์…‹ ๊ตฌ์กฐ ๋ถ„์„ ์‹คํŒจ"
    
    # ํ…์ŠคํŠธ/์ฝ”๋“œ ํŒŒ์ผ์˜ ๊ฒฝ์šฐ
    lines = content.split('\n')
    total_lines = len(lines)
    non_empty_lines = len([line for line in lines if line.strip()])
    
    if any(keyword in content.lower() for keyword in ['def ', 'class ', 'import ', 'function']):
        functions = len([line for line in lines if 'def ' in line])
        classes = len([line for line in lines if 'class ' in line])
        imports = len([line for line in lines if 'import ' in line or 'from ' in line])
        return f"์ฝ”๋“œ ๊ตฌ์กฐ ๋ถ„์„: ์ด {total_lines}์ค„ (ํ•จ์ˆ˜ {functions}๊ฐœ, ํด๋ž˜์Šค {classes}๊ฐœ, ์ž„ํฌํŠธ {imports}๊ฐœ)"
    
    paragraphs = content.count('\n\n') + 1
    words = len(content.split())
    return f"๋ฌธ์„œ ๊ตฌ์กฐ ๋ถ„์„: ์ด {total_lines}์ค„, {paragraphs}๊ฐœ ๋ฌธ๋‹จ, ์•ฝ {words}๊ฐœ ๋‹จ์–ด"

def read_uploaded_file(file):
    if file is None:
        return "", ""
    try:
        file_ext = os.path.splitext(file.name)[1].lower()
        
        if file_ext == '.parquet':
            df = pd.read_parquet(file.name, engine='pyarrow')
            content = df.head(10).to_markdown(index=False)
            return content, "parquet"
        elif file_ext == '.csv':
            df = pd.read_csv(file.name)
            content = f"๋ฐ์ดํ„ฐ ๋ฏธ๋ฆฌ๋ณด๊ธฐ:\n{df.head(10).to_markdown(index=False)}\n\n"
            content += f"\n๋ฐ์ดํ„ฐ ์ •๋ณด:\n"
            content += f"- ์ด ํ–‰ ์ˆ˜: {len(df)}\n"
            content += f"- ์ด ์—ด ์ˆ˜: {len(df.columns)}\n"
            content += f"- ์ปฌ๋Ÿผ ๋ชฉ๋ก: {', '.join(df.columns)}\n"
            return content, "csv"
        else:
            with open(file.name, 'r', encoding='utf-8') as f:
                content = f.read()
            return content, "text"
    except Exception as e:
        return f"ํŒŒ์ผ์„ ์ฝ๋Š” ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}", "error"

def format_history(history):
    formatted_history = []
    for user_msg, assistant_msg in history:
        formatted_history.append({"role": "user", "content": user_msg})
        if assistant_msg:
            formatted_history.append({"role": "assistant", "content": assistant_msg})
    return formatted_history

def chat(message, history, uploaded_file, model_name, system_message="", max_tokens=4000, temperature=0.7, top_p=0.9):
    system_prefix = """๋„ˆ๋Š” ํŒŒ์ผ ๋ถ„์„ ์ „๋ฌธ๊ฐ€์ž…๋‹ˆ๋‹ค. ์—…๋กœ๋“œ๋œ ํŒŒ์ผ์˜ ๋‚ด์šฉ์„ ๊นŠ์ด ์žˆ๊ฒŒ ๋ถ„์„ํ•˜์—ฌ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ด€์ ์—์„œ ์„ค๋ช…ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค:

1. ํŒŒ์ผ์˜ ์ „๋ฐ˜์ ์ธ ๊ตฌ์กฐ์™€ ๊ตฌ์„ฑ
2. ์ฃผ์š” ๋‚ด์šฉ๊ณผ ํŒจํ„ด ๋ถ„์„
3. ๋ฐ์ดํ„ฐ์˜ ํŠน์ง•๊ณผ ์˜๋ฏธ
   - ๋ฐ์ดํ„ฐ์…‹์˜ ๊ฒฝ์šฐ: ์ปฌ๋Ÿผ์˜ ์˜๋ฏธ, ๋ฐ์ดํ„ฐ ํƒ€์ž…, ๊ฐ’์˜ ๋ถ„ํฌ
   - ํ…์ŠคํŠธ/์ฝ”๋“œ์˜ ๊ฒฝ์šฐ: ๊ตฌ์กฐ์  ํŠน์ง•, ์ฃผ์š” ํŒจํ„ด
4. ์ž ์žฌ์  ํ™œ์šฉ ๋ฐฉ์•ˆ
5. ๋ฐ์ดํ„ฐ ํ’ˆ์งˆ ๋ฐ ๊ฐœ์„  ๊ฐ€๋Šฅํ•œ ๋ถ€๋ถ„

์ „๋ฌธ๊ฐ€์  ๊ด€์ ์—์„œ ์ƒ์„ธํ•˜๊ณ  ๊ตฌ์กฐ์ ์ธ ๋ถ„์„์„ ์ œ๊ณตํ•˜๋˜, ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ์„ค๋ช…ํ•˜์„ธ์š”. ๋ถ„์„ ๊ฒฐ๊ณผ๋Š” Markdown ํ˜•์‹์œผ๋กœ ์ž‘์„ฑํ•˜๊ณ , ๊ฐ€๋Šฅํ•œ ํ•œ ๊ตฌ์ฒด์ ์ธ ์˜ˆ์‹œ๋ฅผ ํฌํ•จํ•˜์„ธ์š”."""

    if uploaded_file:
        content, file_type = read_uploaded_file(uploaded_file)
        if file_type == "error":
            yield "", history + [[message, content]]
            return
        
        # ํŒŒ์ผ ๋‚ด์šฉ ๋ถ„์„ ๋ฐ ๊ตฌ์กฐ์  ์š”์•ฝ
        file_summary = analyze_file_content(content, file_type)
        
        if file_type in ['parquet', 'csv']:
            system_message += f"\n\nํŒŒ์ผ ๋‚ด์šฉ:\n```markdown\n{content}\n```"
        else:
            system_message += f"\n\nํŒŒ์ผ ๋‚ด์šฉ:\n```\n{content}\n```"
            
        if message == "ํŒŒ์ผ ๋ถ„์„์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.":
            message = f"""[๊ตฌ์กฐ ๋ถ„์„] {file_summary}

๋‹ค์Œ ๊ด€์ ์—์„œ ์ƒ์„ธ ๋ถ„์„์„ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”:
1. ํŒŒ์ผ์˜ ์ „๋ฐ˜์ ์ธ ๊ตฌ์กฐ์™€ ํ˜•์‹
2. ์ฃผ์š” ๋‚ด์šฉ ๋ฐ ๊ตฌ์„ฑ์š”์†Œ ๋ถ„์„
3. ๋ฐ์ดํ„ฐ/๋‚ด์šฉ์˜ ํŠน์ง•๊ณผ ํŒจํ„ด
4. ํ’ˆ์งˆ ๋ฐ ์™„์„ฑ๋„ ํ‰๊ฐ€
5. ๊ฐœ์„  ๊ฐ€๋Šฅํ•œ ๋ถ€๋ถ„ ์ œ์•ˆ
6. ์‹ค์ œ ํ™œ์šฉ ๋ฐฉ์•ˆ ๋ฐ ์ถ”์ฒœ์‚ฌํ•ญ"""

    messages = [{"role": "system", "content": f"{system_prefix} {system_message}"}]
    messages.extend(format_history(history))
    messages.append({"role": "user", "content": message})

    try:
        client = get_client(model_name)
        partial_message = ""
        
        for msg in client.chat_completion(
            messages,
            max_tokens=max_tokens,
            stream=True,
            temperature=temperature,
            top_p=top_p,
        ):
            token = msg.choices[0].delta.get('content', None)
            if token:
                partial_message += token
                yield "", history + [[message, partial_message]]
                
    except Exception as e:
        error_msg = f"์ถ”๋ก  ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"
        yield "", history + [[message, error_msg]]

css = """
footer {visibility: hidden}
"""

with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css=css) as demo:
    with gr.Row():
        with gr.Column(scale=2):
            chatbot = gr.Chatbot(height=600)
            msg = gr.Textbox(
                label="๋ฉ”์‹œ์ง€๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”",
                show_label=False,
                placeholder="๋ฉ”์‹œ์ง€๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”...",
                container=False
            )
            clear = gr.ClearButton([msg, chatbot])
        
        with gr.Column(scale=1):
            model_name = gr.Radio(
                choices=list(LLM_MODELS.keys()),
                value="Default",
                label="LLM ๋ชจ๋ธ ์„ ํƒ",
                info="์‚ฌ์šฉํ•  LLM ๋ชจ๋ธ์„ ์„ ํƒํ•˜์„ธ์š”"
            )
            
            file_upload = gr.File(
                label="ํŒŒ์ผ ์—…๋กœ๋“œ (ํ…์ŠคํŠธ, ์ฝ”๋“œ, CSV, Parquet ํŒŒ์ผ)",
                file_types=["text", ".csv", ".parquet"],
                type="filepath"
            )
            
            with gr.Accordion("๊ณ ๊ธ‰ ์„ค์ •", open=False):
                system_message = gr.Textbox(label="System Message", value="")
                max_tokens = gr.Slider(minimum=1, maximum=8000, value=4000, label="Max Tokens")
                temperature = gr.Slider(minimum=0, maximum=1, value=0.7, label="Temperature")
                top_p = gr.Slider(minimum=0, maximum=1, value=0.9, label="Top P")

    # ์ด๋ฒคํŠธ ๋ฐ”์ธ๋”ฉ
    msg.submit(
        chat,
        inputs=[msg, chatbot, file_upload, model_name, system_message, max_tokens, temperature, top_p],
        outputs=[msg, chatbot],
        queue=True
    ).then(
        lambda: gr.update(interactive=True),
        None,
        [msg]
    )

    # ํŒŒ์ผ ์—…๋กœ๋“œ ์‹œ ์ž๋™ ๋ถ„์„
    file_upload.change(
        chat,
        inputs=[gr.Textbox(value="ํŒŒ์ผ ๋ถ„์„์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค."), chatbot, file_upload, model_name, system_message, max_tokens, temperature, top_p],
        outputs=[msg, chatbot],
        queue=True
    )

    # ์˜ˆ์ œ ์ถ”๊ฐ€
    gr.Examples(
        examples=[
            ["ํŒŒ์ผ์˜ ์ „๋ฐ˜์ ์ธ ๊ตฌ์กฐ์™€ ํŠน์ง•์„ ์ž์„ธํžˆ ์„ค๋ช…ํ•ด์ฃผ์„ธ์š”."],
            ["์ด ํŒŒ์ผ์˜ ์ฃผ์š” ํŒจํ„ด๊ณผ ํŠน์ง•์„ ๋ถ„์„ํ•ด์ฃผ์„ธ์š”."],
            ["ํŒŒ์ผ์˜ ํ’ˆ์งˆ๊ณผ ๊ฐœ์„  ๊ฐ€๋Šฅํ•œ ๋ถ€๋ถ„์„ ํ‰๊ฐ€ํ•ด์ฃผ์„ธ์š”."],
            ["์ด ํŒŒ์ผ์„ ์‹ค์ œ๋กœ ์–ด๋–ป๊ฒŒ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ์„๊นŒ์š”?"],
            ["ํŒŒ์ผ์˜ ์ฃผ์š” ๋‚ด์šฉ์„ ์š”์•ฝํ•˜๊ณ  ํ•ต์‹ฌ ์ธ์‚ฌ์ดํŠธ๋ฅผ ๋„์ถœํ•ด์ฃผ์„ธ์š”."],
            ["์ด์ „ ๋ถ„์„์„ ์ด์–ด์„œ ๋” ์ž์„ธํžˆ ์„ค๋ช…ํ•ด์ฃผ์„ธ์š”."],
        ],
        inputs=msg,
    )

if __name__ == "__main__":
    demo.launch()