AutoPercenty3/test/kiprisAPI.py

116 lines
5.6 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}")
def parse_xml(self, xml_data, status):
# XML 데이터 파싱
root = ET.fromstring(xml_data)
total_items = 0
status_registered = 0
status_published = 0
# 'body/items/item' 경로에 맞춰 'item' 태그를 순회하면서 필요한 데이터 추출
for i, item in enumerate(root.findall('.//body/items/item')):
total_items += 1
application_status = item.find('applicationStatus').text if item.find('applicationStatus') is not None else None
product_category = item.find('classificationCode').text if item.find('classificationCode') is not None else None
if product_category:
category_desc = self.add_category_description(product_category) if product_category else "No category description"
else:
category_desc = None
# 각 상태의 개수를 카운트
if application_status == "등록":
status_registered += 1
if application_status == "공개":
status_published += 1
# 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
}
# self.results.append(result)
# 상태 개수와 총 아이템 개수 출력
logger.debug(f"검색된 item 총 개수: {total_items}")
self.results['total_count'] = total_items
logger.debug(f"등록 상태인 item 개수: {status_registered}")
logger.debug(f"공개 상태인 item 개수: {status_published}")
def get_results(self):
return self.results
def run(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)
self.parse_xml(xml_data, status)
except Exception as e:
logger.error(f"API 요청 중 에러발생 : {e}")
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)