Spaces:
Running
Running
fix: ์ํฌ๋ฆฟ ๊ฐ ๊ฐํ/๊ณต๋ฐฑ์ผ๋ก datalab ํค๋ ๊ฒ์ฆ ์คํจํ๋ ๊ฒ ๋ฐฉ์ด(.strip)
0685414 | # ๋ค์ด๋ฒ ๋ฐ์ดํฐ๋ฉ ๊ฒ์์ด ํธ๋ ๋๋ก ์ฑ๋ณร์ฐ๋ น ์ถ์ ๋น์ค์ ์ฐ์ถํ๋ ๋ชจ๋ | |
| # ์ฃผ์: ์ธ๊ทธ๋จผํธ๋ณ ๋ ๋ฆฝ ์ ๊ทํ๋ฅผ ์ต์ปค ํค์๋ ๋น์จ๋ก ์์ํ '์ถ์ ' ์๋๊ฐ. ์ ๋ ๊ฒ์๋ ์๋. | |
| import os | |
| from datetime import date, timedelta | |
| import requests | |
| URL = "https://openapi.naver.com/v1/datalab/search" | |
| ANCHOR = "๋ ์จ" # ์ ๊ทํ ์์์ฉ ๊ด๋ฒ์ ํค์๋ (๊ฐ์ : ์ฐ๋ นยท์ฑ๋ณ ๋ถํฌ๊ฐ ๋น๊ต์ ๊ณ ๋ฆ) | |
| AGE_BANDS = { # ํ์ ๊ตฌ๊ฐ โ ๋ฐ์ดํฐ๋ฉ ์ฐ๋ น ์ฝ๋ | |
| "20๋ ์ดํ": ["1", "2", "3", "4"], # ~29์ธ | |
| "30๋": ["5", "6"], | |
| "40๋": ["7", "8"], | |
| "50๋ ์ด์": ["9", "10", "11"], # 50์ธ~ | |
| } | |
| GENDERS = {"m": "๋จ์ฑ", "f": "์ฌ์ฑ"} | |
| def _headers() -> dict: | |
| # .strip(): ์ํฌ๋ฆฟ ๋ฑ๋ก ์ ๋ธ๋ ค์จ ๊ฐํ/๊ณต๋ฐฑ์ด HTTP ํค๋ ๊ฒ์ฆ์ ๊นจ๋ ๊ฒ ๋ฐฉ์ง(HF Secrets ๋ถ์ฌ๋ฃ๊ธฐ ์ด์) | |
| return { | |
| "X-Naver-Client-Id": os.environ["NAVER_CLIENT_ID"].strip(), | |
| "X-Naver-Client-Secret": os.environ["NAVER_CLIENT_SECRET"].strip(), | |
| "Content-Type": "application/json", | |
| } | |
| def _segment_score(keyword: str, gender: str, ages: list, start: str, end: str) -> float: | |
| # ํ ์ธ๊ทธ๋จผํธ์์ [ํค์๋, ์ต์ปค]๋ฅผ ๊ฐ์ ์์ฒญ์ผ๋ก ์ ๊ทํ โ ํค์๋/์ต์ปค ํ๊ท ๋น์จ ๋ฐํ | |
| body = { | |
| "startDate": start, "endDate": end, "timeUnit": "month", | |
| "keywordGroups": [ | |
| {"groupName": "kw", "keywords": [keyword]}, | |
| {"groupName": "anchor", "keywords": [ANCHOR]}, | |
| ], | |
| "gender": gender, "ages": ages, | |
| } | |
| res = requests.post(URL, json=body, headers=_headers(), timeout=10) | |
| res.raise_for_status() | |
| groups = {g["title"]: g["data"] for g in res.json()["results"]} | |
| def avg(rows): | |
| return sum(d["ratio"] for d in rows) / len(rows) if rows else 0.0 | |
| kw, anchor = avg(groups.get("kw", [])), avg(groups.get("anchor", [])) | |
| return kw / anchor if anchor else 0.0 | |
| def demographics(keyword: str) -> dict: | |
| # ์ฑ๋ณร์ฐ๋ น 8๊ฐ ์ธ๊ทธ๋จผํธ์ ์ถ์ ๋น์ค(%) ๋ฐํ | |
| end = date.today().replace(day=1) - timedelta(days=1) # ์ง๋๋ฌ ๋ง์ผ | |
| start = end.replace(year=end.year - 1, day=1) # ์ฝ 13๊ฐ์ ์ 1์ผ | |
| cells, total = [], 0.0 | |
| for g, glabel in GENDERS.items(): | |
| for alabel, ages in AGE_BANDS.items(): | |
| score = _segment_score(keyword, g, ages, start.isoformat(), end.isoformat()) | |
| cells.append({"gender": glabel, "age": alabel, "score": round(score, 4)}) | |
| total += score | |
| for c in cells: | |
| c["pct"] = round(c["score"] / total * 100, 1) if total else 0.0 | |
| return {"cells": cells, "anchor": ANCHOR} | |