142 lines
6.9 KiB
Python
142 lines
6.9 KiB
Python
import xml.etree.ElementTree as ET
|
|
import requests, json
|
|
import os, sys
|
|
import logging
|
|
|
|
class Kipris_API:
|
|
def __init__(self, logger, apikey=None):
|
|
self.logger = logger
|
|
self.url = 'http://kipo-api.kipi.or.kr/openapi/service/trademarkInfoSearchService/getWordSearch'
|
|
self.apikey = apikey
|
|
self.results = []
|
|
|
|
self.base_dir = self.get_base_dir()
|
|
self.kipris_cat_path = os.path.join(self.base_dir, 'kiprisCategories.json')
|
|
|
|
self.category_description = self.load_category_descriptions(self.kipris_cat_path)
|
|
|
|
|
|
def get_base_dir(self):
|
|
"""
|
|
실행 환경에 따라 base_dir을 설정하는 메서드.
|
|
cx_Freeze로 패키징된 경우 실행 파일의 경로, 일반 Python 환경일 경우 __file__을 기준으로 설정.
|
|
"""
|
|
if getattr(sys, 'frozen', False): # 패키징된 경우
|
|
base_dir = os.path.dirname(sys.executable)
|
|
internal_dir = os.path.join(base_dir, '_internal') # _internal 디렉토리 포함
|
|
if os.path.exists(internal_dir): # _internal 디렉토리가 존재하면 base_dir로 설정
|
|
return internal_dir
|
|
|
|
else: # 일반 Python 실행 환경
|
|
base_dir = os.path.dirname(os.path.abspath(__file__))
|
|
return base_dir
|
|
|
|
def fetch_and_decode(self, params):
|
|
# API 요청 및 응답 받기
|
|
try:
|
|
response = requests.get(self.url, params=params)
|
|
decoded_data = response.content.decode('utf-8')
|
|
return decoded_data
|
|
except Exception as e:
|
|
self.logger.log(f'키프리스 요청 중 에러발생 : {e}', level=logging.ERROR, exc_info=True)
|
|
|
|
def parse_xml(self, xml_data, status):
|
|
"""XML 데이터 파싱 및 결과 저장"""
|
|
root = ET.fromstring(xml_data)
|
|
|
|
for i, item in enumerate(root.findall('.//body/items/item')):
|
|
application_status = item.find('applicationStatus').text if item.find('applicationStatus') is not None else None
|
|
|
|
# 필요한 데이터 필드 추출
|
|
if application_status in status:
|
|
title = item.find('title').text if item.find('title') is not None else None
|
|
registration_date = item.find('registrationDate').text if item.find('registrationDate') is not None else None
|
|
applicant_name = item.find('applicantName').text if item.find('applicantName') is not None else None
|
|
classification_code = item.find('classificationCode').text if item.find('classificationCode') is not None else None
|
|
category_desc = self.add_category_description(classification_code) if classification_code else None
|
|
|
|
# 결과 리스트에 추가
|
|
self.results.append({
|
|
"title": title,
|
|
"registration_date": registration_date,
|
|
"applicant_name": applicant_name,
|
|
"classification_code": classification_code,
|
|
"category_description": category_desc,
|
|
"application_status": application_status
|
|
})
|
|
|
|
# 결과 확인용 로그 출력
|
|
self.logger.log(f"총 {len(self.results)}개의 결과가 '등록' 또는 '공개' 상태로 검색됨.", level=logging.ERROR)
|
|
def get_results(self):
|
|
"""결과 반환"""
|
|
return self.results
|
|
|
|
|
|
# if application_status in ["등록", "공개"]:
|
|
# if application_status in status: # status는 self.set_status 리스트를 참조
|
|
|
|
# self.results[f"result_{i+1}"] = {
|
|
# "index_no": item.find('indexNo').text if item.find('indexNo') is not None else None,
|
|
# "application_number": item.find('applicationNumber').text if item.find('applicationNumber') is not None else None,
|
|
# "application_date": item.find('applicationDate').text if item.find('applicationDate') is not None else None,
|
|
# "publication_number": item.find('publicationNumber').text if item.find('publicationNumber') is not None else None,
|
|
# "publication_date": item.find('publicationDate').text if item.find('publicationDate') is not None else None,
|
|
# "registration_date": item.find('registrationDate').text if item.find('registrationDate') is not None else None,
|
|
# "registration_number": item.find('registrationNumber').text if item.find('registrationNumber') is not None else None,
|
|
# "applicant_name": item.find('applicantName').text if item.find('applicantName') is not None else None,
|
|
# "agent_name": item.find('agentName').text if item.find('agentName') is not None else None,
|
|
# "title": item.find('title').text if item.find('title') is not None else None,
|
|
# "drawing_url": item.find('drawing').text if item.find('drawing') is not None else None,
|
|
# "big_drawing_url": item.find('bigDrawing').text if item.find('bigDrawing') is not None else None,
|
|
# "full_text": item.find('fullText').text if item.find('fullText') is not None else None,
|
|
# "application_status": application_status,
|
|
# "classification_code": item.find('classificationCode').text if item.find('classificationCode') is not None else None,
|
|
# "category_description": category_desc
|
|
# }
|
|
|
|
|
|
def search_trademark(self, keyword, status=['등록', '공개']):
|
|
"""키워드로 상표 검색 후 결과 반환"""
|
|
params = {
|
|
'serviceKey': self.apikey,
|
|
'searchString': keyword,
|
|
'searchRecentYear': '0',
|
|
'title': '',
|
|
'fullText': '',
|
|
'drawing': '',
|
|
'bigDrawing': ''
|
|
}
|
|
self.logger.log(f'Search params: {params}', level=logging.ERROR)
|
|
|
|
try:
|
|
xml_data = self.fetch_and_decode(params)
|
|
if xml_data:
|
|
self.parse_xml(xml_data, status)
|
|
else:
|
|
self.logger.log(f'API 응답이 없습니다.', level=logging.ERROR)
|
|
|
|
return {}
|
|
except Exception as e:
|
|
self.logger.log(f'API 요청 중 에러 발생: {e}', level=logging.ERROR, exc_info=True)
|
|
return {}
|
|
|
|
return self.get_results()
|
|
|
|
def close_Kipris(self):
|
|
pass
|
|
|
|
def load_category_descriptions(self, filename):
|
|
"""JSON 파일에서 카테고리 설명을 로드합니다."""
|
|
with open(filename, 'r', encoding='utf-8') as file:
|
|
return json.load(file)
|
|
|
|
def add_category_description(self, category_code):
|
|
"""각 분류 코드를 설명과 함께 포맷합니다."""
|
|
descriptions = []
|
|
codes = category_code.split('|')
|
|
for code in codes:
|
|
description = self.category_description.get(code, "카테고리 설명을 찾을 수 없습니다.")
|
|
descriptions.append(f"[{code}] - {description}")
|
|
return "; ".join(descriptions)
|
|
|