File size: 11,136 Bytes
f9b9d56
83ee74c
574f73e
705c5b5
a352e50
83ee74c
f9b9d56
e4d39de
ad9db85
e4d39de
a352e50
79e0b8a
 
ad9db85
 
 
 
f9b9d56
2af89cf
e4d39de
a352e50
da20c1b
a352e50
 
 
 
 
 
 
 
99d94e0
a352e50
e4d39de
 
da20c1b
e4d39de
2af89cf
 
 
 
 
da20c1b
2af89cf
 
da20c1b
e4d39de
da20c1b
 
 
e4d39de
2af89cf
705c5b5
0997082
2af89cf
705c5b5
99d94e0
 
a352e50
 
 
 
 
2af89cf
a352e50
99d94e0
a352e50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
705c5b5
521288b
 
 
 
 
a352e50
521288b
 
e4d39de
705c5b5
e4d39de
0997082
d57197f
 
 
 
 
 
 
 
ad9db85
e4d39de
a352e50
 
 
 
 
 
 
 
705c5b5
7ffca43
2af89cf
 
a352e50
2af89cf
 
7ffca43
a352e50
e4d39de
7ffca43
e4d39de
7ffca43
e4d39de
a352e50
 
 
 
 
 
 
 
705c5b5
 
a352e50
 
 
 
 
 
 
 
 
 
 
0997082
705c5b5
0997082
ad9db85
da20c1b
a352e50
da20c1b
ad9db85
f2c0975
 
83ee74c
0997082
 
83ee74c
7ffca43
705c5b5
da20c1b
a352e50
 
 
 
 
da20c1b
0997082
e4d39de
a352e50
 
 
 
 
705c5b5
7b3fa19
7ffca43
7b3fa19
 
0dfd273
 
e4d39de
 
 
 
 
 
 
 
 
 
63c5e29
 
0dfd273
 
a352e50
 
0dfd273
7ffca43
a352e50
7ffca43
a352e50
7ffca43
 
a352e50
63c5e29
 
2af89cf
ad9db85
e4d39de
a352e50
 
ad9db85
 
a352e50
7ffca43
a352e50
 
d57197f
7ffca43
63c5e29
a352e50
 
 
 
e4d39de
63c5e29
e4d39de
7ffca43
 
ad9db85
da20c1b
 
 
 
 
 
7ffca43
 
a352e50
0dfd273
 
 
 
 
 
 
 
 
 
e4d39de
7ffca43
 
a352e50
da20c1b
 
7ffca43
63c5e29
e4d39de
63c5e29
 
a352e50
 
 
 
 
 
63c5e29
 
 
f9b9d56
 
0dfd273
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
import gradio as gr
from huggingface_hub import InferenceClient
import os
import pandas as pd
import pdfplumber
from typing import List, Tuple

# LLM Models Definition
LLM_MODELS = {
    "Cohere c4ai-crp-08-2024": "CohereForAI/c4ai-command-r-plus-08-2024",  # Default
    "Meta Llama3.3-70B": "meta-llama/Llama-3.3-70B-Instruct",
    "Mistral Nemo 2407": "mistralai/Mistral-Nemo-Instruct-2407",
    "Alibaba Qwen QwQ-32B": "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):
    """Analyze file content and return structural summary"""
    if file_type in ['parquet', 'csv', 'pdf']:
        try:
            if file_type == 'pdf':
                with pdfplumber.open(content) as pdf:
                    pages = pdf.pages
                    lines = []
                    for page in pages:
                        lines.extend(page.extract_text().split('\n'))
            else:
                lines = content.split('\n')
            header = lines[0]
            columns = len(header.split('|')) - 1
            rows = len(lines) - 3
            return f"πŸ“Š Dataset Structure: {columns} columns, {rows} data samples"
        except:
            return "❌ Dataset structure analysis failed"
    
    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"πŸ’» Code Structure: {total_lines} lines (Functions: {functions}, Classes: {classes}, Imports: {imports})"
    
    paragraphs = content.count('\n\n') + 1
    words = len(content.split())
    return f"πŸ“ Document Structure: {total_lines} lines, {paragraphs} paragraphs, ~{words} words"

def read_uploaded_file(file):
    if file is None:
        return "", ""
    try:
        file_ext = os.path.splitext(file.name)[1].lower()
        
        if file_ext in ['.parquet', '.pdf']:
            if file_ext == '.parquet':
                df = pd.read_parquet(file.name, engine='pyarrow')
            else:
                df = pd.read_csv(file.name, encoding='utf-8', engine='python')  # Use 'python' engine to handle PDF files
            content = df.head(10).to_markdown(index=False)
            return content, file_ext
        elif file_ext == '.csv':
            df = pd.read_csv(file.name)
            content = f"πŸ“Š Data Preview:\n{df.head(10).to_markdown(index=False)}\n\n"
            content += f"\nπŸ“ˆ Data Information:\n"
            content += f"- Total Rows: {len(df)}\n"
            content += f"- Total Columns: {len(df.columns)}\n"
            content += f"- Column List: {', '.join(df.columns)}\n"
            content += f"\nπŸ“‹ Column Data Types:\n"
            for col, dtype in df.dtypes.items():
                content += f"- {col}: {dtype}\n"
            null_counts = df.isnull().sum()
            if null_counts.any():
                content += f"\n⚠️ Missing Values:\n"
                for col, null_count in null_counts[null_counts > 0].items():
                    content += f"- {col}: {null_count} missing\n"
            return content, file_ext
        else:
            encodings = ['utf-8', 'cp949', 'euc-kr', 'latin1']
            for encoding in encodings:
                try:
                    with open(file.name, 'r', encoding=encoding) as f:
                        content = f.read()
                    return content, file_ext
                except UnicodeDecodeError:
                    continue
            raise UnicodeDecodeError(f"❌ Unable to read file with supported encodings ({', '.join(encodings)})")
    except Exception as e:
        return f"❌ Error reading file: {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 = """You are a file analysis expert. Analyze the uploaded file in depth from the following perspectives:
   1. πŸ“‹ Overall structure and composition
   2. πŸ“Š Key content and pattern analysis
   3. πŸ“ˆ Data characteristics and meaning
      - For datasets: Column meanings, data types, value distributions
      - For text/code: Structural features, main patterns
   4. πŸ’‘ Potential applications
   5. ✨ Data quality and areas for improvement
   Provide detailed and structured analysis from an expert perspective, but explain in an easy-to-understand way. Format the analysis results in Markdown and include specific examples where possible."""

    if uploaded_file:
        content, file_type = read_uploaded_file(uploaded_file)
        if file_type == "error":
            return "", [{"role": "user", "content": message}, {"role": "assistant", "content": content}]
        
        file_summary = analyze_file_content(content, file_type)
        
        if file_type in ['parquet', 'csv', 'pdf']:
            system_message += f"\n\nFile Content:\n```markdown\n{content}\n```"
        else:
            system_message += f"\n\nFile Content:\n```\n{content}\n```"
            
        if message == "Starting file analysis...":
            message = f"""[ꡬ쑰 뢄석] {file_summary}
μžμ„Ένžˆ λΆ„μ„ν•΄μ£Όμ„Έμš”:
1. πŸ“‹ 전체 ꡬ쑰 및 ν˜•μ‹
2. πŸ“Š μ£Όμš” λ‚΄μš© 및 κ΅¬μ„±μš”μ†Œ 뢄석
3. πŸ“ˆ 데이터/λ‚΄μš©μ˜ νŠΉμ„± 및 νŒ¨ν„΄
4. ⭐ ν’ˆμ§ˆ 및 μ™„μ „μ„± 평가
5. πŸ’‘ μ œμ•ˆν•˜λŠ” κ°œμ„ μ 
6. 🎯 μ‹€μš©μ μΈ ν™œμš© 및 ꢌμž₯사항"""

    messages = [{"role": "system", "content": f"{system_prefix} {system_message}"}]
    
    # Convert history to message format
    if history is not None:
        for item in history:
            if isinstance(item, dict):
                messages.append(item)
            elif isinstance(item, (list, tuple)) and len(item) == 2:
                messages.append({"role": "user", "content": item[0]})
                if item[1]:
                    messages.append({"role": "assistant", "content": item[1]})

    messages.append({"role": "user", "content": message})

    try:
        client = get_client(model_name)
        partial_message = ""
        current_history = []
        
        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
                current_history = [
                    {"role": "user", "content": message},
                    {"role": "assistant", "content": partial_message}
                ]
                yield "", current_history
                
    except Exception as e:
        error_msg = f"❌ Inference error: {str(e)}"
        error_history = [
            {"role": "user", "content": message},
            {"role": "assistant", "content": error_msg}
        ]
        yield "", error_history

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

# ... (이전 μ½”λ“œ 동일)

with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css=css, title="EveryChat πŸ€–") as demo:
    gr.HTML(
        """
        <div style="text-align: center; max-width: 800px; margin: 0 auto;">
            <h1 style="font-size: 3em; font-weight: 600; margin: 0.5em;">EveryChat πŸ€–</h1>
            <h3 style="font-size: 1.2em; margin: 1em;">Your Intelligent File Analysis Assistant πŸ“Š</h3>
        </div>
        """
    )
    
    with gr.Row():
        with gr.Column(scale=2):
            chatbot = gr.Chatbot(
                height=600, 
                label="μ±„νŒ… μΈν„°νŽ˜μ΄μŠ€ πŸ’¬",
                type="messages"
            )
            msg = gr.Textbox(
                label="λ©”μ‹œμ§€λ₯Ό μž…λ ₯ν•˜μ„Έμš”",
                show_label=False,
                placeholder="μ—…λ‘œλ“œλœ νŒŒμΌμ— λŒ€ν•΄ λ¬Όμ–΄λ³΄μ„Έμš”... πŸ’­",
                container=False
            )
            send = gr.Button("전솑 πŸ“€")
        
        with gr.Column(scale=1):
            model_name = gr.Radio(
                choices=list(LLM_MODELS.keys()),
                value="Cohere c4ai-crp-08-2024",
                label="LLM λͺ¨λΈ 선택 πŸ€–",
                info="μ„ ν˜Έν•˜λŠ” AI λͺ¨λΈμ„ μ„ νƒν•˜μ„Έμš”"
            )
            
            gr.Markdown("### 파일 μ—…λ‘œλ“œ πŸ“\n지원: ν…μŠ€νŠΈ, μ½”λ“œ, CSV, Parquet, PDF 파일")
            file_upload = gr.File(
                label="파일 μ—…λ‘œλ“œ",
                file_types=["text", ".csv", ".parquet", ".pdf"],
                type="filepath"
            )
            
            with gr.Accordion("κ³ κΈ‰ μ„€μ • βš™οΈ", open=False):
                system_message = gr.Textbox(label="μ‹œμŠ€ν…œ λ©”μ‹œμ§€ πŸ“", value="")
                max_tokens = gr.Slider(minimum=1, maximum=8000, value=4000, label="μ΅œλŒ€ 토큰 πŸ“Š")
                temperature = gr.Slider(minimum=0, maximum=1, value=0.7, label="μ˜¨λ„ 🌑️")
                top_p = gr.Slider(minimum=0, maximum=1, value=0.9, label="Top P πŸ“ˆ")

    # Event bindings
    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]
    )

    send.click(
        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]
    )

    # Auto-analysis on file upload
    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
    )

    # Example queries
    gr.Examples(
        examples=[
            ["파일의 전체 ꡬ쑰와 νŠΉμ§•μ„ μžμ„Ένžˆ μ„€λͺ…ν•΄μ£Όμ„Έμš” πŸ“‹"],
            ["파일의 μ£Όμš” νŒ¨ν„΄κ³Ό νŠΉμ„±μ„ λΆ„μ„ν•΄μ£Όμ„Έμš” πŸ“Š"],
            ["파일의 ν’ˆμ§ˆκ³Ό κ°œμ„ μ μ„ ν‰κ°€ν•΄μ£Όμ„Έμš” πŸ’‘"],
            ["이 νŒŒμΌμ„ μ–΄λ–»κ²Œ μ‹€μš©μ μœΌλ‘œ ν™œμš©ν•  수 μžˆμ„κΉŒμš”? 🎯"],
            ["μ£Όμš” λ‚΄μš©μ„ μš”μ•½ν•˜κ³  핡심 톡찰λ ₯을 λ„μΆœν•΄μ£Όμ„Έμš” ✨"],
            ["더 μžμ„Έν•œ 뢄석을 κ³„μ†ν•΄μ£Όμ„Έμš” πŸ“ˆ"],
        ],
        inputs=msg,
    )

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