Download app.py from Sangwon78/example12: direct link, hf CLI and curl.
- Browser
- Download file 4.73 kB
-
https://huggingface.co/spaces/Sangwon78/example12/resolve/main/app.py
- Command line
-
hf download hf://spaces/Sangwon78/example12/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Sangwon78/example12/resolve/main/app.py
4.73 kB
| import gradio as gr | |
| import pandas as pd | |
| import re | |
| import io | |
| import openpyxl | |
| from openpyxl import Workbook | |
| import tempfile | |
| def remove_special_characters(text: str): | |
| return re.sub(r"[^\w\sㄱ-힣]", "", text) | |
| def extract_keywords(text_list, top_n=3): | |
| combined_text = " ".join(text_list) | |
| combined_text = remove_special_characters(combined_text) | |
| words = combined_text.split() | |
| freq = {} | |
| for w in words: | |
| freq[w] = freq.get(w, 0) + 1 | |
| sorted_words = sorted(freq.items(), key=lambda x: x[1], reverse=True) | |
| keywords = [w[0] for w in sorted_words[:top_n]] | |
| return ", ".join(keywords) | |
| def process_excel(file): | |
| # 엑셀 읽기 | |
| df = pd.read_excel(file.name, header=None) | |
| df.columns = ["고객ID", "리뷰날짜", "리뷰내용", "리뷰점수"] + list(df.columns[4:]) | |
| df["리뷰내용"] = df["리뷰내용"].astype(str).apply(remove_special_characters) | |
| df_use = df[["고객ID", "리뷰날짜", "리뷰내용", "리뷰점수"]] | |
| all_ids = df_use["고객ID"].dropna().unique() | |
| combined_id = ", ".join(map(str, all_ids)) | |
| all_dates = df_use["리뷰날짜"].dropna().unique() | |
| combined_dates = ", ".join(map(str, sorted(all_dates))) | |
| keywords = extract_keywords(df_use["리뷰내용"].tolist()) | |
| df_use["리뷰점수"] = pd.to_numeric(df_use["리뷰점수"], errors='coerce') | |
| score_mean = df_use["리뷰점수"].mean() | |
| wb = Workbook() | |
| ws = wb.active | |
| ws["A1"] = "고객ID" | |
| ws["B1"] = "리뷰날짜" | |
| ws["C1"] = "리뷰내용" | |
| ws["D1"] = "리뷰점수" | |
| for i, row in enumerate(df_use.values, start=2): | |
| ws.cell(row=i, column=1, value=row[0]) | |
| ws.cell(row=i, column=2, value=row[1]) | |
| ws.cell(row=i, column=3, value=row[2]) | |
| ws.cell(row=i, column=4, value=row[3]) | |
| ws["A8"] = combined_id | |
| ws["B8"] = combined_dates | |
| ws["C8"] = keywords | |
| ws["D8"] = score_mean | |
| # 메모리에 저장 | |
| output = io.BytesIO() | |
| wb.save(output) | |
| output.seek(0) | |
| # 여기서 dict로 반환하지 않고, 임시 파일에 씁니다. | |
| with tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx") as tmp: | |
| tmp.write(output.getvalue()) | |
| tmp_path = tmp.name | |
| return df_use, tmp_path | |
| def create_app(): | |
| with gr.Blocks() as demo: | |
| gr.Markdown("## 엑셀 파일 업로드 데모") | |
| file_input = gr.File(label="엑셀 파일 업로드", file_types=[".xlsx"]) | |
| generate_button = gr.Button("데이터 추출 및 결과 생성") | |
| output_df = gr.DataFrame(label="처리된 결과 미리보기") | |
| download_file = gr.File(label="결과 엑셀 다운로드") | |
| def on_click(file): | |
| df_preview, tmp_path = process_excel(file) | |
| # 첫 번째 출력: DataFrame 미리보기 | |
| # 두 번째 출력: 실제 파일 경로(str)를 반환 | |
| return df_preview, tmp_path | |
| generate_button.click( | |
| fn=on_click, | |
| inputs=file_input, | |
| outputs=[output_df, download_file] | |
| ) | |
| ############################### | |
| # 여기서부터 새로 추가된 기능 # | |
| ############################### | |
| gr.Markdown("## 가맹점명 검색 기능(추가)") | |
| text_input = gr.Textbox(label="가맹점명 입력") | |
| text_output = gr.Textbox(label="검색 결과", lines=4) | |
| def search_data(file, store_name): | |
| if not file: | |
| return "엑셀 파일을 업로드 해주세요." | |
| # 여기서는 첫 행을 헤더로 가정합니다 (A1=가맹점명, B1=주소, ...) | |
| df2 = pd.read_excel(file.name) | |
| # A열(첫 번째 컬럼)에서 store_name과 같은 행을 찾음 | |
| row = df2[df2[df2.columns[0]] == store_name] | |
| if row.empty: | |
| return "해당 가맹점명을 찾을 수 없습니다." | |
| # B, C, D 열 데이터 추출 | |
| address = str(row[df2.columns[1]].values[0]) | |
| biz_type = str(row[df2.columns[2]].values[0]) | |
| data_date = str(row[df2.columns[3]].values[0]) | |
| result_text = ( | |
| f"가맹점명: {store_name}\n" | |
| f"주소: {address}\n" | |
| f"업종명: {biz_type}\n" | |
| f"데이터일자: {data_date}" | |
| ) | |
| return result_text | |
| search_button = gr.Button("가맹점명 검색") | |
| # 'file_input'과 'text_input'을 받아서 'search_data'로 처리 후 'text_output'에 표시 | |
| search_button.click( | |
| fn=search_data, | |
| inputs=[file_input, text_input], | |
| outputs=text_output | |
| ) | |
| return demo | |
| if __name__ == "__main__": | |
| app = create_app() | |
| app.launch() | |