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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
파일 처리 및 API 관련 함수
|
| 3 |
+
"""
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
import zlib
|
| 7 |
+
import zipfile
|
| 8 |
+
import tempfile
|
| 9 |
+
import requests
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Optional, Tuple, List, Dict, Generator
|
| 12 |
+
from xml.etree import ElementTree as ET
|
| 13 |
+
from datetime import datetime
|
| 14 |
+
|
| 15 |
+
from utils import (
|
| 16 |
+
API_URL, API_KEY, GROQ_API_KEY, CATEGORY_CODES,
|
| 17 |
+
OLEFILE_AVAILABLE, PYPDF2_AVAILABLE, PDFPLUMBER_AVAILABLE, GROQ_AVAILABLE,
|
| 18 |
+
extract_region_from_text, extract_region_from_hashtags, classify_org_type,
|
| 19 |
+
parse_deadline, is_ongoing
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
if OLEFILE_AVAILABLE:
|
| 23 |
+
import olefile
|
| 24 |
+
if PYPDF2_AVAILABLE:
|
| 25 |
+
import PyPDF2
|
| 26 |
+
if PDFPLUMBER_AVAILABLE:
|
| 27 |
+
import pdfplumber
|
| 28 |
+
if GROQ_AVAILABLE:
|
| 29 |
+
from groq import Groq
|
| 30 |
+
|
| 31 |
+
import pandas as pd
|
| 32 |
+
from bs4 import BeautifulSoup
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# ============================================================
|
| 36 |
+
# 파일 텍스트 추출 함수
|
| 37 |
+
# ============================================================
|
| 38 |
+
def extract_text_from_hwpx(file_path: str) -> Tuple[Optional[str], Optional[str]]:
|
| 39 |
+
"""HWPX 파일에서 텍스트 추출"""
|
| 40 |
+
try:
|
| 41 |
+
text_parts = []
|
| 42 |
+
with zipfile.ZipFile(file_path, 'r') as zf:
|
| 43 |
+
file_list = zf.namelist()
|
| 44 |
+
section_files = sorted([f for f in file_list if f.startswith('Contents/section') and f.endswith('.xml')])
|
| 45 |
+
if not section_files:
|
| 46 |
+
section_files = sorted([f for f in file_list if 'section' in f.lower() and f.endswith('.xml')])
|
| 47 |
+
for section_file in section_files:
|
| 48 |
+
try:
|
| 49 |
+
with zf.open(section_file) as sf:
|
| 50 |
+
content = sf.read()
|
| 51 |
+
content_str = content.decode('utf-8')
|
| 52 |
+
content_str = re.sub(r'\sxmlns[^"]*"[^"]*"', '', content_str)
|
| 53 |
+
content_str = re.sub(r'<[a-zA-Z]+:', '<', content_str)
|
| 54 |
+
content_str = re.sub(r'</[a-zA-Z]+:', '</', content_str)
|
| 55 |
+
try:
|
| 56 |
+
root = ET.fromstring(content_str)
|
| 57 |
+
texts = []
|
| 58 |
+
for elem in root.iter():
|
| 59 |
+
if elem.tag.endswith('t') or elem.tag == 't':
|
| 60 |
+
if elem.text:
|
| 61 |
+
texts.append(elem.text)
|
| 62 |
+
elif elem.text and elem.text.strip():
|
| 63 |
+
if any(x in elem.tag.lower() for x in ['text', 'run', 'para', 'char']):
|
| 64 |
+
texts.append(elem.text.strip())
|
| 65 |
+
if texts:
|
| 66 |
+
text_parts.append(' '.join(texts))
|
| 67 |
+
except ET.ParseError:
|
| 68 |
+
text_matches = re.findall(r'>([^<]+)<', content.decode('utf-8', errors='ignore'))
|
| 69 |
+
clean_texts = [t.strip() for t in text_matches if t.strip() and len(t.strip()) > 1]
|
| 70 |
+
if clean_texts:
|
| 71 |
+
text_parts.append(' '.join(clean_texts))
|
| 72 |
+
except:
|
| 73 |
+
continue
|
| 74 |
+
if text_parts:
|
| 75 |
+
result = '\n\n'.join(text_parts)
|
| 76 |
+
result = re.sub(r'\s+', ' ', result)
|
| 77 |
+
result = re.sub(r'\n{3,}', '\n\n', result)
|
| 78 |
+
return result.strip(), None
|
| 79 |
+
return None, "HWPX에서 텍스트를 찾을 수 없습니다"
|
| 80 |
+
except zipfile.BadZipFile:
|
| 81 |
+
return None, "유효하지 않은 HWPX 파일"
|
| 82 |
+
except Exception as e:
|
| 83 |
+
return None, f"HWPX 처리 오류: {str(e)}"
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def extract_hwp_section_text(data: bytes) -> Optional[str]:
|
| 87 |
+
"""HWP 섹션 데이터에서 텍스트 추출"""
|
| 88 |
+
texts = []
|
| 89 |
+
pos = 0
|
| 90 |
+
while pos < len(data) - 4:
|
| 91 |
+
try:
|
| 92 |
+
header = int.from_bytes(data[pos:pos+4], 'little')
|
| 93 |
+
tag_id = header & 0x3FF
|
| 94 |
+
size = (header >> 20) & 0xFFF
|
| 95 |
+
pos += 4
|
| 96 |
+
if size == 0xFFF:
|
| 97 |
+
if pos + 4 > len(data):
|
| 98 |
+
break
|
| 99 |
+
size = int.from_bytes(data[pos:pos+4], 'little')
|
| 100 |
+
pos += 4
|
| 101 |
+
if pos + size > len(data):
|
| 102 |
+
break
|
| 103 |
+
record_data = data[pos:pos+size]
|
| 104 |
+
pos += size
|
| 105 |
+
if tag_id == 67 and size > 0:
|
| 106 |
+
text = decode_para_text(record_data)
|
| 107 |
+
if text:
|
| 108 |
+
texts.append(text)
|
| 109 |
+
except:
|
| 110 |
+
pos += 1
|
| 111 |
+
continue
|
| 112 |
+
return '\n'.join(texts) if texts else None
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def decode_para_text(data: bytes) -> Optional[str]:
|
| 116 |
+
"""HWP 문단 텍스트 디코딩"""
|
| 117 |
+
result = []
|
| 118 |
+
i = 0
|
| 119 |
+
while i < len(data) - 1:
|
| 120 |
+
code = int.from_bytes(data[i:i+2], 'little')
|
| 121 |
+
if code == 0:
|
| 122 |
+
pass
|
| 123 |
+
elif code in [1, 2, 3]:
|
| 124 |
+
i += 14
|
| 125 |
+
elif code == 9:
|
| 126 |
+
result.append('\t')
|
| 127 |
+
elif code in [10, 13]:
|
| 128 |
+
result.append('\n')
|
| 129 |
+
elif code == 24:
|
| 130 |
+
result.append('-')
|
| 131 |
+
elif code in [30, 31]:
|
| 132 |
+
result.append(' ')
|
| 133 |
+
elif code >= 32:
|
| 134 |
+
try:
|
| 135 |
+
char = chr(code)
|
| 136 |
+
if char.isprintable() or char in '\n\t ':
|
| 137 |
+
result.append(char)
|
| 138 |
+
except:
|
| 139 |
+
pass
|
| 140 |
+
i += 2
|
| 141 |
+
text = ''.join(result).strip()
|
| 142 |
+
text = re.sub(r'[ \t]+', ' ', text)
|
| 143 |
+
text = re.sub(r'\n{3,}', '\n\n', text)
|
| 144 |
+
return text if len(text) > 2 else None
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def extract_text_from_hwp(file_path: str) -> Tuple[Optional[str], Optional[str]]:
|
| 148 |
+
"""HWP 파일에서 텍스트 추출"""
|
| 149 |
+
if not OLEFILE_AVAILABLE:
|
| 150 |
+
return None, "olefile 모듈 없음"
|
| 151 |
+
try:
|
| 152 |
+
ole = olefile.OleFileIO(file_path)
|
| 153 |
+
if not ole.exists('FileHeader'):
|
| 154 |
+
ole.close()
|
| 155 |
+
return None, "HWP 파일 헤더 없음"
|
| 156 |
+
header_data = ole.openstream('FileHeader').read()
|
| 157 |
+
is_compressed = (header_data[36] & 1) == 1 if len(header_data) > 36 else True
|
| 158 |
+
all_texts = []
|
| 159 |
+
for entry in ole.listdir():
|
| 160 |
+
entry_path = '/'.join(entry)
|
| 161 |
+
if entry_path.startswith('BodyText/Section'):
|
| 162 |
+
try:
|
| 163 |
+
stream_data = ole.openstream(entry).read()
|
| 164 |
+
if is_compressed:
|
| 165 |
+
try:
|
| 166 |
+
stream_data = zlib.decompress(stream_data, -15)
|
| 167 |
+
except:
|
| 168 |
+
try:
|
| 169 |
+
stream_data = zlib.decompress(stream_data)
|
| 170 |
+
except:
|
| 171 |
+
pass
|
| 172 |
+
section_text = extract_hwp_section_text(stream_data)
|
| 173 |
+
if section_text:
|
| 174 |
+
all_texts.append(section_text)
|
| 175 |
+
except:
|
| 176 |
+
continue
|
| 177 |
+
ole.close()
|
| 178 |
+
if all_texts:
|
| 179 |
+
return '\n\n'.join(all_texts).strip(), None
|
| 180 |
+
return None, "텍스트를 찾을 수 없습니다"
|
| 181 |
+
except Exception as e:
|
| 182 |
+
return None, f"olefile 오류: {str(e)}"
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def extract_text_from_pdf(file_path: str) -> Optional[str]:
|
| 186 |
+
"""PDF 파일에서 텍스트 추출"""
|
| 187 |
+
text_parts = []
|
| 188 |
+
if PDFPLUMBER_AVAILABLE:
|
| 189 |
+
try:
|
| 190 |
+
with pdfplumber.open(file_path) as pdf:
|
| 191 |
+
for page in pdf.pages:
|
| 192 |
+
text = page.extract_text()
|
| 193 |
+
if text:
|
| 194 |
+
text_parts.append(text)
|
| 195 |
+
if text_parts:
|
| 196 |
+
return "\n\n".join(text_parts)
|
| 197 |
+
except Exception as e:
|
| 198 |
+
print(f"pdfplumber error: {e}")
|
| 199 |
+
if PYPDF2_AVAILABLE:
|
| 200 |
+
try:
|
| 201 |
+
with open(file_path, 'rb') as f:
|
| 202 |
+
reader = PyPDF2.PdfReader(f)
|
| 203 |
+
for page in reader.pages:
|
| 204 |
+
text = page.extract_text()
|
| 205 |
+
if text:
|
| 206 |
+
text_parts.append(text)
|
| 207 |
+
if text_parts:
|
| 208 |
+
return "\n\n".join(text_parts)
|
| 209 |
+
except Exception as e:
|
| 210 |
+
print(f"PyPDF2 error: {e}")
|
| 211 |
+
return None
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def extract_text_from_file(file_path: str) -> Tuple[Optional[str], Optional[str]]:
|
| 215 |
+
"""파일 유형에 따라 텍스트 추출"""
|
| 216 |
+
ext = Path(file_path).suffix.lower()
|
| 217 |
+
if ext == '.hwp':
|
| 218 |
+
return extract_text_from_hwp(file_path)
|
| 219 |
+
elif ext == '.hwpx':
|
| 220 |
+
return extract_text_from_hwpx(file_path)
|
| 221 |
+
elif ext == '.pdf':
|
| 222 |
+
text = extract_text_from_pdf(file_path)
|
| 223 |
+
if text:
|
| 224 |
+
return text, None
|
| 225 |
+
return None, "PDF 텍스트 추출 실패"
|
| 226 |
+
elif ext in ['.txt', '.md']:
|
| 227 |
+
try:
|
| 228 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 229 |
+
return f.read(), None
|
| 230 |
+
except:
|
| 231 |
+
try:
|
| 232 |
+
with open(file_path, 'r', encoding='cp949') as f:
|
| 233 |
+
return f.read(), None
|
| 234 |
+
except Exception as e:
|
| 235 |
+
return None, f"텍스트 파일 읽기 실패: {e}"
|
| 236 |
+
else:
|
| 237 |
+
return None, f"지원하지 않는 파일 형식: {ext}"
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def extract_zip_files(zip_path: str, extract_dir: str) -> List[str]:
|
| 241 |
+
"""ZIP 파일 압축 해제"""
|
| 242 |
+
extracted_files = []
|
| 243 |
+
try:
|
| 244 |
+
with zipfile.ZipFile(zip_path, 'r') as zf:
|
| 245 |
+
for name in zf.namelist():
|
| 246 |
+
ext = Path(name).suffix.lower()
|
| 247 |
+
if ext in ['.hwp', '.hwpx', '.pdf', '.txt', '.doc', '.docx']:
|
| 248 |
+
try:
|
| 249 |
+
try:
|
| 250 |
+
decoded_name = name.encode('cp437').decode('cp949')
|
| 251 |
+
except:
|
| 252 |
+
decoded_name = name
|
| 253 |
+
safe_name = os.path.basename(decoded_name)
|
| 254 |
+
extract_path = os.path.join(extract_dir, safe_name)
|
| 255 |
+
with zf.open(name) as src, open(extract_path, 'wb') as dst:
|
| 256 |
+
dst.write(src.read())
|
| 257 |
+
extracted_files.append(extract_path)
|
| 258 |
+
except Exception as e:
|
| 259 |
+
print(f"ZIP 파일 추출 오류 ({name}): {e}")
|
| 260 |
+
except Exception as e:
|
| 261 |
+
print(f"ZIP 처리 오류: {e}")
|
| 262 |
+
return extracted_files
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
# ============================================================
|
| 266 |
+
# API 관련 함수
|
| 267 |
+
# ============================================================
|
| 268 |
+
def fetch_all_from_api(category: str = "전체", region: str = "전체(지역)", keyword: str = "") -> Tuple[List[Dict], str]:
|
| 269 |
+
"""API에서 전체 데이터를 페이지네이션으로 수집"""
|
| 270 |
+
if not API_KEY:
|
| 271 |
+
return [], "❌ API 키가 설정되지 않았습니다. (BIZ_API 환경변수)"
|
| 272 |
+
all_items = []
|
| 273 |
+
page_size = 100
|
| 274 |
+
max_pages = 10
|
| 275 |
+
headers = {"User-Agent": "Mozilla/5.0", "Accept": "application/json"}
|
| 276 |
+
hashtags = []
|
| 277 |
+
if category and category != "전체":
|
| 278 |
+
hashtags.append(category)
|
| 279 |
+
if region and region != "전체(지역)":
|
| 280 |
+
hashtags.append(region)
|
| 281 |
+
if keyword and keyword.strip():
|
| 282 |
+
hashtags.append(keyword.strip())
|
| 283 |
+
|
| 284 |
+
for page_idx in range(1, max_pages + 1):
|
| 285 |
+
try:
|
| 286 |
+
params = {"crtfcKey": API_KEY, "dataType": "json", "pageUnit": page_size, "pageIndex": page_idx}
|
| 287 |
+
if category and category != "전체" and category in CATEGORY_CODES:
|
| 288 |
+
if CATEGORY_CODES[category]:
|
| 289 |
+
params["searchLclasId"] = CATEGORY_CODES[category]
|
| 290 |
+
if hashtags:
|
| 291 |
+
params["hashtags"] = ",".join(hashtags)
|
| 292 |
+
response = requests.get(API_URL, params=params, headers=headers, timeout=(15, 60), verify=True)
|
| 293 |
+
response.raise_for_status()
|
| 294 |
+
result = response.json()
|
| 295 |
+
items = []
|
| 296 |
+
json_array = result.get("jsonArray", result)
|
| 297 |
+
if isinstance(json_array, dict):
|
| 298 |
+
items = json_array.get("item", [])
|
| 299 |
+
if isinstance(items, dict):
|
| 300 |
+
items = [items]
|
| 301 |
+
elif isinstance(json_array, list):
|
| 302 |
+
items = json_array
|
| 303 |
+
if not items:
|
| 304 |
+
break
|
| 305 |
+
all_items.extend(items)
|
| 306 |
+
if page_idx == 1 and items:
|
| 307 |
+
total_cnt = items[0].get("totCnt", 0)
|
| 308 |
+
try:
|
| 309 |
+
total_cnt = int(total_cnt)
|
| 310 |
+
except:
|
| 311 |
+
total_cnt = len(items)
|
| 312 |
+
needed_pages = (total_cnt + page_size - 1) // page_size
|
| 313 |
+
max_pages = min(max_pages, needed_pages)
|
| 314 |
+
if len(items) < page_size:
|
| 315 |
+
break
|
| 316 |
+
except requests.exceptions.Timeout:
|
| 317 |
+
return all_items, f"⏱️ 페이지 {page_idx} 요청 시간 초과"
|
| 318 |
+
except requests.exceptions.RequestException as e:
|
| 319 |
+
if all_items:
|
| 320 |
+
break
|
| 321 |
+
return [], f"❌ API 요청 오류: {str(e)[:50]}"
|
| 322 |
+
except Exception as e:
|
| 323 |
+
if all_items:
|
| 324 |
+
break
|
| 325 |
+
return [], f"❌ 오류: {str(e)[:50]}"
|
| 326 |
+
return all_items, ""
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def download_file(url: str, save_dir: str, hint_filename: str = None) -> Tuple[Optional[str], Optional[str]]:
|
| 330 |
+
"""파일 다운로드"""
|
| 331 |
+
try:
|
| 332 |
+
headers = {"User-Agent": "Mozilla/5.0", "Accept": "*/*", "Referer": "https://www.bizinfo.go.kr/"}
|
| 333 |
+
response = requests.get(url, headers=headers, timeout=60, stream=True, verify=False, allow_redirects=True)
|
| 334 |
+
response.raise_for_status()
|
| 335 |
+
cd = response.headers.get('Content-Disposition', '')
|
| 336 |
+
filename = None
|
| 337 |
+
if cd:
|
| 338 |
+
match = re.search(r"filename\*=(?:UTF-8''|utf-8'')(.+)", cd, re.IGNORECASE)
|
| 339 |
+
if match:
|
| 340 |
+
from urllib.parse import unquote
|
| 341 |
+
filename = unquote(match.group(1))
|
| 342 |
+
else:
|
| 343 |
+
match = re.search(r'filename=(["\']?)(.+?)\1(?:;|$)', cd)
|
| 344 |
+
if match:
|
| 345 |
+
filename = match.group(2)
|
| 346 |
+
if not filename and hint_filename:
|
| 347 |
+
filename = hint_filename
|
| 348 |
+
if not filename:
|
| 349 |
+
from urllib.parse import urlparse
|
| 350 |
+
parsed = urlparse(url)
|
| 351 |
+
filename = parsed.path.split('/')[-1]
|
| 352 |
+
if not filename or '.' not in filename:
|
| 353 |
+
content_type = response.headers.get('Content-Type', '').lower()
|
| 354 |
+
if 'pdf' in content_type:
|
| 355 |
+
filename = f"document_{hash(url) % 10000}.pdf"
|
| 356 |
+
elif 'hwp' in content_type:
|
| 357 |
+
filename = f"document_{hash(url) % 10000}.hwp"
|
| 358 |
+
else:
|
| 359 |
+
filename = f"file_{hash(url) % 10000}.bin"
|
| 360 |
+
filename = re.sub(r'[<>:"/\\|?*]', '_', filename)
|
| 361 |
+
file_path = os.path.join(save_dir, filename)
|
| 362 |
+
with open(file_path, 'wb') as f:
|
| 363 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 364 |
+
if chunk:
|
| 365 |
+
f.write(chunk)
|
| 366 |
+
if os.path.getsize(file_path) == 0:
|
| 367 |
+
os.remove(file_path)
|
| 368 |
+
return None, "빈 파일이 다운로드됨"
|
| 369 |
+
return file_path, None
|
| 370 |
+
except Exception as e:
|
| 371 |
+
return None, f"다운로드 실패: {str(e)}"
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def call_groq_api_stream(messages: List[Dict]) -> Generator[str, None, None]:
|
| 375 |
+
"""Groq API 스트리밍 호출"""
|
| 376 |
+
if not GROQ_AVAILABLE:
|
| 377 |
+
yield "❌ Groq 라이브러리가 설치되지 않았습니다."
|
| 378 |
+
return
|
| 379 |
+
if not GROQ_API_KEY:
|
| 380 |
+
yield "❌ GROQ_API_KEY 환경변수가 설정되지 않았습니다."
|
| 381 |
+
return
|
| 382 |
+
try:
|
| 383 |
+
client = Groq(api_key=GROQ_API_KEY)
|
| 384 |
+
completion = client.chat.completions.create(
|
| 385 |
+
model="llama-3.3-70b-versatile",
|
| 386 |
+
messages=messages,
|
| 387 |
+
temperature=0.3,
|
| 388 |
+
max_tokens=4096,
|
| 389 |
+
stream=True,
|
| 390 |
+
)
|
| 391 |
+
for chunk in completion:
|
| 392 |
+
if chunk.choices[0].delta.content:
|
| 393 |
+
yield chunk.choices[0].delta.content
|
| 394 |
+
except Exception as e:
|
| 395 |
+
yield f"❌ API 오류: {str(e)}"
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def fetch_announcement_detail(url: str) -> Tuple[str, List[Dict]]:
|
| 399 |
+
"""공고 상세 페이지에서 본문과 첨부파일 정보 추출"""
|
| 400 |
+
try:
|
| 401 |
+
headers = {
|
| 402 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
| 403 |
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
|
| 404 |
+
"Accept-Language": "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7",
|
| 405 |
+
}
|
| 406 |
+
response = requests.get(url, headers=headers, timeout=30, verify=False)
|
| 407 |
+
response.raise_for_status()
|
| 408 |
+
html_text = response.text
|
| 409 |
+
soup = BeautifulSoup(html_text, 'html.parser')
|
| 410 |
+
content_text = ""
|
| 411 |
+
tables = soup.find_all('table')
|
| 412 |
+
for table in tables:
|
| 413 |
+
text = table.get_text(separator='\n', strip=True)
|
| 414 |
+
if '사업개요' in text or '지원대상' in text or '신청기간' in text:
|
| 415 |
+
content_text += text + "\n\n"
|
| 416 |
+
main_content = soup.find('div', {'id': 'container'}) or soup.find('main') or soup.find('article')
|
| 417 |
+
if main_content and not content_text:
|
| 418 |
+
content_text = main_content.get_text(separator='\n', strip=True)
|
| 419 |
+
attachments = []
|
| 420 |
+
for a_tag in soup.find_all('a', href=True):
|
| 421 |
+
href = a_tag.get('href', '')
|
| 422 |
+
href_clean = re.sub(r';jsessionid=[^?]*', '', href)
|
| 423 |
+
if 'getImageFile.do' in href_clean or 'fileDown' in href_clean or 'atchFileId' in href_clean:
|
| 424 |
+
filename = a_tag.get_text(strip=True)
|
| 425 |
+
if filename in ['다운로드', '바로보기', '내려받기', '']:
|
| 426 |
+
parent = a_tag.parent
|
| 427 |
+
if parent:
|
| 428 |
+
parent_text = parent.get_text(separator='|', strip=True)
|
| 429 |
+
parts = [p.strip() for p in parent_text.split('|') if p.strip()]
|
| 430 |
+
for part in parts:
|
| 431 |
+
if part not in ['다운로드', '바로보기', '내려받기'] and ('.' in part):
|
| 432 |
+
filename = part
|
| 433 |
+
break
|
| 434 |
+
title = a_tag.get('title', '')
|
| 435 |
+
if title and '첨부파일' in title:
|
| 436 |
+
match = re.search(r'첨부파일\s+(.+?)\s+다운로드', title)
|
| 437 |
+
if match:
|
| 438 |
+
filename = match.group(1)
|
| 439 |
+
if not filename or filename in ['다운로드', '바로보기', '내려받기']:
|
| 440 |
+
filename = f"첨부파일_{len(attachments)+1}"
|
| 441 |
+
if href_clean.startswith('/'):
|
| 442 |
+
full_url = f"https://www.bizinfo.go.kr{href_clean}"
|
| 443 |
+
elif href_clean.startswith('http'):
|
| 444 |
+
full_url = href_clean
|
| 445 |
+
else:
|
| 446 |
+
continue
|
| 447 |
+
ext = Path(filename).suffix.lower()
|
| 448 |
+
if not ext:
|
| 449 |
+
ext = '.unknown'
|
| 450 |
+
if not any(att['url'] == full_url for att in attachments):
|
| 451 |
+
attachments.append({
|
| 452 |
+
"filename": filename,
|
| 453 |
+
"url": full_url,
|
| 454 |
+
"type": ext[1:] if ext.startswith('.') else ext
|
| 455 |
+
})
|
| 456 |
+
return content_text, attachments
|
| 457 |
+
except Exception as e:
|
| 458 |
+
import traceback
|
| 459 |
+
return f"상세 정보 조회 실패: {str(e)}\n{traceback.format_exc()}", []
|
utils.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import requests
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from typing import Optional, Tuple, List, Dict, Generator
|
| 5 |
+
import os
|
| 6 |
+
import tempfile
|
| 7 |
+
import zipfile
|
| 8 |
+
import re
|
| 9 |
+
import json
|
| 10 |
+
import zlib
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from bs4 import BeautifulSoup
|
| 13 |
+
import urllib3
|
| 14 |
+
from datetime import datetime, timedelta
|
| 15 |
+
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
import olefile
|
| 19 |
+
OLEFILE_AVAILABLE = True
|
| 20 |
+
except ImportError:
|
| 21 |
+
OLEFILE_AVAILABLE = False
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
import PyPDF2
|
| 25 |
+
PYPDF2_AVAILABLE = True
|
| 26 |
+
except ImportError:
|
| 27 |
+
PYPDF2_AVAILABLE = False
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
import pdfplumber
|
| 31 |
+
PDFPLUMBER_AVAILABLE = True
|
| 32 |
+
except ImportError:
|
| 33 |
+
PDFPLUMBER_AVAILABLE = False
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
from groq import Groq
|
| 37 |
+
GROQ_AVAILABLE = True
|
| 38 |
+
except ImportError:
|
| 39 |
+
GROQ_AVAILABLE = False
|
| 40 |
+
|
| 41 |
+
from xml.etree import ElementTree as ET
|
| 42 |
+
|
| 43 |
+
# ============================================================
|
| 44 |
+
# 환경변수 및 API 설정
|
| 45 |
+
# ============================================================
|
| 46 |
+
API_URL = "https://www.bizinfo.go.kr/uss/rss/bizinfoApi.do"
|
| 47 |
+
API_KEY = os.getenv("BIZ_API", "")
|
| 48 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
|
| 49 |
+
|
| 50 |
+
# ============================================================
|
| 51 |
+
# 상수 정의
|
| 52 |
+
# ============================================================
|
| 53 |
+
CATEGORY_CODES = {
|
| 54 |
+
"전체": "", "금융": "01", "기술": "02", "인력": "03", "수출": "04",
|
| 55 |
+
"내수": "05", "창업": "06", "경영": "07", "기타": "09"
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
REGION_LIST = [
|
| 59 |
+
"전체(지역)", "서울", "부산", "대구", "인천", "광주", "대전", "울산", "세종",
|
| 60 |
+
"경기", "강원", "충북", "충남", "전북", "전남", "경북", "경남", "제주"
|
| 61 |
+
]
|
| 62 |
+
|
| 63 |
+
SIDO_LIST = [
|
| 64 |
+
"서울특별시", "부산광역시", "대구광역시", "인천광역시", "광주광역시",
|
| 65 |
+
"대전광역시", "울산광역시", "세종특별자치시", "경기도", "강원특별자치도",
|
| 66 |
+
"충청북도", "충청남도", "전북특별자치도", "전라남도", "경상북도", "경상남도", "제주특별자치도"
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
ORG_TYPE_OPTIONS = ["전체", "중앙부처", "지자체"]
|
| 70 |
+
SORT_OPTIONS = ["등록일순", "마감일순"]
|
| 71 |
+
STATUS_OPTIONS = ["진행중", "전체(지난공고포함)"]
|
| 72 |
+
|
| 73 |
+
COMPANY_TYPE_OPTIONS = ["개인사업자", "법인사업자", "비영리법인", "조합", "협동조합", "사회적기업"]
|
| 74 |
+
CORP_TYPE_OPTIONS = ["해당없음(개인)", "주식회사", "유한회사", "유한책임회사", "합자회사", "합명회사"]
|
| 75 |
+
COMPANY_SIZE_OPTIONS = ["소기업", "중기업", "중견기업", "대기업"]
|
| 76 |
+
|
| 77 |
+
INDUSTRY_MAJOR_OPTIONS = [
|
| 78 |
+
"A. 농업, 임업 및 어업", "B. 광업", "C. 제조업",
|
| 79 |
+
"D. 전기, 가스, 증기 및 공기조절 공급업", "E. 수도, 하수 및 폐기물 처리, 원료 재생업",
|
| 80 |
+
"F. 건설업", "G. 도매 및 소매업", "H. 운수 및 창고업", "I. 숙박 및 음식점업",
|
| 81 |
+
"J. 정보통신업", "K. 금융 및 보험업", "L. 부동산업", "M. 전문, 과학 및 기술 서비스업",
|
| 82 |
+
"N. 사업시설 관리, 사업 지원 및 임대 서비스업", "P. 교육 서비스업",
|
| 83 |
+
"Q. 보건업 및 사회복지 서비스업", "R. 예술, 스포츠 및 여가관련 서비스업"
|
| 84 |
+
]
|
| 85 |
+
|
| 86 |
+
CORE_INDUSTRY_OPTIONS = [
|
| 87 |
+
"인공지능(AI)", "반도체", "바이오/헬스케어", "미래자동차(전기차/자율주행)",
|
| 88 |
+
"로봇", "이차전지", "디스플레이", "5G/6G 통신", "양자기술", "우주항공"
|
| 89 |
+
]
|
| 90 |
+
|
| 91 |
+
NATIONAL_STRATEGIC_TECH = [
|
| 92 |
+
"반도체·디스플레이", "이차전지", "첨단모빌리티", "차세대 원자력", "첨단바이오",
|
| 93 |
+
"우주항공·해양", "수소", "사이버보안", "인공지능", "차세대 통신", "첨단로봇·제조", "양자"
|
| 94 |
+
]
|
| 95 |
+
|
| 96 |
+
CREDIT_GRADE_OPTIONS = ["AAA", "AA+", "AA", "AA-", "A+", "A", "A-", "BBB+", "BBB", "BBB-",
|
| 97 |
+
"BB+", "BB", "BB-", "B+", "B", "B-", "CCC", "CC", "C", "D", "미평가"]
|
| 98 |
+
TCB_GRADE_OPTIONS = ["T1", "T2", "T3", "T4", "T5", "T6", "T7", "T8", "T9", "T10", "미평가"]
|
| 99 |
+
|
| 100 |
+
ISO_CERT_OPTIONS = [
|
| 101 |
+
"ISO 9001 (품질경영)", "ISO 14001 (환경경영)", "ISO 27001 (정보보안)",
|
| 102 |
+
"ISO 45001 (안전보건)", "ISO 22000 (식품안전)", "ISO 13485 (의료기기)", "IATF 16949 (자동차)"
|
| 103 |
+
]
|
| 104 |
+
|
| 105 |
+
CENTRAL_GOV_KEYWORDS = [
|
| 106 |
+
"부", "처", "청", "원", "위원회", "중소벤처기업부", "산업통상", "과학기술", "고용노동",
|
| 107 |
+
"농림축산", "해양수산", "환경부", "국토교통", "문화체육", "보건복지", "행정안전",
|
| 108 |
+
"기획재정", "외교부", "법무부", "국방부", "교육부", "통일부", "여성가족",
|
| 109 |
+
"특허청", "관세청", "조달청", "통계청", "기상청", "소방청", "경찰청",
|
| 110 |
+
"산림청", "농촌진흥청", "식품의약품안전처", "방위사업청", "병무청", "국세청",
|
| 111 |
+
"대한무역투자진흥공사", "한국산업기술진흥원", "한국에너지공단", "한국인터넷진흥원",
|
| 112 |
+
"정보통신산업진흥원", "한국콘텐츠진흥원", "한국관광공사", "대한상공회의소",
|
| 113 |
+
"중소기업중앙회", "기��보증기금", "신용보증기금", "한국산업안전보건공단"
|
| 114 |
+
]
|
| 115 |
+
|
| 116 |
+
LOCAL_GOV_KEYWORDS = [
|
| 117 |
+
"도", "시", "군", "구청", "특별시", "광역시", "특별자치", "자치도", "자치시",
|
| 118 |
+
"서울", "부산", "대구", "인천", "광주", "대전", "울산", "세종",
|
| 119 |
+
"경기", "강원", "충북", "충남", "전북", "전남", "경북", "경남", "제주",
|
| 120 |
+
"테크노파크", "TP", "경제진흥원", "창조경제", "지역혁신", "소상공인진흥"
|
| 121 |
+
]
|
| 122 |
+
|
| 123 |
+
REGION_MATCH_KEYWORDS = {
|
| 124 |
+
"서울": ["서울", "서울특별시", "서울시", "SBA", "서울산업진흥원", "서울경제진흥원",
|
| 125 |
+
"서울신용보증재단", "서울테크노파크", "서울창업허브", "SH공사"],
|
| 126 |
+
"부산": ["부산", "부산광역시", "부산시", "부산경제진흥원", "부산테크노파크"],
|
| 127 |
+
"대구": ["대구", "대구광역시", "대구시", "대구경북", "대구테크노파크"],
|
| 128 |
+
"인천": ["인천", "인천광역시", "인천시", "인천경제자유구역", "인천테크노파크"],
|
| 129 |
+
"광주": ["광주", "광주광역시", "광주시", "광주전남", "광주테크노파크"],
|
| 130 |
+
"대전": ["대전", "대전광역시", "대전시", "대전테크노파크", "대전경제통상진흥원"],
|
| 131 |
+
"울산": ["울산", "울산광역시", "울산시", "울산테크노파크", "울산경제진흥원"],
|
| 132 |
+
"세종": ["세종", "세종특별자치시", "세종시", "세종테크노파크"],
|
| 133 |
+
"경기": ["경기", "경기도", "경기TP", "경기테크노파크", "경기경제과학진흥원",
|
| 134 |
+
"수원", "성남", "고양", "용인", "부천", "안산", "안양",
|
| 135 |
+
"남양주", "화성", "평택", "의정부", "시흥", "파주", "김포", "광명", "광주시",
|
| 136 |
+
"군포", "하남", "오산", "이천", "안성", "의왕", "양평", "여주", "과천",
|
| 137 |
+
"구리", "포천", "동두천", "가평", "연천"],
|
| 138 |
+
"강원": ["강원", "강원도", "강원특별자치도", "강원TP", "강원테크노파크", "강원경제진흥원",
|
| 139 |
+
"춘천", "원주", "강릉", "동해", "태백",
|
| 140 |
+
"속초", "삼척", "홍천", "횡성", "영월", "평창", "정선", "철원", "화천",
|
| 141 |
+
"양구", "인제", "고성", "양양"],
|
| 142 |
+
"충북": ["충북", "충청북도", "충북TP", "충북테크노파크", "충청북도기업진흥원",
|
| 143 |
+
"청주", "충주", "제천", "보은", "옥천", "영동", "증평",
|
| 144 |
+
"진천", "괴산", "음성", "단양"],
|
| 145 |
+
"충남": ["충남", "충청남도", "충남TP", "충남테크노파크", "충남경제진흥원",
|
| 146 |
+
"천안", "공주", "보령", "아산", "서산", "논산", "계룡",
|
| 147 |
+
"당진", "금산", "부여", "서천", "청양", "홍성", "예산", "태안"],
|
| 148 |
+
"전북": ["전북", "전라북도", "전북특별자치도", "전북TP", "전북테크노파크", "전북경제통상진흥원",
|
| 149 |
+
"전주", "군산", "익산", "정읍", "남원",
|
| 150 |
+
"김제", "완주", "진안", "무주", "장수", "임실", "순창", "고창", "부안"],
|
| 151 |
+
"전남": ["전남", "전라남도", "전남TP", "전남테크노파크", "전남경제통상진흥원",
|
| 152 |
+
"목포", "여수", "순천", "나주", "광양", "담양", "곡성",
|
| 153 |
+
"구례", "고흥", "보성", "화순", "장흥", "강진", "해남", "영암", "무안",
|
| 154 |
+
"함평", "영광", "장성", "완도", "진도", "신안"],
|
| 155 |
+
"경북": ["경북", "경상북도", "경북TP", "경북테크노파크", "경북경제진흥원",
|
| 156 |
+
"포항", "경주", "김천", "안동", "구미", "영주", "영천",
|
| 157 |
+
"상주", "문경", "경산", "군위", "의성", "청송", "영양", "영덕", "청도",
|
| 158 |
+
"고령", "성주", "칠곡", "예천", "봉화", "울진", "울릉"],
|
| 159 |
+
"경남": ["경남", "경상남도", "경남TP", "경남테크노파크", "경남경제진흥원",
|
| 160 |
+
"창원", "진주", "통영", "사천", "김해", "밀양", "거제",
|
| 161 |
+
"양산", "의령", "함안", "창녕", "고성", "남해", "하동", "산청", "함양",
|
| 162 |
+
"거창", "합천"],
|
| 163 |
+
"제주": ["제주", "제주도", "제주특별자치도", "제주시", "서귀포", "제주TP", "제주테크노파크"]
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# ============================================================
|
| 168 |
+
# 유틸리티 함수
|
| 169 |
+
# ============================================================
|
| 170 |
+
def calculate_age(birth_date: str) -> int:
|
| 171 |
+
"""생년월일로 만나이 계산"""
|
| 172 |
+
if not birth_date:
|
| 173 |
+
return 0
|
| 174 |
+
try:
|
| 175 |
+
birth = datetime.strptime(birth_date, "%Y-%m-%d")
|
| 176 |
+
today = datetime.now()
|
| 177 |
+
age = today.year - birth.year
|
| 178 |
+
if (today.month, today.day) < (birth.month, birth.day):
|
| 179 |
+
age -= 1
|
| 180 |
+
return age
|
| 181 |
+
except:
|
| 182 |
+
return 0
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def calculate_company_age(establish_date: str) -> Tuple[int, int]:
|
| 186 |
+
"""설립일로 업력 계산 (년, 월)"""
|
| 187 |
+
if not establish_date:
|
| 188 |
+
return 0, 0
|
| 189 |
+
try:
|
| 190 |
+
establish = datetime.strptime(establish_date, "%Y-%m-%d")
|
| 191 |
+
today = datetime.now()
|
| 192 |
+
years = today.year - establish.year
|
| 193 |
+
months = today.month - establish.month
|
| 194 |
+
if months < 0:
|
| 195 |
+
years -= 1
|
| 196 |
+
months += 12
|
| 197 |
+
return years, months
|
| 198 |
+
except:
|
| 199 |
+
return 0, 0
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def extract_region_from_text(text: str) -> Optional[str]:
|
| 203 |
+
"""텍스트에서 지역 정보 추출"""
|
| 204 |
+
if not text:
|
| 205 |
+
return None
|
| 206 |
+
text = text.strip()
|
| 207 |
+
bracket_match = re.match(r'\[([가-힣]+)\]', text)
|
| 208 |
+
if bracket_match:
|
| 209 |
+
region_text = bracket_match.group(1)
|
| 210 |
+
for region, keywords in REGION_MATCH_KEYWORDS.items():
|
| 211 |
+
for kw in keywords:
|
| 212 |
+
if kw in region_text:
|
| 213 |
+
return region
|
| 214 |
+
for region in ["서울", "부산", "대구", "인천", "광주", "대전", "울산", "세종"]:
|
| 215 |
+
keywords = REGION_MATCH_KEYWORDS.get(region, [])
|
| 216 |
+
for kw in keywords:
|
| 217 |
+
if kw in text:
|
| 218 |
+
if region == "광주" and ("경기" in text or "경기도" in text):
|
| 219 |
+
continue
|
| 220 |
+
return region
|
| 221 |
+
for region in ["경기", "강원", "충북", "충남", "전북", "전남", "경북", "경남", "제주"]:
|
| 222 |
+
keywords = REGION_MATCH_KEYWORDS.get(region, [])
|
| 223 |
+
for kw in keywords:
|
| 224 |
+
if kw in text:
|
| 225 |
+
return region
|
| 226 |
+
return None
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def extract_region_from_hashtags(hash_tags: str) -> Optional[str]:
|
| 230 |
+
"""해시태그에서 지역 정보 추출"""
|
| 231 |
+
if not hash_tags:
|
| 232 |
+
return None
|
| 233 |
+
tags = [t.strip() for t in hash_tags.split(",")]
|
| 234 |
+
region_names = list(REGION_MATCH_KEYWORDS.keys())
|
| 235 |
+
for tag in tags:
|
| 236 |
+
if tag in region_names:
|
| 237 |
+
return tag
|
| 238 |
+
for region in region_names:
|
| 239 |
+
if region in tag:
|
| 240 |
+
return region
|
| 241 |
+
return None
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def classify_org_type(author: str) -> str:
|
| 245 |
+
"""소관기관명을 기반으로 기관유형 분류"""
|
| 246 |
+
if not author:
|
| 247 |
+
return "기타"
|
| 248 |
+
author = author.strip()
|
| 249 |
+
if author.startswith("[") and "]" in author:
|
| 250 |
+
return "지자체"
|
| 251 |
+
for keyword in LOCAL_GOV_KEYWORDS:
|
| 252 |
+
if keyword in author:
|
| 253 |
+
is_central = any(central_kw in author and len(central_kw) > 2 for central_kw in CENTRAL_GOV_KEYWORDS)
|
| 254 |
+
if not is_central:
|
| 255 |
+
return "지자체"
|
| 256 |
+
for keyword in CENTRAL_GOV_KEYWORDS:
|
| 257 |
+
if keyword in author:
|
| 258 |
+
return "중앙부처"
|
| 259 |
+
return "중앙부처"
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def parse_deadline(req_dt: str) -> Optional[datetime]:
|
| 263 |
+
"""신청기간에서 마감일 추출"""
|
| 264 |
+
if not req_dt:
|
| 265 |
+
return None
|
| 266 |
+
try:
|
| 267 |
+
if "~" in req_dt:
|
| 268 |
+
end_date_str = req_dt.split("~")[-1].strip()
|
| 269 |
+
else:
|
| 270 |
+
end_date_str = req_dt.strip()
|
| 271 |
+
end_date_str = re.sub(r'[^0-9]', '', end_date_str)
|
| 272 |
+
if len(end_date_str) >= 8:
|
| 273 |
+
return datetime.strptime(end_date_str[:8], "%Y%m%d")
|
| 274 |
+
except:
|
| 275 |
+
pass
|
| 276 |
+
return None
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def is_ongoing(req_dt: str) -> bool:
|
| 280 |
+
"""진행중 공고인지 확인"""
|
| 281 |
+
if not req_dt:
|
| 282 |
+
return True
|
| 283 |
+
if any(kw in req_dt for kw in ["소진", "추후", "상시", "별도"]):
|
| 284 |
+
return True
|
| 285 |
+
deadline = parse_deadline(req_dt)
|
| 286 |
+
if deadline:
|
| 287 |
+
return deadline >= datetime.now()
|
| 288 |
+
return True
|