AutoPercenty3/test/kiprisAPI.py

124 lines
6.0 KiB
Python

import xml.etree.ElementTree as ET
import requests, json
import logging
# 로거 인스턴스 가져오기
logger = logging.getLogger('default_logger')
class Kipris_API:
def __init__(self, apikey=None):
self.url = 'http://kipo-api.kipi.or.kr/openapi/service/trademarkInfoSearchService/getWordSearch'
self.apikey = apikey
self.results = []
filename = 'kiprisCategories.json'
self.category_description = self.load_category_descriptions(filename)
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:
logger.error(f"키프리스 요청 중 에러발생 : {e}", 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
})
# 결과 확인용 로그 출력
logger.debug(f"{len(self.results)}개의 결과가 '등록' 또는 '공개' 상태로 검색됨.")
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': ''
}
logger.debug(f"Search params: {params}")
try:
xml_data = self.fetch_and_decode(params)
if xml_data:
self.parse_xml(xml_data, status)
else:
logger.error("API 응답이 없습니다.")
return {}
except Exception as e:
logger.error(f"API 요청 중 에러 발생: {e}", 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)