blueellia commited on
Commit
6b4bfdb
ยท
verified ยท
1 Parent(s): abb12de

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +210 -0
app.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io, re, time, requests, 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.stDownloadButton>button{background:#10b981!important;color:#fff!important;border:none!important;border-radius:8px!important;font-weight:600!important;width:100%!important}
14
+ </style>""", unsafe_allow_html=True)
15
+
16
+ FSC_KEY = "2446da601452d231f1ff77a4c5ac9598896028fb96e8be586bf7f4be58b6231c"
17
+ KAKAO_KEY = "e8eef7246a2cd0f3d2d55af8a806e3ef"
18
+ 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"}
19
+ WORKERS = 20
20
+
21
+ def kakao_keyword(name, addr):
22
+ try:
23
+ r = requests.get("https://dapi.kakao.com/v2/local/search/keyword.json",
24
+ headers={"Authorization":f"KakaoAK {KAKAO_KEY}"},
25
+ params={"query":f"{name} {addr[:20]}","size":5}, timeout=5)
26
+ docs = r.json().get("documents",[])
27
+ gu = re.search(r'[\w]+๊ตฌ|[\w]+๊ตฐ', addr)
28
+ gu = gu.group() if gu else ""
29
+ if gu:
30
+ local = [d for d in docs if gu in d.get("address_name","") or gu in d.get("road_address_name","")]
31
+ if local:
32
+ return next((d for d in local if name[:4] in d.get("place_name","")), local[0])
33
+ return next((d for d in docs if name[:4] in d.get("place_name","")), docs[0] if docs else None)
34
+ except: return None
35
+
36
+ def fsc_info(name, biz_no):
37
+ try:
38
+ r = requests.get(
39
+ "https://apis.data.go.kr/1160100/service/GetCorpBasicInfoService_V2/getCorpOutline_V2",
40
+ params={"serviceKey":FSC_KEY,"pageNo":1,"numOfRows":5,"resultType":"json","corpNm":name}, timeout=5)
41
+ items = r.json().get("response",{}).get("body",{}).get("items",{}).get("item",[])
42
+ if not items: return None
43
+ if isinstance(items, dict): items = [items]
44
+ bc = re.sub(r'\D','',str(biz_no))
45
+ m = next((i for i in items if re.sub(r'\D','',str(i.get("bzno",""))) == bc), items[0])
46
+ return {"phone":m.get("enpTlno",""), "addr":m.get("enpBsadr","") or m.get("enpDtadr","")}
47
+ except: return None
48
+
49
+ def naver_phone(name, addr):
50
+ clean = re.sub(r'์ฃผ์‹ํšŒ์‚ฌ|์œ ํ•œํšŒ์‚ฌ|\(์ฃผ\)|\(์œ \)|[(){}\[\]]','',name).strip()
51
+ gu = re.search(r'[\w]+๊ตฌ', addr); gu = gu.group() if gu else ""
52
+ try:
53
+ r = requests.get("https://m.map.naver.com/search2/search.nhn",
54
+ headers=NAV_HDR, params={"query":f"{clean} {gu}","type":"all"}, timeout=8)
55
+ if r.status_code == 429: time.sleep(30); return naver_phone(name, addr)
56
+ 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)']:
57
+ f = re.findall(pat, r.text)
58
+ if f: return f[0]
59
+ except: pass
60
+ return ""
61
+
62
+ def process_one(row_data):
63
+ idx, name, addr, biz_no, is_corp, gu = row_data
64
+ phone=""; full_addr=addr; lat=None; lon=None
65
+
66
+ if is_corp:
67
+ info = fsc_info(name, biz_no)
68
+ if info:
69
+ phone = info.get("phone","")
70
+ # FSC ์ฃผ์†Œ๋Š” ๋ณธ์‚ฌ ์ฃผ์†Œ๋ผ ๋ฎ์–ด์“ฐ์ง€ ์•Š์Œ
71
+ time.sleep(0.1)
72
+
73
+ kk = kakao_keyword(name, addr)
74
+ if kk:
75
+ if not phone: phone = kk.get("phone","")
76
+ road = kk.get("road_address_name","") or kk.get("address_name","")
77
+ # ์นด์นด์˜ค ๊ฒฐ๊ณผ๊ฐ€ ๊ฐ™์€ ๊ตฌ/๊ตฐ์ผ ๋•Œ๋งŒ ์ฃผ์†Œ ์—…๋ฐ์ดํŠธ
78
+ if road and gu and gu in road:
79
+ full_addr = road
80
+ lat = float(kk.get("y") or 0) or None
81
+ lon = float(kk.get("x") or 0) or None
82
+ elif not road or (gu and gu not in road):
83
+ # ์—‰๋šฑํ•œ ์ง€์—ญ ๊ฒฐ๊ณผ โ†’ ์›๋ณธ ์ฃผ์†Œ ์œ ์ง€, ์ขŒํ‘œ๋งŒ ์ทจ๋“
84
+ lat = float(kk.get("y") or 0) or None
85
+ lon = float(kk.get("x") or 0) or None
86
+
87
+ if not phone: phone = naver_phone(name, full_addr)
88
+ return idx, {"phone":phone, "addr":full_addr, "lat":lat, "lon":lon}
89
+
90
+ def make_excel(df):
91
+ wb = Workbook(); ws = wb.active; ws.title = "๋ณด์™„์™„๋ฃŒ"
92
+ def thin():
93
+ s = Side(style="thin",color="D0D0D0")
94
+ return Border(left=s,right=s,top=s,bottom=s)
95
+ hdrs = list(df.columns)
96
+ widths = {"์‚ฌ์—…์žฅ๋ช…":26,"์—…์ข…":18,"๋ฒ•์ธ์—ฌ๋ถ€":8,"์ฃผ์†Œ":42,"์ „ํ™”๋ฒˆํ˜ธ":14,"๊ฐ€์ž…์ž์ˆ˜":8,"๋‹น์›”๊ณ ์ง€๊ธˆ์•ก":14,"์œ„๋„":12,"๊ฒฝ๋„":12}
97
+ CENTER = {"๋ฒ•์ธ์—ฌ๋ถ€","๊ฐ€์ž…์ž์ˆ˜","๋‹น์›”๊ณ ์ง€๊ธˆ์•ก","์œ„๋„","๊ฒฝ๋„","์ „ํ™”๋ฒˆํ˜ธ"}
98
+ for c,h in enumerate(hdrs,1):
99
+ cell = ws.cell(1,c,h)
100
+ cell.fill = PatternFill("solid",start_color="1F3864")
101
+ cell.font = Font(name="Arial",size=10,bold=True,color="FFFFFF")
102
+ cell.alignment = Alignment(horizontal="center",vertical="center")
103
+ cell.border = thin()
104
+ ws.column_dimensions[get_column_letter(c)].width = widths.get(h,12)
105
+ ws.row_dimensions[1].height = 18
106
+ ws.freeze_panes = "A2"
107
+ ws.auto_filter.ref = f"A1:{get_column_letter(len(hdrs))}1"
108
+ for ri,row in enumerate(df.itertuples(index=False),2):
109
+ for ci,(h,v) in enumerate(zip(hdrs,row),1):
110
+ if pd.isna(v) or str(v) in ("nan","None"): v=""
111
+ cell = ws.cell(ri,ci,v)
112
+ cell.font = Font(name="Arial",size=10)
113
+ cell.border = thin()
114
+ cell.fill = PatternFill("solid",start_color="FFFFFF" if ri%2==0 else "F8FAFC")
115
+ cell.alignment = Alignment(horizontal="center" if h in CENTER else "left",vertical="center")
116
+ buf = io.BytesIO(); wb.save(buf); return buf.getvalue()
117
+
118
+ # โ”€โ”€ UI โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
119
+ st.title("๐Ÿ“‹ ์‚ฌ์—…์žฅ ์ฃผ์†Œยท์ „ํ™”๋ฒˆํ˜ธ ๋ณด์™„")
120
+ st.caption("์ง€์—ญ ํŒŒ์ผ ์—…๋กœ๋“œ โ†’ ์ž๋™ ์ฒ˜๋ฆฌ โ†’ ๋‹ค์šด๋กœ๋“œ")
121
+ st.divider()
122
+
123
+ uploaded = st.file_uploader("ํŒŒ์ผ ์„ ํƒ (๊ตญ๋ฏผ์—ฐ๊ธˆ_XX์‹œ_XX๊ตฌ_์‚ฌ์—…์žฅ.xlsx)", type=["xlsx"])
124
+
125
+ if uploaded:
126
+ df = pd.read_excel(uploaded)
127
+ df.columns = [c.strip() for c in df.columns]
128
+ gc.collect()
129
+
130
+ name_col = next((c for c in df.columns if "์‚ฌ์—…์žฅ๋ช…" in c or "์ƒํ˜ธ" in c), None)
131
+ addr_col = next((c for c in df.columns if "์ฃผ์†Œ" in c or "๋„๋กœ๋ช…" in c), None)
132
+ biz_col = next((c for c in df.columns if "์‚ฌ์—…์ž" in c and "๋ฒˆํ˜ธ" in c), None)
133
+ type_col = next((c for c in df.columns if "ํ˜•ํƒœ" in c or "๋ฒ•์ธ" in c), None)
134
+ emp_col = next((c for c in df.columns if "๊ฐ€์ž…์ž" in c), None)
135
+ pay_col = next((c for c in df.columns if "๊ณ ์ง€" in c), None)
136
+ ind_col = next((c for c in df.columns if "์—…์ข…" in c), None)
137
+
138
+ for col in ["์ „ํ™”๋ฒˆํ˜ธ"]:
139
+ if col not in df.columns: df[col] = ""
140
+ else: df[col] = df[col].fillna("").astype(str).replace("nan","")
141
+ for col in ["์œ„๋„","๊ฒฝ๋„"]:
142
+ if col not in df.columns: df[col] = None
143
+ else: df[col] = pd.to_numeric(df[col], errors="coerce")
144
+
145
+ total = len(df)
146
+ fname = uploaded.name.replace(".xlsx","")
147
+ st.success(f"โœ… {fname} โ€” {total:,}๊ฐœ ๋กœ๋“œ ์™„๋ฃŒ")
148
+
149
+ prog = st.progress(0, text="์ฒ˜๋ฆฌ ์ค‘...")
150
+ phone_ok = coord_ok = completed = 0
151
+
152
+ # ๊ตฌ/๊ตฐ ์ถ”์ถœ (์—‰๋šฑํ•œ ์ง€์—ญ ํ•„ํ„ฐ๋ง์šฉ)
153
+ gu = ""
154
+ if addr_col:
155
+ sample = df[addr_col].dropna().iloc[0] if len(df) > 0 else ""
156
+ m = re.search(r'[\w]+๊ตฌ|[\w]+๊ตฐ', str(sample))
157
+ gu = m.group() if m else ""
158
+
159
+ tasks = []
160
+ for idx in df.index:
161
+ row = df.loc[idx]
162
+ tasks.append((idx,
163
+ str(row.get(name_col,"")) if name_col else "",
164
+ str(row.get(addr_col,"")) if addr_col else "",
165
+ str(row.get(biz_col,"")) if biz_col else "",
166
+ str(row.get(type_col,"")) in ["๋ฒ•์ธ","1"] if type_col else False,
167
+ gu))
168
+
169
+ with ThreadPoolExecutor(max_workers=WORKERS) as executor:
170
+ futures = {executor.submit(process_one, t): t[0] for t in tasks}
171
+ for future in as_completed(futures):
172
+ try:
173
+ idx, res = future.result()
174
+ df.loc[idx,"์ „ํ™”๋ฒˆํ˜ธ"] = str(res["phone"])
175
+ df.loc[idx,"์œ„๋„"] = res["lat"]
176
+ df.loc[idx,"๊ฒฝ๋„"] = res["lon"]
177
+ if addr_col and res["addr"]: df.loc[idx,addr_col] = res["addr"]
178
+ if res["phone"]: phone_ok += 1
179
+ if res["lat"]: coord_ok += 1
180
+ except: pass
181
+ completed += 1
182
+ prog.progress(completed/total, text=f"๐Ÿ“ž{phone_ok} ๐Ÿ“{coord_ok} | {completed}/{total}")
183
+
184
+ prog.empty()
185
+
186
+ col_map = {}
187
+ if name_col: col_map[name_col]="์‚ฌ์—…์žฅ๋ช…"
188
+ if type_col: col_map[type_col]="๋ฒ•์ธ์—ฌ๋ถ€"
189
+ if addr_col: col_map[addr_col]="์ฃผ์†Œ"
190
+ col_map["์ „ํ™”๋ฒˆํ˜ธ"]="์ „ํ™”๋ฒˆํ˜ธ"
191
+ if emp_col: col_map[emp_col]="๊ฐ€์ž…์ž์ˆ˜"
192
+ if pay_col: col_map[pay_col]="๋‹น์›”๊ณ ์ง€๊ธˆ์•ก"
193
+ if ind_col: col_map[ind_col]="์—…์ข…"
194
+ col_map["์œ„๋„"]="์œ„๋„"; col_map["๊ฒฝ๋„"]="๊ฒฝ๋„"
195
+
196
+ out = df[[c for c in col_map if c in df.columns]].rename(columns=col_map)
197
+ # ์ „ํ™”๋ฒˆํ˜ธ/์ฃผ์†Œ ์—†์œผ๋ฉด ์‚ญ์ œ + ํ•ด๋‹น ๊ตฌ/๊ตฐ ์•„๋‹Œ ์ฃผ์†Œ๋„ ์‚ญ์ œ
198
+ mask = (out["์ „ํ™”๋ฒˆํ˜ธ"].notna() & (out["์ „ํ™”๋ฒˆํ˜ธ"]!="") &
199
+ out["์ฃผ์†Œ"].notna() & (out["์ฃผ์†Œ"]!=""))
200
+ if gu:
201
+ mask = mask & out["์ฃผ์†Œ"].str.contains(gu, na=False)
202
+ out = out[mask].reset_index(drop=True)
203
+ del df; gc.collect()
204
+
205
+ st.success(f"โœ… ์™„๋ฃŒ! ๐Ÿ“ž{phone_ok:,}๊ฐœ | ๐Ÿ“{coord_ok:,}๊ฐœ | ์ตœ์ข… {len(out):,}๊ฐœ")
206
+ st.balloons()
207
+ st.download_button("โฌ‡๏ธ ๋ณด์™„ ์™„๋ฃŒ ์—‘์…€ ๋‹ค์šด๋กœ๋“œ",
208
+ make_excel(out), fname+"_๋ณด์™„์™„๋ฃŒ.xlsx",
209
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
210
+ use_container_width=True)