Spaces:
Building
Building
import gradio as gr | |
from huggingface_hub import InferenceClient | |
import os | |
import pandas as pd | |
from typing import List, Tuple | |
# LLM λͺ¨λΈ μ μ | |
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): | |
"""νμΌ λ΄μ©μ λΆμνμ¬ κ΅¬μ‘°μ μμ½μ λ°ν""" | |
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() |