blueellia commited on
Commit
e95ab0c
·
verified ·
1 Parent(s): 20bbcd1

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -219
app.py DELETED
@@ -1,219 +0,0 @@
1
- import io, re, time, random, requests, pickle, gc
2
- import pandas as pd
3
- import streamlit as st
4
- from concurrent.futures import ThreadPoolExecutor, as_completed
5
- from openpyxl import Workbook
6
- from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
7
- from openpyxl.utils import get_column_letter
8
-
9
- st.set_page_config(page_title="사업장 주소·전화번호 보완", page_icon="📋", layout="centered")
10
- st.markdown("""<style>
11
- #MainMenu,footer,header{visibility:hidden}
12
- .block-container{max-width:660px!important;padding:2rem 1rem!important}
13
- div.stButton>button{background:#3b82f6!important;color:#fff!important;border:none!important;border-radius:8px!important;font-weight:600!important;width:100%!important}
14
- div.stDownloadButton>button{background:#10b981!important;color:#fff!important;border:none!important;border-radius:8px!important;font-weight:600!important;width:100%!important}
15
- </style>""", unsafe_allow_html=True)
16
-
17
- import os
18
-
19
- FSC_KEY = os.getenv("FSC_KEY")
20
- KAKAO_KEY = os.getenv("KAKAO_KEY")
21
-
22
- NAV_HDR = {"User-Agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15","Referer":"https://map.naver.com/","Accept-Language":"ko-KR,ko;q=0.9"}
23
- WORKERS = 5
24
-
25
- def kakao_keyword(name, addr):
26
- try:
27
- r = requests.get("https://dapi.kakao.com/v2/local/search/keyword.json",
28
- headers={"Authorization":f"KakaoAK {KAKAO_KEY}"},
29
- params={"query":f"{name} {addr[:20]}","size":5}, timeout=5)
30
- docs = r.json().get("documents",[])
31
- m = next((d for d in docs if name[:4] in d.get("place_name","")), None)
32
- return m or (docs[0] if docs else None)
33
- except: return None
34
-
35
- def fsc_info(name, biz_no):
36
- try:
37
- r = requests.get(
38
- "https://apis.data.go.kr/1160100/service/GetCorpBasicInfoService_V2/getCorpOutline_V2",
39
- params={"serviceKey":FSC_KEY,"pageNo":1,"numOfRows":5,"resultType":"json","corpNm":name}, timeout=5)
40
- items = r.json().get("response",{}).get("body",{}).get("items",{}).get("item",[])
41
- if not items: return None
42
- if isinstance(items, dict): items = [items]
43
- bc = re.sub(r'\D','',str(biz_no))
44
- m = next((i for i in items if re.sub(r'\D','',str(i.get("bzno",""))) == bc), items[0])
45
- return {"phone":m.get("enpTlno",""), "addr":m.get("enpBsadr","") or m.get("enpDtadr","")}
46
- except: return None
47
-
48
- def naver_phone(name, addr):
49
- clean = re.sub(r'주식회사|유한회사|\(주\)|\(유\)|[(){}\[\]]','',name).strip()
50
- gu = re.search(r'[\w]+구', addr); gu = gu.group() if gu else ""
51
- try:
52
- r = requests.get("https://m.map.naver.com/search2/search.nhn",
53
- headers=NAV_HDR, params={"query":f"{clean} {gu}","type":"all"}, timeout=8)
54
- if r.status_code == 429: time.sleep(30); return naver_phone(name, addr)
55
- for pat in [r'tel:(0\d{1,2}-?\d{3,4}-?\d{4})',r'(?<!\d)(0\d{1,2}-\d{3,4}-\d{4})(?!\d)']:
56
- f = re.findall(pat, r.text)
57
- if f: return f[0]
58
- except: pass
59
- return ""
60
-
61
- def process_one(row_data):
62
- idx, name, addr, biz_no, is_corp = row_data
63
- phone=""; full_addr=addr; lat=None; lon=None
64
- if is_corp:
65
- info = fsc_info(name, biz_no)
66
- if info:
67
- phone = info.get("phone","")
68
- if info.get("addr"): full_addr = info["addr"]
69
- time.sleep(0.1)
70
- kk = kakao_keyword(name, addr)
71
- if kk:
72
- if not phone: phone = kk.get("phone","")
73
- lat = float(kk.get("y") or 0) or None
74
- lon = float(kk.get("x") or 0) or None
75
- road = kk.get("road_address_name","")
76
- if road: full_addr = road
77
- if not phone: phone = naver_phone(name, full_addr)
78
- return idx, {"phone":phone, "addr":full_addr, "lat":lat, "lon":lon}
79
-
80
- def make_excel(df):
81
- wb = Workbook(); ws = wb.active; ws.title = "보완완료"
82
- def thin():
83
- s = Side(style="thin",color="D0D0D0")
84
- return Border(left=s,right=s,top=s,bottom=s)
85
- hdrs = list(df.columns)
86
- widths = {"사업장명":26,"업종":18,"법인여부":8,"주소":42,"전화번호":14,"가입자수":8,"당월고지금액":14,"위도":12,"경도":12}
87
- CENTER = {"법인여부","가입자수","당월고지금액","위도","경도","전화번호"}
88
- for c,h in enumerate(hdrs,1):
89
- cell = ws.cell(1,c,h)
90
- cell.fill = PatternFill("solid",start_color="1F3864")
91
- cell.font = Font(name="Arial",size=10,bold=True,color="FFFFFF")
92
- cell.alignment = Alignment(horizontal="center",vertical="center")
93
- cell.border = thin()
94
- ws.column_dimensions[get_column_letter(c)].width = widths.get(h,12)
95
- ws.row_dimensions[1].height = 18
96
- ws.freeze_panes = "A2"
97
- ws.auto_filter.ref = f"A1:{get_column_letter(len(hdrs))}1"
98
- for ri,row in enumerate(df.itertuples(index=False),2):
99
- for ci,(h,v) in enumerate(zip(hdrs,row),1):
100
- if pd.isna(v) or str(v) in ("nan","None"): v=""
101
- cell = ws.cell(ri,ci,v)
102
- cell.font = Font(name="Arial",size=10)
103
- cell.border = thin()
104
- cell.fill = PatternFill("solid",start_color="FFFFFF" if ri%2==0 else "F8FAFC")
105
- cell.alignment = Alignment(horizontal="center" if h in CENTER else "left",vertical="center")
106
- buf = io.BytesIO(); wb.save(buf); return buf.getvalue()
107
-
108
- # ── UI ──────────────────────────────────────────────────
109
- st.title("📋 사업장 주소·전화번호 보완")
110
- st.caption("대시보드에서 다운로드한 지역 파일을 업로드하세요")
111
- st.divider()
112
-
113
- uploaded = st.file_uploader("파일 선택 (국민연금_XX시_XX구_사업장.xlsx)", type=["xlsx"])
114
-
115
- if uploaded:
116
- # 필요한 컬럼만 읽기 (메모리 절약)
117
- df = pd.read_excel(uploaded)
118
- df.columns = [c.strip() for c in df.columns]
119
- gc.collect() # 메모리 정리
120
-
121
- name_col = next((c for c in df.columns if "사업장명" in c or "상호" in c), None)
122
- addr_col = next((c for c in df.columns if "주소" in c or "도로명" in c), None)
123
- biz_col = next((c for c in df.columns if "사업자" in c and "번호" in c), None)
124
- type_col = next((c for c in df.columns if "형태" in c or "법인" in c), None)
125
- emp_col = next((c for c in df.columns if "가입자" in c), None)
126
- pay_col = next((c for c in df.columns if "고지" in c), None)
127
- ind_col = next((c for c in df.columns if "업종" in c), None)
128
-
129
- for col in ["전화번호"]:
130
- if col not in df.columns: df[col] = ""
131
- else: df[col] = df[col].fillna("").astype(str).replace("nan","")
132
- for col in ["위도","경도"]:
133
- if col not in df.columns: df[col] = None
134
- else: df[col] = pd.to_numeric(df[col], errors="coerce")
135
-
136
- total = len(df)
137
- fname = uploaded.name.replace(".xlsx","")
138
- corp = int((df[type_col].astype(str).str.contains("법인|^1$")).sum()) if type_col else 0
139
-
140
- st.success(f"✅ **{fname}** — {total:,}개 사업장 (법인 {corp:,}개)")
141
- est = max(1, int(total * 0.3 / WORKERS / 60))
142
- st.caption(f"⏱ 예상 소요: 약 {est}분")
143
-
144
- CHUNK = 1000
145
-
146
- # 세션 초기화 (파일 바뀌면 리셋)
147
- if "df_work" not in st.session_state or st.session_state.get("work_fname") != fname:
148
- st.session_state["df_work"] = df.copy()
149
- st.session_state["work_fname"] = fname
150
- st.session_state["work_done"] = 0
151
- st.session_state["phone_ok"] = 0
152
- st.session_state["coord_ok"] = 0
153
- st.session_state["finished"] = False
154
-
155
- wdf = st.session_state["df_work"]
156
- done_cnt = st.session_state["work_done"]
157
- finished = st.session_state["finished"]
158
-
159
- # 진행바
160
- pct = done_cnt / total if total > 0 else 0
161
- st.progress(pct, text=f"{done_cnt:,}/{total:,}개 완료 | 📞{st.session_state['phone_ok']} 📍{st.session_state['coord_ok']}")
162
-
163
- def get_out(wdf):
164
- col_map = {}
165
- if name_col: col_map[name_col]="사업장명"
166
- if type_col: col_map[type_col]="법인여부"
167
- if addr_col: col_map[addr_col]="주소"
168
- col_map["전화번호"]="전화번호"
169
- if emp_col: col_map[emp_col]="가입자수"
170
- if pay_col: col_map[pay_col]="당월고지금액"
171
- if ind_col: col_map[ind_col]="업종"
172
- col_map["위도"]="위도"; col_map["경도"]="경도"
173
- out = wdf[[c for c in col_map if c in wdf.columns]].rename(columns=col_map)
174
- return out[out["전화번호"].notna() & (out["전화번호"]!="") &
175
- out["주소"].notna() & (out["주소"]!="")].reset_index(drop=True)
176
-
177
- if finished:
178
- out = get_out(wdf)
179
- st.success(f"✅ 완료! 📞 {st.session_state['phone_ok']:,}개 | 📍 {st.session_state['coord_ok']:,}개 | 최종 {len(out):,}개")
180
- st.balloons()
181
- st.download_button("⬇️ 보완 완료 엑셀 다운로드",
182
- make_excel(out), fname+"_보완완료.xlsx",
183
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
184
- use_container_width=True)
185
-
186
- elif done_cnt >= total:
187
- st.session_state["finished"] = True
188
- st.rerun()
189
-
190
- else:
191
- btn_label = "🚀 보완 시작" if done_cnt == 0 else f"▶️ 계속 ({done_cnt:,}/{total:,})"
192
- if st.button(btn_label, type="primary", use_container_width=True):
193
- chunk_idx = list(wdf.index[done_cnt:done_cnt+CHUNK])
194
- prog = st.progress(0, text=f"처리 중... (0/{len(chunk_idx)})")
195
- for i, idx in enumerate(chunk_idx):
196
- row = wdf.loc[idx]
197
- t = (idx,
198
- str(row.get(name_col,"")) if name_col else "",
199
- str(row.get(addr_col,"")) if addr_col else "",
200
- str(row.get(biz_col,"")) if biz_col else "",
201
- str(row.get(type_col,"")) in ["법인","1"] if type_col else False)
202
- try:
203
- _, res = process_one(t)
204
- wdf.loc[idx,"전화번호"] = str(res["phone"])
205
- wdf.loc[idx,"위도"] = res["lat"]
206
- wdf.loc[idx,"경도"] = res["lon"]
207
- if addr_col and res["addr"]: wdf.loc[idx,addr_col] = res["addr"]
208
- if res["phone"]: st.session_state["phone_ok"] += 1
209
- if res["lat"]: st.session_state["coord_ok"] += 1
210
- except: pass
211
- prog.progress((i+1)/len(chunk_idx), text=f"처리 중... ({i+1}/{len(chunk_idx)})")
212
-
213
- st.session_state["df_work"] = wdf
214
- st.session_state["work_done"] = done_cnt + len(chunk_idx)
215
- prog.empty()
216
- st.rerun()
217
-
218
- if done_cnt > 0:
219
- st.caption(f"새로고침 되어도 {done_cnt:,}개 저장됨. 버튼 눌러 계속하세요.")