sum-csv / app.py
fantos's picture
Update app.py
162720f verified
import gradio as gr
import pandas as pd
import os
import tempfile
import chardet
def detect_encoding(file_path):
"""
파일의 인코딩을 κ°μ§€ν•˜λŠ” ν•¨μˆ˜
"""
with open(file_path, 'rb') as f:
result = chardet.detect(f.read())
return result['encoding']
def merge_csv_files(files):
"""
μ—¬λŸ¬ CSV νŒŒμΌμ„ ν•˜λ‚˜λ‘œ λ³‘ν•©ν•˜λŠ” ν•¨μˆ˜
Args:
files: μ—…λ‘œλ“œλœ CSV 파일 λͺ©λ‘
Returns:
λ³‘ν•©λœ CSV 파일 κ²½λ‘œμ™€ μƒνƒœ λ©”μ‹œμ§€
"""
if not files or len(files) == 0:
return None, "파일이 μ—…λ‘œλ“œλ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€."
if len(files) > 30:
return None, "μ΅œλŒ€ 30개 νŒŒμΌκΉŒμ§€λ§Œ 병합 κ°€λŠ₯ν•©λ‹ˆλ‹€."
try:
# λͺ¨λ“  νŒŒμΌμ„ DataFrame 리슀트둜 읽기
dataframes = []
for file in files:
# 파일의 인코딩 감지
encoding = detect_encoding(file.name)
try:
df = pd.read_csv(file.name, encoding=encoding)
except UnicodeDecodeError:
# κ°μ§€λœ 인코딩이 μ‹€νŒ¨ν•˜λ©΄ λ‹€λ₯Έ 인코딩 μ‹œλ„
encodings_to_try = ['cp949', 'euc-kr', 'latin1', 'ISO-8859-1']
for enc in encodings_to_try:
try:
df = pd.read_csv(file.name, encoding=enc)
break
except UnicodeDecodeError:
continue
else:
return None, f"파일 '{os.path.basename(file.name)}'의 인코딩을 κ²°μ •ν•  수 μ—†μŠ΅λ‹ˆλ‹€."
dataframes.append(df)
# λͺ¨λ“  DataFrame 병합
if dataframes:
merged_df = pd.concat(dataframes, ignore_index=True)
# μž„μ‹œ νŒŒμΌμ— μ €μž₯
with tempfile.NamedTemporaryFile(delete=False, suffix='.csv') as tmp:
output_path = tmp.name
# λ³‘ν•©λœ 데이터λ₯Ό Excel ν˜Έν™˜ ν˜•μ‹(UTF-8 with BOM)으둜 μ €μž₯
merged_df.to_csv(output_path, index=False, encoding='utf-8-sig')
return output_path, f"{len(files)}개 파일이 μ„±κ³΅μ μœΌλ‘œ λ³‘ν•©λ˜μ—ˆμŠ΅λ‹ˆλ‹€. Excelμ—μ„œ μ—΄ λ•Œ UTF-8 μΈμ½”λ”©μœΌλ‘œ μ—΄μ–΄μ£Όμ„Έμš”."
else:
return None, "병합할 데이터가 μ—†μŠ΅λ‹ˆλ‹€."
except Exception as e:
return None, f"였λ₯˜ λ°œμƒ: {str(e)}"
# Gradio μΈν„°νŽ˜μ΄μŠ€ μ„€μ •
with gr.Blocks(title="CSV 파일 병합기") as app:
gr.Markdown("# CSV 파일 병합기")
gr.Markdown("μ΅œλŒ€ 30개의 CSV νŒŒμΌμ„ ν•˜λ‚˜λ‘œ λ³‘ν•©ν•©λ‹ˆλ‹€.")
with gr.Row():
with gr.Column():
input_files = gr.File(
file_count="multiple",
label="CSV 파일 μ—…λ‘œλ“œ (μ΅œλŒ€ 30개)"
)
with gr.Column():
merge_button = gr.Button("파일 λ³‘ν•©ν•˜κΈ°")
output_file = gr.File(label="λ³‘ν•©λœ CSV")
status = gr.Textbox(label="μƒνƒœ")
merge_button.click(
fn=merge_csv_files,
inputs=[input_files],
outputs=[output_file, status]
)
# μ•± μ‹€ν–‰
if __name__ == "__main__":
app.launch()