File size: 8,453 Bytes
1271db4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 |
"""
ํค์๋ ๊ฒ์๋ ์กฐํ ๊ด๋ จ ๊ธฐ๋ฅ
- ๋ค์ด๋ฒ API๋ฅผ ํตํ ํค์๋ ๊ฒ์๋ ์กฐํ
- ๊ฒ์๋ ๋ฐฐ์น ์ฒ๋ฆฌ
"""
import requests
import time
import random
from concurrent.futures import ThreadPoolExecutor, as_completed
import api_utils
import logging
# ๋ก๊น
์ค์
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
def exponential_backoff_sleep(retry_count, base_delay=0.3, max_delay=5.0):
"""์ง์ ๋ฐฑ์คํ ๋ฐฉ์์ ๋๊ธฐ ์๊ฐ ๊ณ์ฐ"""
delay = min(base_delay * (2 ** retry_count), max_delay)
# ์ฝ๊ฐ์ ๋๋ค์ฑ ์ถ๊ฐ (์งํฐ)
jitter = random.uniform(0, 0.5) * delay
time.sleep(delay + jitter)
def fetch_search_volume_batch(keywords_batch):
"""ํค์๋ ๋ฐฐ์น์ ๋ํ ๋ค์ด๋ฒ ๊ฒ์๋ ์กฐํ"""
# 1. ์คํ์ด์ค๋ฐ ์ ๊ฑฐ ๊ฐ์ - ๋ฐฐ์น ํค์๋๋ค ์ ์ฒ๋ฆฌ
cleaned_keywords_batch = []
for kw in keywords_batch:
cleaned_kw = kw.strip().replace(" ", "") if kw else ""
cleaned_keywords_batch.append(cleaned_kw)
keywords_batch = cleaned_keywords_batch
result = {}
max_retries = 3
retry_count = 0
while retry_count < max_retries:
try:
# ์์ฐจ์ ์ผ๋ก API ์ค์ ๊ฐ์ ธ์ค๊ธฐ (๋ฐฐ์น๋ง๋ค ํ ๋ฒ๋ง ํธ์ถ)
api_config = api_utils.get_next_api_config()
API_KEY = api_config["API_KEY"]
SECRET_KEY = api_config["SECRET_KEY"]
CUSTOMER_ID_STR = api_config["CUSTOMER_ID"]
logger.debug(f"=== ํ๊ฒฝ ๋ณ์ ์ฒดํฌ (์๋ #{retry_count+1}) ===")
logger.info(f"๋ฐฐ์น ํฌ๊ธฐ: {len(keywords_batch)}๊ฐ ํค์๋")
# API ์ค์ ์ ํจ์ฑ ๊ฒ์ฌ
is_valid, message = api_utils.validate_api_config(api_config)
if not is_valid:
logger.error(f"โ {message}")
retry_count += 1
exponential_backoff_sleep(retry_count)
continue
# CUSTOMER_ID๋ฅผ ์ ์๋ก ๋ณํ
try:
CUSTOMER_ID = int(CUSTOMER_ID_STR)
except ValueError:
logger.error(f"โ CUSTOMER_ID ๋ณํ ์ค๋ฅ: '{CUSTOMER_ID_STR}'๋ ์ ํจํ ์ซ์๊ฐ ์๋๋๋ค.")
retry_count += 1
exponential_backoff_sleep(retry_count)
continue
BASE_URL = "https://api.naver.com"
uri = "/keywordstool"
method = "GET"
headers = api_utils.get_header(method, uri, API_KEY, SECRET_KEY, CUSTOMER_ID)
# ํค์๋ ๋ฐฐ์น๋ฅผ ํ ๋ฒ์ API๋ก ์ ์ก
params = {
"hintKeywords": keywords_batch,
"showDetail": "1"
}
logger.debug(f"์์ฒญ ํ๋ผ๋ฏธํฐ: {len(keywords_batch)}๊ฐ ํค์๋")
# API ํธ์ถ
response = requests.get(BASE_URL + uri, params=params, headers=headers, timeout=10)
logger.debug(f"์๋ต ์ํ ์ฝ๋: {response.status_code}")
if response.status_code != 200:
logger.error(f"โ API ์ค๋ฅ ์๋ต (์๋ #{retry_count+1}):")
logger.error(f" ๋ณธ๋ฌธ: {response.text}")
retry_count += 1
exponential_backoff_sleep(retry_count)
continue
# ์๋ต ๋ฐ์ดํฐ ํ์ฑ
result_data = response.json()
logger.debug(f"์๋ต ๋ฐ์ดํฐ ๊ตฌ์กฐ:")
logger.debug(f" ํ์
: {type(result_data)}")
logger.debug(f" ํค๋ค: {result_data.keys() if isinstance(result_data, dict) else 'N/A'}")
if isinstance(result_data, dict) and "keywordList" in result_data:
logger.debug(f" keywordList ๊ธธ์ด: {len(result_data['keywordList'])}")
# ๋ฐฐ์น ๋ด ๊ฐ ํค์๋์ ๋งค์นญ
for keyword in keywords_batch:
found = False
for item in result_data["keywordList"]:
rel_keyword = item.get("relKeyword", "")
if rel_keyword == keyword:
pc_count = item.get("monthlyPcQcCnt", 0)
mobile_count = item.get("monthlyMobileQcCnt", 0)
# ์ซ์ ๋ณํ
try:
if isinstance(pc_count, str):
pc_count_converted = int(pc_count.replace(",", ""))
else:
pc_count_converted = int(pc_count)
except:
pc_count_converted = 0
try:
if isinstance(mobile_count, str):
mobile_count_converted = int(mobile_count.replace(",", ""))
else:
mobile_count_converted = int(mobile_count)
except:
mobile_count_converted = 0
total_count = pc_count_converted + mobile_count_converted
result[keyword] = {
"PC๊ฒ์๋": pc_count_converted,
"๋ชจ๋ฐ์ผ๊ฒ์๋": mobile_count_converted,
"์ด๊ฒ์๋": total_count
}
logger.debug(f"โ
'{keyword}': PC={pc_count_converted}, Mobile={mobile_count_converted}, Total={total_count}")
found = True
break
if not found:
logger.warning(f"โ '{keyword}': ๋งค์นญ๋๋ ๋ฐ์ดํฐ๋ฅผ ์ฐพ์ ์ ์์")
# ์ฑ๊ณต์ ์ผ๋ก ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์์ผ๋ฏ๋ก ๋ฃจํ ์ข
๋ฃ
break
else:
logger.error(f"โ keywordList๊ฐ ์์ (์๋ #{retry_count+1})")
logger.error(f"์ ์ฒด ์๋ต: {result_data}")
retry_count += 1
exponential_backoff_sleep(retry_count)
except Exception as e:
logger.error(f"โ ๋ฐฐ์น ์ฒ๋ฆฌ ์ค ์ค๋ฅ (์๋ #{retry_count+1}): {str(e)}")
import traceback
logger.error(traceback.format_exc())
retry_count += 1
exponential_backoff_sleep(retry_count)
logger.info(f"\n=== ๋ฐฐ์น ์ฒ๋ฆฌ ์๋ฃ ===")
logger.info(f"์ฑ๊ณต์ ์ผ๋ก ์ฒ๋ฆฌ๋ ํค์๋ ์: {len(result)}")
return result
def fetch_all_search_volumes(keywords, batch_size=5):
"""ํค์๋ ๋ฆฌ์คํธ์ ๋ํ ๋ค์ด๋ฒ ๊ฒ์๋ ๋ณ๋ ฌ ์กฐํ"""
results = {}
batches = []
# ํค์๋๋ฅผ 5๊ฐ์ฉ ๋ฌถ์ด์ ๋ฐฐ์น ์์ฑ
for i in range(0, len(keywords), batch_size):
batch = keywords[i:i + batch_size]
batches.append(batch)
logger.info(f"์ด {len(batches)}๊ฐ ๋ฐฐ์น๋ก {len(keywords)}๊ฐ ํค์๋ ์ฒ๋ฆฌ ์คโฆ")
logger.info(f"๋ฐฐ์น ํฌ๊ธฐ: {batch_size}, ๋ณ๋ ฌ ์์ปค: 3๊ฐ, API ๊ณ์ : {len(api_utils.NAVER_API_CONFIGS)}๊ฐ ์์ฐจ ์ฌ์ฉ")
with ThreadPoolExecutor(max_workers=3) as executor: # ์์ปค ์ ์ ํ
futures = {executor.submit(fetch_search_volume_batch, batch): batch for batch in batches}
for future in as_completed(futures):
batch = futures[future]
try:
batch_results = future.result()
results.update(batch_results)
logger.info(f"๋ฐฐ์น ์ฒ๋ฆฌ ์๋ฃ: {len(batch)}๊ฐ ํค์๋ (์ฑ๊ณต: {len(batch_results)}๊ฐ)")
except Exception as e:
logger.error(f"๋ฐฐ์น ์ฒ๋ฆฌ ์ค๋ฅ: {e}")
# API ๋ ์ดํธ ๋ฆฌ๋ฐ ๋ฐฉ์ง๋ฅผ ์ํ ์ง์ ๋ฐฑ์คํ ์ฌ์ฉ
exponential_backoff_sleep(0) # ์ด๊ธฐ ์ง์ฐ ์ ์ฉ
logger.info(f"๊ฒ์๋ ์กฐํ ์๋ฃ: {len(results)}๊ฐ ํค์๋")
return results |