import re import pandas as pd import io import tempfile import os from collections import Counter, defaultdict import gradio as gr import requests import time import hmac import hashlib import base64 from concurrent.futures import ThreadPoolExecutor, as_completed import threading # 네이버 API 관련 함수들 def generate_signature(timestamp, method, uri, secret_key): message = f"{timestamp}.{method}.{uri}" digest = hmac.new(secret_key.encode("utf-8"), message.encode("utf-8"), hashlib.sha256).digest() return base64.b64encode(digest).decode() def get_header(method, uri, api_key, secret_key, customer_id): timestamp = str(round(time.time() * 1000)) signature = generate_signature(timestamp, method, uri, secret_key) return { "Content-Type": "application/json; charset=UTF-8", "X-Timestamp": timestamp, "X-API-KEY": api_key, "X-Customer": str(customer_id), "X-Signature": signature } def fetch_search_volume_batch(keywords_batch): """키워드 배치에 대한 네이버 검색량 조회""" try: # 환경 변수에서 API 정보 가져오기 API_KEY = os.environ.get("NAVER_API_KEY") SECRET_KEY = os.environ.get("NAVER_SECRET_KEY") CUSTOMER_ID = os.environ.get("NAVER_CUSTOMER_ID") if not all([API_KEY, SECRET_KEY, CUSTOMER_ID]): print("네이버 API 키가 설정되지 않았습니다.") return {} BASE_URL = "https://api.naver.com" uri = "/keywordstool" method = "POST" # POST 메서드로 변경 headers = get_header(method, uri, API_KEY, SECRET_KEY, int(CUSTOMER_ID)) # JSON body로 데이터 전송 data = { "hintKeywords": keywords_batch, "showDetail": "1" } response = requests.post(BASE_URL + uri, json=data, headers=headers) if response.status_code != 200: print(f"네이버 API 응답 오류: {response.status_code} - {response.text}") return {} data = response.json() # 결과 파싱 result = {} if "keywordList" in data: for item in data["keywordList"]: keyword = item.get("relKeyword", "") pc_count = item.get("monthlyPcQcCnt", 0) mobile_count = item.get("monthlyMobileQcCnt", 0) # 문자열을 숫자로 변환 try: pc_count = int(str(pc_count).replace(",", "")) if pc_count else 0 mobile_count = int(str(mobile_count).replace(",", "")) if mobile_count else 0 except: pc_count = mobile_count = 0 total_count = pc_count + mobile_count result[keyword] = { "PC검색량": pc_count, "모바일검색량": mobile_count, "총검색량": total_count } return result except Exception as e: print(f"네이버 API 호출 오류: {str(e)}") return {} def fetch_all_search_volumes(keywords, batch_size=5): # 배치 크기를 5로 줄임 """키워드 리스트에 대한 네이버 검색량 병렬 조회""" results = {} batches = [] # 키워드를 배치로 나누기 for i in range(0, len(keywords), batch_size): batch = keywords[i:i + batch_size] batches.append(batch) print(f"총 {len(batches)}개 배치로 {len(keywords)}개 키워드 처리 중...") # 병렬 처리 with ThreadPoolExecutor(max_workers=3) as executor: # 워커 수도 3으로 줄임 future_to_batch = {executor.submit(fetch_search_volume_batch, batch): batch for batch in batches} for future in as_completed(future_to_batch): batch = future_to_batch[future] try: batch_results = future.result() results.update(batch_results) print(f"배치 처리 완료: {len(batch)}개 키워드") except Exception as e: print(f"배치 처리 오류: {str(e)}") # API 레이트 리미트 방지를 위한 딜레이 time.sleep(1) # 딜레이를 1초로 증가 print(f"검색량 조회 완료: {len(results)}개 키워드") return results def preprocess_text(text): """ 텍스트 전처리 함수: 1. "*" 문제가 나오면 제거 2. " "이면 " "로 변경 3. 스페이스가 1개 이상이면 무조건 2개면 1개로 수정 """ # 1. "*" 제거 processed = re.sub(r'\*', '', text) # 2 & 3. 스페이스가 2개 이상이면 1개로 수정 processed = re.sub(r'\s{2,}', ' ', processed) return processed.strip() def extract_product_categories(text): """ 텍스트에서 상품명과 해당 카테고리를 추출하는 함수 """ main_categories = [ '가구/인테리어', '생활/건강', '패션잡화', '디지털/가전', '출산/육아', '스포츠/레저', '화장품/미용', '패션의류', '여가/생활편의', '식품' ] lines = text.split('\n') # 상품명과 카테고리를 매핑 product_categories = {} current_product = None for i, line in enumerate(lines): clean_line = preprocess_text(line) # 찜하기가 포함된 라인이면 직후의 라인이 상품명 if '찜하기' in clean_line: # 이전 상품 저장 if current_product and current_category: product_categories[current_product] = current_category # 새로운 상품 시작 if i + 1 < len(lines): current_product = preprocess_text(lines[i + 1]) current_category = None # 카테고리 라인 체크 - 전체 라인을 그대로 저장 else: for main_cat in main_categories: if clean_line.startswith(main_cat): if current_product: current_category = clean_line # 전체 라인을 저장 break # 마지막 상품 저장 if current_product and current_category: product_categories[current_product] = current_category return product_categories def extract_titles(text, debug=False): """ 텍스트에서 제품 제목을 추출하는 함수 """ # 원본 줄 저장 (** 패턴 보존) original_lines = text.split('\n') # 전처리된 줄 저장 lines = [preprocess_text(line) for line in original_lines] # 제목이 아닌 것으로 간주할 명확한 패턴들 (정규표현식) exclude_patterns = [ r'^상품만 보기$', r'^구매정보$', r'^포인트 최대.*$', r'^생활/건강.*$', r'^적립쿠폰$', r'^별점.*$', r'^리뷰.*$', r'^쇼핑몰별.*$', r'^파워$', r'^서비스$', r'^빅파워.*$', r'^굿서비스$', r'^무료교환반품$', r'^오늘출발$', r'^네이버플러스.*$', r'^멤버십.*$', r'^신고하기$', r'^등록일.*$', r'^톡톡$', r'^.*포인트 적립예정$', r'^와우 멤버십.*$', ] # 제품 블록 경계 찾기 block_boundaries = [] for i in range(len(lines)): if '찜하기' in lines[i]: block_boundaries.append(i) # 마지막 블록 끝 추가 if len(block_boundaries) > 0: block_boundaries.append(len(lines)) else: # 찜하기가 없는 경우, 전체 텍스트를 하나의 블록으로 처리 block_boundaries = [0, len(lines)] if debug: print(f"총 {len(block_boundaries) - 1}개의 제품 블록 발견") # 최종 제목 목록 final_titles = [] # 각 제품 블록별로 처리 for b in range(len(block_boundaries) - 1): block_start = block_boundaries[b] block_end = block_boundaries[b + 1] # 현재 블록 내에서만 사용할 제목 후보 리스트 block_title_candidates = [] # 블록 내 광고 위치 파악 ad_indices = [] for i in range(block_start, block_end): if '광고' in lines[i]: ad_indices.append(i) # 블록 내 광고 위치 기반 광고 근처 표시 (블록 경계 내에서만) has_ad_nearby = [False] * (block_end - block_start) for ad_idx in ad_indices: # 광고 주변 5줄 범위를 블록 내에서만 계산 for j in range(max(0, ad_idx - block_start - 5), min(block_end - block_start, ad_idx - block_start + 6)): has_ad_nearby[j] = True # 블록에 광고가 있는지 확인 block_has_ad = len(ad_indices) > 0 # 광고가 있는 블록은 제외하지 않고, 광고 주변 텍스트만 제외 if debug and block_has_ad: print(f"블록 {b+1} (라인 {block_start+1}-{block_end}): 광고 포함") # 패턴 1: ** 패턴 확인 for i in range(block_start, block_end): # 블록 내 상대적 인덱스 relative_idx = i - block_start # 광고 주변이면 건너뛰기 if block_has_ad and has_ad_nearby[relative_idx]: continue original_line = original_lines[i] if '**' in original_line: matches = re.findall(r'\*\*(.*?)\*\*', original_line) for match in matches: clean_match = preprocess_text(match) # 제목으로 적합한지 확인 if is_valid_title(clean_match, exclude_patterns): # 해외 접두사 제거 if clean_match.startswith('해외'): clean_match = clean_match[2:] block_title_candidates.append(clean_match) # 패턴 2: 가격 정보 바로 위 줄 확인 for i in range(block_start, block_end - 1): # 블록 내 상대적 인덱스 relative_idx = i - block_start # 광고 주변이면 건너뛰기 if block_has_ad and has_ad_nearby[relative_idx]: continue current_line = lines[i] next_line = lines[i + 1] # 가격 패턴 확인 price_pattern = re.search(r'\d+,?\d*원', next_line) or '원배송비' in next_line if price_pattern and is_valid_title(current_line, exclude_patterns) and '찜하기' not in current_line: # 해외 접두사 제거 if current_line.startswith('해외'): current_line = current_line[2:] block_title_candidates.append(current_line) # 패턴 3: 찜하기 다음 줄 확인 if block_start + 1 < block_end: # 블록 내 상대적 인덱스 relative_idx = 1 # 첫 줄 다음 # 광고 주변이 아닌 경우에만 처리 if not (block_has_ad and has_ad_nearby[relative_idx]): next_line = lines[block_start + 1] if is_valid_title(next_line, exclude_patterns): # 해외 접두사 제거 if next_line.startswith('해외'): next_line = next_line[2:] block_title_candidates.append(next_line) # 패턴 4: 위아래로 3줄 내에 동일한 텍스트 확인 (규칙 4) for i in range(block_start, block_end): # 블록 내 상대적 인덱스 relative_idx = i - block_start # 광고 주변이면 건너뛰기 if block_has_ad and has_ad_nearby[relative_idx]: continue current_line = lines[i] if not is_valid_title(current_line, exclude_patterns): continue # 위아래로 3줄 범위 내에 동일한 텍스트 확인 (블록 경계 내에서) for j in range(max(block_start, i - 3), min(block_end, i + 4)): if i != j and lines[i] == lines[j]: # 해외 접두사 제거 if current_line.startswith('해외'): current_line = current_line[2:] block_title_candidates.append(current_line) break # 현재 블록에서 가장 적합한 제목 선택 best_title = select_best_title(block_title_candidates) # 적합한 제목을 찾았으면 최종 목록에 추가 if best_title: final_titles.append(best_title) if debug: print(f"블록 {b+1}의 제목: {best_title}") else: # 제목을 찾지 못한 경우, 블록의 첫 줄 이후 5줄 내에서 찾기 for i in range(block_start + 1, min(block_start + 6, block_end)): # 블록 내 상대적 인덱스 relative_idx = i - block_start # 광고 주변이면 건너뛰기 if block_has_ad and has_ad_nearby[relative_idx]: continue current_line = lines[i] if is_valid_title(current_line, exclude_patterns): # 해외 접두사 제거 if current_line.startswith('해외'): current_line = current_line[2:] final_titles.append(current_line) if debug: print(f"블록 {b+1}의 대체 제목: {current_line}") break return final_titles def is_valid_title(text, exclude_patterns): """ 제목으로 적합한지 확인하는 함수 * 특정 키워드 요구 대신 구조적 패턴 검사 """ # 길이 검사 (너무 짧으면 제목이 아님) if len(text) < 10: return False # 숫자만으로 구성된 텍스트 제외 if re.match(r'^[\d,.\s]+$', text): return False # 제외 패턴 검사 for pattern in exclude_patterns: if re.match(pattern, text): return False return True def select_best_title(candidates): """ 여러 제목 후보 중 가장 적합한 것을 선택 """ if not candidates: return None # 제목 점수 계산 함수 def score_title(title): score = 0 # 길이가 적절한 제목 선호 (10-50자) if 10 <= len(title) <= 50: score += 3 elif 50 < len(title) <= 100: score += 2 else: score += 1 # 특정 패턴이 제목에 포함되어 있으면 점수 추가 if re.search(r'[A-Za-z0-9\-]+', title): # 모델번호 포함 가능성 score += 2 # 브랜드명이 앞에 오는 경우 점수 추가 if re.match(r'^[가-힣A-Za-z]+\s', title): score += 1 return score # 점수 기반으로 정렬 scored_candidates = [(score_title(title), title) for title in candidates] scored_candidates.sort(reverse=True) return scored_candidates[0][1] if scored_candidates else None def extract_keywords(titles): """ 제목에서 의미 있는 키워드를 추출하는 함수 """ # 불용어 목록 (제외할 단어들) stop_words = [ '및', '등', '외', '포함', '세트', '구성', '가능', '용', '있는', '위한', '기타', '없음', '사용', '개', '있음', '없음', '기본', '가능한', '또는', '포함된', '함께', '경우', '제공', '적용', '수', '시', '함', '의', '이', '가', '을', '를', '에', '에서', '으로', '로', '는', '은', '이다', '있다', '더', '와', '과', '해도' ] # 모든 키워드를 저장할 딕셔너리: {키워드: [등장 제목 인덱스 리스트]} keyword_indices = defaultdict(list) # 모든 제목에서 키워드 추출 for idx, title in enumerate(titles): # 제목에서 특수문자, 괄호 등 제거 clean_title = re.sub(r'[^\w\s]', ' ', title) # 제목을 단어로 분리 words = clean_title.split() # 한 제목 내에서 이미 처리한 키워드 추적 processed_words = set() for word in words: # 2글자 미만 단어, 숫자만으로 된 단어, 불용어 제외 if len(word) < 2 or word.isdigit() or word.lower() in stop_words: continue # 각 키워드는 제목당 한 번만 카운트 if word not in processed_words: keyword_indices[word].append(idx) processed_words.add(word) return keyword_indices def categorize_keywords_by_products(keyword_indices, titles, product_categories): """ 상품명에 따라 키워드를 카테고리별로 분류하는 함수 """ # 모든 카테고리 목록 추출 all_categories = set(product_categories.values()) # 각 키워드별로 카테고리 매핑 keyword_mappings = {} # 각 키워드에 대해 카테고리 판단 for keyword, indices in keyword_indices.items(): keyword_mappings[keyword] = set() # 키워드가 등장한 각 상품에 대해 카테고리 확인 for idx in indices: if idx < len(titles): title = titles[idx] # 해당 상품의 카테고리 찾기 if title in product_categories: category = product_categories[title] keyword_mappings[keyword].add(category) return keyword_mappings, sorted(list(all_categories)) def analyze_keywords_with_categories(titles, text, include_search_volume=True): """ 제목에서 키워드를 분석하고 카테고리별로 분류하는 함수 반환: - keyword_stats: 키워드 분석 정보가 담긴 DataFrame """ # 상품명과 카테고리 매핑 추출 product_categories = extract_product_categories(text) # 제목에서 키워드 추출 keyword_indices = extract_keywords(titles) # 키워드 카테고리 분류 keyword_mappings, all_categories = categorize_keywords_by_products(keyword_indices, titles, product_categories) # 네이버 검색량 조회 (병렬 처리) search_volumes = {} if include_search_volume: keywords_list = list(keyword_indices.keys()) search_volumes = fetch_all_search_volumes(keywords_list) # 키워드 통계 정보 생성 keyword_stats = [] for keyword, indices in keyword_indices.items(): # 해당 키워드가 등장한 제목 수 count = len(indices) # 등장한 제목 순위 문자열 ranks = ", ".join(str(idx + 1) for idx in indices) # 상위 노출 카테고리 결정 if any(idx < 10 for idx in indices): exposure_category = "상위 10개" elif any(idx < 20 for idx in indices): exposure_category = "상위 20개" elif any(idx < 30 for idx in indices): exposure_category = "상위 30개" elif any(idx < 40 for idx in indices): exposure_category = "상위 40개" else: exposure_category = "1페이지 미포함" # 기본 키워드 정보 keyword_data = { '키워드': keyword, '등장 순위': ranks, '사용 횟수': count, '상위노출 키워드': exposure_category } # 네이버 검색량 정보 추가 if keyword in search_volumes: keyword_data['PC검색량'] = search_volumes[keyword]['PC검색량'] keyword_data['모바일검색량'] = search_volumes[keyword]['모바일검색량'] keyword_data['총검색량'] = search_volumes[keyword]['총검색량'] else: keyword_data['PC검색량'] = 0 keyword_data['모바일검색량'] = 0 keyword_data['총검색량'] = 0 # 각 카테고리별로 "O" 표시 추가 for category in all_categories: keyword_data[category] = "O" if category in keyword_mappings[keyword] else "" keyword_stats.append(keyword_data) # 사용 횟수 기준으로 정렬 keyword_stats = sorted(keyword_stats, key=lambda x: x['사용 횟수'], reverse=True) # DataFrame으로 변환 df = pd.DataFrame(keyword_stats) return df def process_text_and_download(input_text, debug=False, include_search_volume=True): """ 텍스트를 분석하여 제목을 추출하고 엑셀 파일로 변환하는 함수 """ if not input_text.strip(): return None, None, "텍스트를 입력해주세요." # 제목 추출 titles = extract_titles(input_text, debug) if not titles: return None, None, "추출된 제목이 없습니다. 다른 텍스트를 시도해보세요." # 번호 부여 및 DataFrame 생성 df_titles = pd.DataFrame({ '번호': range(1, len(titles) + 1), '제목': titles }) # 키워드 분석 수행 (카테고리 포함) keyword_df = analyze_keywords_with_categories(titles, input_text, include_search_volume) # 임시 파일로 저장 (제목용) titles_file = tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx') titles_file.close() # 임시 파일로 저장 (키워드용) keywords_file = tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx') keywords_file.close() # 제목 데이터 엑셀 파일로 변환 with pd.ExcelWriter(titles_file.name, engine='xlsxwriter') as writer: df_titles.to_excel(writer, sheet_name='제목 목록', index=False) # 열 너비 자동 조정 worksheet = writer.sheets['제목 목록'] worksheet.set_column('A:A', 5) # 번호 열 worksheet.set_column('B:B', 100) # 제목 열 # 키워드 데이터 엑셀 파일로 변환 with pd.ExcelWriter(keywords_file.name, engine='xlsxwriter') as writer: keyword_df.to_excel(writer, sheet_name='키워드 분석', index=False) # 열 너비 자동 조정 worksheet = writer.sheets['키워드 분석'] worksheet.set_column('A:A', 15) # 키워드 열 worksheet.set_column('B:B', 30) # 등장 순위 열 worksheet.set_column('C:C', 10) # 사용 횟수 열 worksheet.set_column('D:D', 15) # 상위노출 키워드 열 worksheet.set_column('E:E', 10) # PC검색량 열 worksheet.set_column('F:F', 12) # 모바일검색량 열 worksheet.set_column('G:G', 10) # 총검색량 열 # H열부터 카테고리 매트릭스 열 너비 조정 for i, col in enumerate(keyword_df.columns[7:], start=7): worksheet.set_column(f'{chr(65+i)}:{chr(65+i)}', 20) # 노출 카테고리별 키워드 수 계산 exposure_counts = keyword_df['상위노출 키워드'].value_counts().to_dict() top10_count = exposure_counts.get('상위 10개', 0) top20_count = exposure_counts.get('상위 20개', 0) top30_count = exposure_counts.get('상위 30개', 0) top40_count = exposure_counts.get('상위 40개', 0) not_included_count = exposure_counts.get('1페이지 미포함', 0) # 카테고리별 키워드 수 계산 result_text = f"총 {len(titles)}개의 제목이 추출되었습니다.\n\n" for i, title in enumerate(titles, 1): result_text += f"{i}. {title}\n" result_text += f"\n\n키워드 분석 결과 (총 {len(keyword_df)}개 키워드):\n" result_text += f"- 상위 10개 제목에 포함된 키워드: {top10_count}개\n" result_text += f"- 상위 20개 제목에 포함된 키워드: {top20_count}개\n" result_text += f"- 상위 30개 제목에 포함된 키워드: {top30_count}개\n" result_text += f"- 상위 40개 제목에 포함된 키워드: {top40_count}개\n" result_text += f"- 1페이지에 포함되지 않은 키워드: {not_included_count}개\n\n" result_text += f"\n가장 많이 사용된 키워드 (상위 20개):\n" for i, row in keyword_df.head(20).iterrows(): # 해당 키워드가 속한 모든 카테고리 찾기 categories = [] for col in keyword_df.columns[7:]: # 카테고리 열들 if row[col] == "O": categories.append(col) category_text = ", ".join(categories) if categories else "미분류" result_text += f"{row['키워드']} - {row['사용 횟수']}회 등장 ({row['상위노출 키워드']}, PC:{row['PC검색량']}, 모바일:{row['모바일검색량']}, 총:{row['총검색량']}, 카테고리: {category_text})\n" return titles_file.name, keywords_file.name, result_text def create_app(): """ 그라디오 앱 생성 함수 """ with gr.Blocks(title="제품 제목 및 키워드 추출기") as app: gr.Markdown(""" # 텍스트에서 제품 제목 및 키워드 추출기 (네이버 검색량 포함) 제품 목록이 포함된 텍스트를 입력하면 제품 제목을 자동으로 추출하고, 키워드 분석을 수행합니다. ### 기능: 1. 제품 제목 추출 2. 카테고리 추출 (가구/인테리어, 생활/건강, 패션잡화, 디지털/가전, 출산/육아, 스포츠/레저, 화장품/미용, 패션의류, 여가/생활편의, 식품) 3. 추출된 제목에서 키워드 추출 및 분석 4. 키워드 사용 빈도 및 등장 순위 분석 5. 상위 노출 키워드 분석 (상위 10개, 20개, 30개, 40개) 6. **네이버 검색량 조회 (PC검색량, 모바일검색량, 총검색량)** 7. 키워드별 카테고리 분류 및 매트릭스 생성 ### 주요 특징: - "*" 문자 제거, 중복 공백 처리 - 광고 주변 텍스트만 제외하여 정확한 제목 추출 - '해외' 접두사 자동 제거 - 키워드 상위 노출 분석 - 네이버 검색량 병렬 조회 (25개 단위) - 카테고리별 키워드 분류 및 매트릭스 표시 ### 네이버 API 설정: - NAVER_API_KEY 환경 변수 설정 필요 - NAVER_SECRET_KEY 환경 변수 설정 필요 - NAVER_CUSTOMER_ID 환경 변수 설정 필요 """) with gr.Row(): with gr.Column(): input_text = gr.Textbox( label="제목을 추출할 텍스트 입력", placeholder="여기에 제품 목록이 포함된 텍스트를 붙여넣으세요...", lines=15 ) debug_mode = gr.Checkbox(label="디버깅 모드 (상세 로그 출력)") search_volume_checkbox = gr.Checkbox(label="네이버 검색량 조회", value=True) submit_btn = gr.Button("제목 추출 및 키워드 분석") with gr.Column(): output_text = gr.Textbox(label="추출 결과", lines=15) titles_download_btn = gr.File(label="제목 목록 다운로드", file_types=[".xlsx"]) keywords_download_btn = gr.File(label="키워드 분석 다운로드", file_types=[".xlsx"]) def process_wrapper(text, debug, include_search_volume): titles_file, keywords_file, result_text = process_text_and_download(text, debug, include_search_volume) return [titles_file, keywords_file, result_text] submit_btn.click( process_wrapper, inputs=[input_text, debug_mode, search_volume_checkbox], outputs=[titles_download_btn, keywords_download_btn, output_text] ) return app # 앱 실행 if __name__ == "__main__": demo = create_app() demo.launch()