|
import gradio as gr |
|
from huggingface_hub import InferenceClient |
|
import os |
|
import pandas as pd |
|
import pdfplumber |
|
from typing import List, Tuple |
|
|
|
|
|
LLM_MODELS = { |
|
"Cohere c4ai-crp-08-2024": "CohereForAI/c4ai-command-r-plus-08-2024", |
|
"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') |
|
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}"}] |
|
|
|
|
|
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 π") |
|
|
|
|
|
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] |
|
) |
|
|
|
|
|
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() |