Update app.py
Browse files1232 unmodified lines678910111 unmodified line131415161718192021222324252627282930313233342 unmodified lines37383940414243444546474849505152535455565758592 unmodified lines6263646566672 unmodified lines707172737475767778799 unmodified lines899091929394959697982 unmodified lines1011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461473 unmodified lines1511521531541551561571581591601611621631641651661671689 unmodified lines1781791801811821831841851861871881891901911921931941 unmodified line1961971981992002016 unmodified lines2082092102112122132142152162172182192203 unmodified lines2242252262272282292302312322332342352362372382392402412422432442452462472482492505 unmodified lines2562572582592602612622632642652 unmodified lines2682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043051 unmodified line3073083093103113123133143153163173183193203213223233243252 unmodified lines3283293303313323333343353363373383393408 unmodified lines3493503513523533543553563573583593603613623633643653663677 unmodified lines37537637737837938038138238338438538638710 unmodified lines3983994004014024038 unmodified lines4124134144154164179 unmodified lines4274284294304314324334344354364374384394404414424434442 unmodified lines4474484494504514524534544552 unmodified lines4584594604614624632 unmodified lines4664674684694704719 unmodified lines4814824834844854861 unmodified line4884894904914924935 unmodified lines4995005015025035041 unmodified line5065075085095105115125135145155165175185195205215225235245255266 unmodified lines5335345355365375381 unmodified line5405415425435445458 unmodified lines5545555565575585595605615625635645659 unmodified lines5755765775785795806 unmodified lines5875885895905915922 unmodified lines5955965975985996003 unmodified lines6046056066076086096106116126131 unmodified line6156166176186196206216226236246251 unmodified line6276286296306316326 unmodified lines6396406416426436446456466476489 unmodified lines65865966066166266366466566666713 unmodified lines6816826836846856866876886896906916926936946956966976 unmodified lines7047057067077087097107117127137147157167177187197207217227237247257267277287295 unmodified lines7357367377387397403 unmodified lines7447457467477487492 unmodified lines7527537547557567577587597607615 unmodified lines7677687697707717721 unmodified line7747757767777787791 unmodified line7817827837847857863 unmodified lines7907917927937947952 unmodified lines7987998008018028038048058068078083 unmodified lines8128138148158168178188198208211 unmodified line8238248258268278288298308318328338348352 unmodified lines8388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738742 unmodified lines8778788798808818828838848858868878888898908918928937 unmodified lines90190290390490590637 unmodified lines94494594694794894995095195295395495595695795895996096196296396496596696796896997097111 unmodified lines983984985986987988989990991992993994import gradio as grimport pandas as pdimport json2 unmodified linesfrom pathlib import Pathfrom typing import Optional, Tuple, List, Dict, Generatorfrom datetime import datetimefrom utils import (CATEGORY_CODES, REGION_LIST, SIDO_LIST, ORG_TYPE_OPTIONS, SORT_OPTIONS, STATUS_OPTIONS,COMPANY_TYPE_OPTIONS, CORP_TYPE_OPTIONS, COMPANY_SIZE_OPTIONS, INDUSTRY_MAJOR_OPTIONS,1 unmodified lineISO_CERT_OPTIONS, extract_region_from_text, extract_region_from_hashtags,classify_org_type, parse_deadline, is_ongoing, calculate_age, calculate_company_age)from file_api import (fetch_all_from_api, fetch_with_cache, download_file, extract_text_from_file, extract_zip_files,call_groq_api_stream, fetch_announcement_detail, CACHE_AVAILABLE)if CACHE_AVAILABLE:from cache_db import (initialize_cache_system, get_sync_status, manual_sync,get_cached_announcements, get_cache)def fetch_announcements(keyword="", category="전체", region="전체(지역)", org_type="전체",sort_by="등록일순", status_filter="진행중", page=1, rows=20) -> Tuple[pd.DataFrame, str]:"""기업마당 API로 공고 목록 조회 (캐시 우선)"""try:items, status_prefix = fetch_with_cache(category, region, keyword)if not items:return pd.DataFrame(), f"⚠️ 검색 결과가 없습니다. {status_prefix}"data = []for item in items:if not isinstance(item, dict):2 unmodified linestitle = item.get("title", "") or item.get("pblancNm", "")exec_org = item.get("excInsttNm", "") or ""hash_tags = item.get("hashTags", "")item_region = extract_region_from_hashtags(hash_tags)if not item_region:item_region = extract_region_from_text(title)if not item_region:item_region = extract_region_from_text(author)item_org_type = classify_org_type(author)req_dt = item.get("reqstDt", "") or item.get("reqstBeginEndDe", "")item_ongoing = is_ongoing(req_dt)pub_date = item.get("pubDate", "") or item.get("creatPnttm", "") or ""if pub_date and len(str(pub_date)) >= 10:pub_date = str(pub_date)[:10]link = item.get("link", "") or item.get("pblancUrl", "")pblanc_id = item.get("seq", "") or item.get("pblancId", "")attachments = []file_url = item.get("flpthNm", "") or ""file_name = item.get("fileNm", "") or ""if file_url and file_name:urls = file_url.split("@") if "@" in file_url else [file_url]names = file_name.split("@") if "@" in file_name else [file_name]for i, (url, name) in enumerate(zip(urls, names)):2 unmodified linesif url and name:ext = Path(name).suffix.lower()[1:] if Path(name).suffix else "unknown"attachments.append({"url": url, "filename": name, "type": ext})print_file = Noneprint_url = item.get("printFlpthNm", "") or ""print_name = item.get("printFileNm", "") or ""2 unmodified linesprint_name = print_name.strip()ext = Path(print_name).suffix.lower()[1:] if Path(print_name).suffix else "unknown"print_file = {"url": print_url, "filename": print_name, "type": ext}description = item.get("description", "") or item.get("bsnsSumryCn", "")if description:import redescription = re.sub(r'<[^>]+>', '', description).strip()deadline = parse_deadline(req_dt)row = {"지원분야": item.get("lcategory", "") or item.get("pldirSportRealmLclasCodeNm", ""),9 unmodified lines"_pub_date": pub_date, "_region": item_region,}data.append(row)if not data:return pd.DataFrame(), f"⚠️ 검색 결과가 없습니다. {status_prefix}"df = pd.DataFrame(data)total_before_filter = len(df)if org_type == "중앙부처":df = df[df["_org_type"] == "중앙부처"]elif org_type == "지자체":2 unmodified linesdf = df[df["_region"] == region]if status_filter == "진행중":df = df[df["_ongoing"] == True]if sort_by == "등록일순":df = df.sort_values(by="_pub_date", ascending=False)elif sort_by == "마감일순":df = df.sort_values(by="_deadline", ascending=True, na_position='last')if len(df) == 0:return pd.DataFrame(), f"⚠️ 필터 조건에 맞는 결과가 없습니다. (전체 {total_before_filter}건 중)"total_filtered = len(df)start_idx = (page - 1) * rowsend_idx = start_idx + rowsdf_page = df.iloc[start_idx:end_idx].copy()df_page.insert(0, "번호", range(total_filtered - start_idx, total_filtered - start_idx - len(df_page), -1))def make_link(row):link = row.get("상세링크", "")if link:if link.startswith('/'):link = f"https://www.bizinfo.go.kr{link}"return f'<a href="{link}" target="_blank">🔗 열기</a>'return ""df_page["바로가기"] = df_page.apply(make_link, axis=1)cols = df_page.columns.tolist()if "상세링크" in cols:cols.remove("상세링크")if "바로가기" in cols:cols.remove("바로가기")cols.insert(2, "바로가기") # 번호, 지원분야 다음에 배치df_page = df_page[cols]internal_cols = [c for c in df_page.columns if c.startswith("_")]df_page = df_page.drop(columns=internal_cols)hide_cols = ["공고ID", "첨부파일", "본문출력파일", "사업개요", "지원대상", "문의처", "신청URL"]for col in hide_cols:if col in df_page.columns:df_page = df_page.drop(columns=[col])status = f"✅ {len(df_page)}건 표시 (페이지 {page}) | 필터 결과: {total_filtered}건 | 수집: {total_before_filter}건"if status_prefix:status = f"{status_prefix} | {status}"return df_page, statusexcept Exception as e:import tracebackreturn pd.DataFrame(), f"❌ 오류: {str(e)[:80]}"def analyze_announcement(detail_url, project_name, print_file=None, api_description="", progress=gr.Progress()):"""공고 본문출력파일을 다운로드하고 AI로 분석Args:detail_url: 공고 상세 링크project_name: 공고명3 unmodified linesif not detail_url:yield "❌ 분석할 공고를 선택해주세요."returnoutput = f"# 📄 {project_name}\n\n---\n\n"all_text = f"## 공고명: {project_name}\n\n"if api_description:all_text += f"### 사업개요:\n{api_description}\n\n"output += f"📋 **사업개요**\n{api_description}\n\n"yield outputif not print_file or not isinstance(print_file, dict) or not print_file.get("url"):progress(0.1, desc="상세 페이지에서 본문출력파일 검색 중...")output += "🔍 **상세 페이지에서 본문출력파일 검색 중...**\n"yield outputtry:content, attachments, scraped_print_file = fetch_announcement_detail(detail_url)if scraped_print_file:print_file = scraped_print_fileoutput += f" ✅ 본문출력파일 발견: `{print_file.get('filename')}`\n\n"9 unmodified linesexcept Exception as e:output += f" ❌ 상세 페이지 조회 실패: {str(e)}\n\n"yield outputextracted_text = Noneif print_file and isinstance(print_file, dict) and print_file.get("url"):output += f"📄 **본문출력파일 발견**\n"output += f" - 파일명: `{print_file.get('filename', '알 수 없음')}`\n"output += f" - 형식: {print_file.get('type', 'unknown').upper()}\n\n"yield outputwith tempfile.TemporaryDirectory() as tmp_dir:progress(0.2, desc="본문출력파일 다운로드 중...")output += f"📥 다운로드 중...\n"yield outputfile_path, error = download_file(print_file['url'], tmp_dir, print_file.get('filename'))if error:output += f" - ⚠️ 다운로드 실패: {error}\n"yield output1 unmodified lineprogress(0.5, desc="텍스트 추출 중...")output += f" - ✅ 다운로드 완료\n"yield outputtext, err = extract_text_from_file(file_path)if text:extracted_text = text6 unmodified linesoutput += "⚠️ **본문출력파일이 없습니다.**\n"output += "사업개요만으로 분석을 진행합니다.\n\n"yield outputif len(all_text) < 100 and not extracted_text:output += "\n❌ **분석할 내용이 충분하지 않습니다.**\n"output += "본문출력파일이 없거나 텍스트 추출에 실패했습니다.\n"yield outputreturnoutput += f"\n📊 **분석 준비 완료** (총 {len(all_text):,}자)\n\n---\n\n## 🤖 AI 분석 결과\n\n"yield outputprogress(0.7, desc="AI 분석 중...")system_prompt = """당신은 정부 지원사업 공고 분석 전문가입니다.주어진 공고 내용을 분석하여 다음 항목을 명확하게 정리해주세요:3 unmodified lines- 신청 기간, 신청 방법, 제출 서류- 중요 유의사항, 제한 사항- 이 사업의 핵심 포인트를 3줄로 요약"""messages = [{"role": "system", "content": system_prompt},{"role": "user", "content": f"다음 지원사업 공고를 분석해주세요:\n\n{all_text[:15000]}"}]for chunk in call_groq_api_stream(messages):output += chunkyield outputoutput += "\n\n---\n✅ **분석 완료**"yield outputdef analyze_uploaded_documents(files, progress=gr.Progress()):"""업로드된 문서들을 분석하여 기업 정보 추출"""if not files:yield "❌ 분석할 파일을 업로드해주세요."returnoutput = "# 📄 업로드 문서 분석 결과\n\n"all_extracted_text = []for i, file in enumerate(files):progress((i + 1) / len(files), desc=f"파일 분석 중... ({i+1}/{len(files)})")filename = os.path.basename(file.name) if hasattr(file, 'name') else f"파일_{i+1}"output += f"## 📎 {filename}\n\n"yield outputtry:text, error = extract_text_from_file(file.name if hasattr(file, 'name') else file)if text:5 unmodified linesexcept Exception as e:output += f"❌ 오류: {str(e)}\n\n"yield outputif all_extracted_text:output += "---\n\n## 🤖 AI 기업정보 추출\n\n"yield outputcombined_text = "\n\n".join([f"[{item['filename']}]\n{item['text'][:3000]}" for item in all_extracted_text])system_prompt = """당신은 기업 서류 분석 전문가입니다.주어진 문서들에서 다음 정보를 추출해주세요:1. 사업자 정보 (사업자등록번호, 법인등록번호, 상호, 대표자, 설립일, 주소, 업종)2 unmodified lines4. 인증/등록 정보 (부설연구소, 벤처기업 인증 등)5. 기타 특이사항JSON 형식으로 정리해주세요."""messages = [{"role": "system", "content": system_prompt},{"role": "user", "content": f"다음 기업 서류들을 분석해주세요:\n\n{combined_text[:12000]}"}]for chunk in call_groq_api_stream(messages):output += chunkyield outputoutput += "\n\n---\n✅ **문서 분석 완료**"yield outputdef match_announcements_with_profile(profile_data, announcements_df, progress=gr.Progress()):"""기업 프로필과 공고를 매칭"""if not profile_data:yield "❌ 기업 프로필을 먼저 입력해주세요."returnif announcements_df is None or (isinstance(announcements_df, pd.DataFrame) and announcements_df.empty):yield "❌ 매칭할 공고 데이터가 없습니다. 먼저 공고를 검색해주세요."returnoutput = "# 🎯 맞춤 과제 매칭 결과\n\n"output += "## 📋 입력된 기업 프로필\n\n"output += f"```json\n{json.dumps(profile_data, ensure_ascii=False, indent=2)[:2000]}\n```\n\n"output += "---\n\n## 🔍 AI 매칭 분석 중...\n\n"yield outputannouncements_text = ""df_to_use = announcements_df if isinstance(announcements_df, pd.DataFrame) else pd.DataFrame()for idx, row in df_to_use.head(20).iterrows():announcements_text += f"""- 지원분야: {row.get('지원분야', '')}- 소관부처: {row.get('소관부처', '')}- 신청기간: {row.get('신청기간', '')}- 지원대상: {row.get('지원대상', '')}---"""system_prompt = """당신은 정부 지원사업 매칭 전문가입니다.기업 프로필과 공고 목록을 분석하여 신청 가능한 과제를 추천해주세요.각 공고에 대해:1 unmodified line- ⚠️ 확인필요: 일부 조건 확인 필요- ❌ 부적합: 자격 미달추천 순위와 이유를 설명해주세요."""messages = [{"role": "system", "content": system_prompt},{"role": "user", "content": f"기업 프로필:\n{json.dumps(profile_data, ensure_ascii=False)}\n\n공고 목록:\n{announcements_text[:8000]}"}]for chunk in call_groq_api_stream(messages):output += chunkyield outputoutput += "\n\n---\n✅ **매칭 분석 완료**"yield outputdef get_cache_info():"""캐시 상태 정보 반환"""if not CACHE_AVAILABLE:return "⚠️ 캐시 시스템 미사용 (API 직접 호출)"status = get_sync_status()info = f"""📦 **캐시 상태**- 총 캐시: {status.get('total_count', 0):,}건2 unmodified lines- 스케줄러: {'✅ 활성' if status.get('scheduler_available') else '❌ 비활성'}"""return infodef do_manual_sync():"""수동 동기화 실행"""if not CACHE_AVAILABLE:return "⚠️ 캐시 시스템을 사용할 수 없습니다."return manual_sync()CUSTOM_CSS = """@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;500;700&display=swap');/* ═══════════════════════════════════════════════════════════🔘 NEUMORPHISM 핵심 변수═══════════════════════════════════════════════════════════ */8 unmodified lines--neu-success: #48bb78;--neu-warning: #ed8936;}/* ═══════════════════════════════════════════════════════════📦 기본 컨테이너═══════════════════════════════════════════════════════════ */.gradio-container {font-family: 'Noto Sans KR', sans-serif !important;background: var(--neu-bg) !important;max-width: 1600px !important;margin: 0 auto !important;min-height: 100vh;}body, .dark {background: var(--neu-bg) !important;}/* ═══════════════════════════════════════════════════════════🎯 헤더 배너 (Neumorphism)═══════════════════════════════════════════════════════════ */7 unmodified lines12px 12px 24px var(--neu-shadow-dark),-12px -12px 24px var(--neu-shadow-light);}.header-banner h1 {color: var(--neu-text-dark) !important;text-shadow: 2px 2px 4px var(--neu-shadow-light), -1px -1px 3px rgba(0,0,0,0.1);}.header-banner p {color: var(--neu-text) !important;}/* ═══════════════════════════════════════════════════════════🏷️ 배지 스타일═══════════════════════════════════════════════════════════ */10 unmodified lines4px 4px 8px var(--neu-shadow-dark),-4px -4px 8px var(--neu-shadow-light);}/* ═══════════════════════════════════════════════════════════📋 섹션 헤더═══════════════════════════════════════════════════════════ */8 unmodified lines6px 6px 12px var(--neu-shadow-dark),-6px -6px 12px var(--neu-shadow-light);}/* ═══════════════════════════════════════════════════════════🔘 버튼 스타일═══════════════════════════════════════════════════════════ */9 unmodified lines-6px -6px 12px var(--neu-shadow-light) !important;transition: all 0.2s ease !important;}.gr-button:hover, button.primary:hover, button.secondary:hover {box-shadow:4px 4px 8px var(--neu-shadow-dark),-4px -4px 8px var(--neu-shadow-light) !important;transform: translateY(-1px);}.gr-button:active, button.primary:active, button.secondary:active {box-shadow:inset 4px 4px 8px var(--neu-shadow-dark),inset -4px -4px 8px var(--neu-shadow-light) !important;transform: translateY(0);}/* 🟢 분석 버튼 */.analyze-btn button, .analyze-btn {background: linear-gradient(145deg, #52c992, #3ea87a) !important;2 unmodified lines6px 6px 12px var(--neu-shadow-dark),-6px -6px 12px var(--neu-shadow-light) !important;}.analyze-btn:hover button, .analyze-btn:hover {background: linear-gradient(145deg, #3ea87a, #359968) !important;}/* 🟣 매칭 버튼 */.match-btn button, .match-btn {background: linear-gradient(145deg, #9f7aea, #805ad5) !important;2 unmodified lines6px 6px 12px var(--neu-shadow-dark),-6px -6px 12px var(--neu-shadow-light) !important;}/* 🟠 동기화 버튼 */.sync-btn button, .sync-btn {background: linear-gradient(145deg, #f6ad55, #ed8936) !important;2 unmodified lines4px 4px 8px var(--neu-shadow-dark),-4px -4px 8px var(--neu-shadow-light) !important;}/* ═══════════════════════════════════════════════════════════📝 입력 필드 (Inset 효과)═══════════════════════════════════════════════════════════ */9 unmodified linesinset 4px 4px 8px var(--neu-shadow-dark),inset -4px -4px 8px var(--neu-shadow-light) !important;}.gr-textbox textarea:focus, .gr-textbox input:focus,input[type="text"]:focus, textarea:focus {outline: none !important;1 unmodified lineinset 6px 6px 12px var(--neu-shadow-dark),inset -6px -6px 12px var(--neu-shadow-light) !important;}/* ═══════════════════════════════════════════════════════════📊 데이터프레임 테이블═══════════════════════════════════════════════════════════ */5 unmodified lines8px 8px 16px var(--neu-shadow-dark),-8px -8px 16px var(--neu-shadow-light) !important;}.gr-dataframe th, .dataframe th {background: var(--neu-bg) !important;color: var(--neu-text-dark) !important;1 unmodified linepadding: 14px 12px !important;border-bottom: 2px solid var(--neu-shadow-dark) !important;}.gr-dataframe td, .dataframe td {background: var(--neu-bg) !important;color: var(--neu-text) !important;padding: 12px !important;border-bottom: 1px solid rgba(163, 177, 198, 0.3) !important;}.gr-dataframe tr:hover td, .dataframe tr:hover td {background: rgba(74, 125, 189, 0.1) !important;}/* ═══════════════════════════════════════════════════════════📁 탭 스타일═══════════════════════════════════════════════════════════ */.gr-tabs, .tabs {background: var(--neu-bg) !important;}.gr-tab-item, .tab-nav button {background: var(--neu-bg) !important;border: none !important;6 unmodified lines4px -4px 8px var(--neu-shadow-dark),-4px -4px 8px var(--neu-shadow-light) !important;}.gr-tab-item.selected, .tab-nav button.selected {background: var(--neu-bg) !important;color: var(--neu-primary) !important;1 unmodified lineinset 3px 3px 6px var(--neu-shadow-dark),inset -3px -3px 6px var(--neu-shadow-light) !important;}/* ═══════════════════════════════════════════════════════════✅ 체크박스═══════════════════════════════════════════════════════════ */8 unmodified linesinset -3px -3px 6px var(--neu-shadow-light);cursor: pointer;}.gr-checkbox input[type="checkbox"]:checked {background: linear-gradient(145deg, #48bb78, #38a169);box-shadow:3px 3px 6px var(--neu-shadow-dark),-3px -3px 6px var(--neu-shadow-light);}/* ═══════════════════════════════════════════════════════════📋 캐시 정보 박스═══════════════════════════════════════════════════════════ */9 unmodified linesinset 4px 4px 8px var(--neu-shadow-dark),inset -4px -4px 8px var(--neu-shadow-light) !important;}/* ═══════════════════════════════════════════════════════════📄 카드/패널 스타일═══════════════════════════════════════════════════════════ */6 unmodified lines8px 8px 16px var(--neu-shadow-dark),-8px -8px 16px var(--neu-shadow-light) !important;}/* ═══════════════════════════════════════════════════════════📊 라벨 스타일═══════════════════════════════════════════════════════════ */2 unmodified linesfont-weight: 600 !important;text-shadow: 1px 1px 2px var(--neu-shadow-light);}/* ═════════════════════════════════��═════════════════════════🔗 링크 스타일═══════════════════════════════════════════════════════════ */3 unmodified linesfont-weight: 600;transition: all 0.2s ease;}a:hover {color: #3a6aa8 !important;text-shadow: 0 0 8px rgba(74, 125, 189, 0.3);}/* ═══════════════════════════════════════════════════════════📱 스크롤바 스타일═══════════════════════════════════════════════════════════ */1 unmodified linewidth: 10px;height: 10px;}::-webkit-scrollbar-track {background: var(--neu-bg);border-radius: 10px;box-shadow: inset 2px 2px 4px var(--neu-shadow-dark);}::-webkit-scrollbar-thumb {background: linear-gradient(145deg, #d1d9e6, #b8c0cc);border-radius: 10px;1 unmodified line2px 2px 4px var(--neu-shadow-dark),-2px -2px 4px var(--neu-shadow-light);}/* ═══════════════════════════════════════════════════════════🎨 마크다운 출력 영역═══════════════════════════════════════════════════════════ */6 unmodified linesinset 4px 4px 8px var(--neu-shadow-dark),inset -4px -4px 8px var(--neu-shadow-light) !important;}.gr-markdown h1, .gr-markdown h2, .gr-markdown h3 {color: var(--neu-text-dark) !important;text-shadow: 2px 2px 4px var(--neu-shadow-light);}/* ═══════════════════════════════════════════════════════════✨ 애니메이션═══════════════════════════════════════════════════════════ */9 unmodified lines-12px -12px 24px var(--neu-shadow-light);}}.loading {animation: pulse-neu 1.5s ease-in-out infinite;}"""def create_interface():with gr.Blocks(title="기업마당 AI 분석기", css=CUSTOM_CSS) as demo:gr.HTML("""13 unmodified lines</div></div>""")selected_url = gr.State("")selected_name = gr.State("")selected_print_file = gr.State(None) # ⭐ 본문출력파일 (dict)selected_description = gr.State("")current_df = gr.State(value=pd.DataFrame())company_profile = gr.State(value={})with gr.Tabs():with gr.Tab("🔍 공고 검색"):with gr.Row():cache_status = gr.Markdown(value=get_cache_info(), elem_classes=["cache-info"])sync_btn = gr.Button("🔄 수동 동기화", size="sm", elem_classes=["sync-btn"])with gr.Row():keyword_input = gr.Textbox(label="🔍 검색어", placeholder="예: AI, 스타트업, R&D", scale=3)category_dropdown = gr.Dropdown(label="📂 지원분야", choices=list(CATEGORY_CODES.keys()), value="전체", scale=1)6 unmodified linespage_input = gr.Number(label="📄 페이지", value=1, minimum=1, scale=1)rows_dropdown = gr.Dropdown(label="📊 표시개수", choices=[10, 15, 20, 30, 50], value=20, scale=1)search_btn = gr.Button("🔎 검색", variant="primary", scale=2)status_output = gr.Textbox(label="📊 조회 결과", interactive=False)results_output = gr.Dataframe(label="📋 공고 목록 (행 클릭으로 선택)", wrap=True, interactive=False, datatype="markdown")with gr.Row():prev_btn = gr.Button("◀️ 이전", size="sm")next_btn = gr.Button("다음 ▶️", size="sm")with gr.Tab("🤖 AI 분석"):with gr.Row():with gr.Column(scale=1):selected_info = gr.Textbox(label="📌 선택된 공고", placeholder="공고 검색 탭에서 선택", lines=3, interactive=False)analyze_btn = gr.Button("🚀 AI 분석 시작", variant="primary", size="lg", elem_classes=["analyze-btn"])with gr.Column(scale=2):analysis_output = gr.Markdown(value="### 📊 분석 결과\n\n*공고를 선택하고 분석 버튼을 클릭하세요*", height=500)with gr.Tab("🎯 맞춤 과제 추출"):gr.HTML("""<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 12px; margin-bottom: 20px;"><h2 style="margin: 0 0 8px 0;">🎯 나만의 맞춤 과제 추출</h2><p style="margin: 0; opacity: 0.9;">기업 정보를 입력하고 문서를 업로드하면 AI가 신청 가능한 과제를 자동으로 매칭해드립니다.</p></div>""")with gr.Tabs():with gr.Tab("1️⃣ 기업 기본정보"):with gr.Row():with gr.Column():5 unmodified linescompany_type = gr.Dropdown(label="기업형태", choices=COMPANY_TYPE_OPTIONS, value="법인사업자")corp_type = gr.Dropdown(label="법인 종류", choices=CORP_TYPE_OPTIONS, value="주식회사")company_size = gr.Dropdown(label="기업규모", choices=COMPANY_SIZE_OPTIONS, value="소기업")with gr.Column():gr.HTML('<div class="section-header">🏆 인증 현황</div>')venture_cert = gr.Checkbox(label="벤처기업 인증")3 unmodified linessmall_biz_cert = gr.Checkbox(label="소상공인확인서 보유")social_venture = gr.Checkbox(label="소셜벤처")startup_flag = gr.Checkbox(label="스타트업")with gr.Column():gr.HTML('<div class="section-header">📍 소재지 정보</div>')hq_sido = gr.Dropdown(label="본사 소재지 (시/도)", choices=SIDO_LIST, value="서울특별시")2 unmodified linesindustrial_complex = gr.Checkbox(label="산업단지 입주")free_zone = gr.Checkbox(label="규제자유특구 소재")non_capital = gr.Checkbox(label="비수도권 (지방기업)")gr.HTML('<div class="section-header">📊 업종 정보</div>')industry_major = gr.Dropdown(label="주업종 (대분류)", choices=INDUSTRY_MAJOR_OPTIONS, value="C. 제조업")is_manufacturing = gr.Checkbox(label="제조업 여부")is_knowledge_service = gr.Checkbox(label="지식서비스업 여부")with gr.Tab("2️⃣ 대표자/인력 정보"):with gr.Row():with gr.Column():5 unmodified linessenior_ceo = gr.Checkbox(label="시니어창업자 (만40세 이상)")women_company = gr.Checkbox(label="여성기업확인서 보유")disabled_company = gr.Checkbox(label="장애인기업확인서 보유")with gr.Column():gr.HTML('<div class="section-header">👥 고용 현황</div>')insurance_employees = gr.Number(label="4대보험 가입자 수", value=0, minimum=0)1 unmodified lineyouth_employees = gr.Number(label="청년고용 인원", value=0, minimum=0)female_ratio = gr.Slider(label="여성고용 비율 (%)", minimum=0, maximum=100, value=0)new_hire_plan = gr.Number(label="신규채용 계획 (명)", value=0, minimum=0)with gr.Column():gr.HTML('<div class="section-header">🔬 연구인력/역량</div>')rd_personnel = gr.Number(label="연구인력 수", value=0, minimum=0)1 unmodified lineresearch_center = gr.Checkbox(label="기업부설연구소 등록")rd_dept = gr.Checkbox(label="연구개발전담부서 등록")patent_count = gr.Number(label="보유 특허 수", value=0, minimum=0)with gr.Tab("3️⃣ 재무 정보"):with gr.Row():with gr.Column():3 unmodified linesoperating_profit = gr.Number(label="영업이익 (백만원)", value=0)net_income = gr.Number(label="당기순이익 (백만원)", value=0)export_amount = gr.Number(label="수출액 (천달러)", value=0, minimum=0)with gr.Column():gr.HTML('<div class="section-header">📊 재무건전성</div>')capital = gr.Number(label="자본금 (백만원)", value=0, minimum=0)2 unmodified linescredit_grade = gr.Dropdown(label="신용등급", choices=CREDIT_GRADE_OPTIONS, value="미평가")tcb_grade = gr.Dropdown(label="TCB 등급", choices=TCB_GRADE_OPTIONS, value="미평가")capital_impairment = gr.Checkbox(label="자본잠식 여부")with gr.Column():gr.HTML('<div class="section-header">🔬 R&D 투자</div>')rd_investment = gr.Number(label="연간 R&D 투자액 (백만원)", value=0, minimum=0)gov_project_exp = gr.Checkbox(label="정부과제 수행 경험")gov_support_3yr = gr.Number(label="최근 3년 정부지원금 (백만원)", value=0, minimum=0)with gr.Tab("4️⃣ 기술분야/제한사항"):with gr.Row():with gr.Column():3 unmodified linesgreen_tech = gr.Checkbox(label="녹색기술 분야")digital_transform = gr.Checkbox(label="디지털전환 분야")defense_industry = gr.Checkbox(label="국방/방산 분야")with gr.Column():gr.HTML('<div class="section-header">📜 인증/ISO</div>')iso_certs = gr.CheckboxGroup(label="ISO 인증", choices=ISO_CERT_OPTIONS)gmp_cert = gr.Checkbox(label="GMP 인증")with gr.Column():gr.HTML('<div class="section-header">⚠️ 결격사유 확인</div>')tax_delinquent = gr.Checkbox(label="국세 체납")1 unmodified linegov_project_fail = gr.Checkbox(label="정부과제 불성실")bankruptcy = gr.Checkbox(label="휴/폐업 이력")financial_default = gr.Checkbox(label="금융기관 연체")with gr.Tab("5️⃣ 문서 ���로드 & 매칭"):gr.HTML("""<div style="background: #EBF5FF; border: 1px solid #3B82F6; border-radius: 8px; padding: 16px; margin-bottom: 16px;"><h3 style="margin: 0 0 8px 0; color: #1E40AF;">📁 문서 업로드</h3><p style="margin: 0; color: #1E3A8A;">사업자등록증, 등기부등본, 재무제표, 중소기업확인서 등을 업로드하면 AI가 자동으로 정보를 추출합니다.</p></div>""")with gr.Row():with gr.Column(scale=1):file_upload = gr.File(2 unmodified linesfile_types=[".hwp", ".hwpx", ".pdf", ".txt", ".xlsx", ".xls"])analyze_docs_btn = gr.Button("📄 문서 분석", variant="secondary", size="lg")with gr.Column(scale=2):doc_analysis_output = gr.Markdown(value="### 📄 문서 분석 결과\n\n*문서를 업로드하고 분석 버튼을 클릭하세요*", height=400)gr.HTML('<hr style="margin: 24px 0;">')with gr.Row():save_profile_btn = gr.Button("💾 프로필 저장", variant="secondary", size="lg")match_btn = gr.Button("🎯 맞춤 과제 매칭 시작", variant="primary", size="lg", elem_classes=["match-btn"])profile_status = gr.Textbox(label="프로필 저장 상태", interactive=False)match_output = gr.Markdown(value="### 🎯 매칭 결과\n\n*프로필을 저장하고 매칭 버튼을 클릭하세요*", height=500)def search_fn(keyword, category, region, org_type, sort_by, status_filter, page, rows):df, status = fetch_announcements(keyword or "", category or "전체", region or "전체(지역)",org_type or "전체", sort_by or "등록일순",status_filter or "진행중", int(page) if page else 1, int(rows) if rows else 20)display_cols = ["번호", "지원분야", "지원사업명", "신청기간", "소관부처", "등록일", "지원대상"]display_df = df[[c for c in display_cols if c in df.columns]] if not df.empty else dfreturn display_df, status, dfdef prev_fn(page, keyword, category, region, org_type, sort_by, status_filter, rows):new_page = max(1, int(page) - 1) if page else 1df, status = fetch_announcements(keyword or "", category or "전체", region or "전체(지역)",org_type or "전체", sort_by or "등록일순",status_filter or "진행중", new_page, int(rows) if rows else 20)display_cols = ["번호", "지원분야", "지원사업명", "신청기간", "소관부처", "등록일", "지원대상"]display_df = df[[c for c in display_cols if c in df.columns]] if not df.empty else dfreturn display_df, status, df, new_pagedef next_fn(page, keyword, category, region, org_type, sort_by, status_filter, rows):new_page = int(page) + 1 if page else 2df, status = fetch_announcements(keyword or "", category or "전체", region or "전체(지역)",org_type or "전체", sort_by or "등록일순",status_filter or "진행중", new_page, int(rows) if rows else 20)display_cols = ["번호", "지원분야", "지원사업명", "신청기간", "소관부처", "등록일", "지원대상"]display_df = df[[c for c in display_cols if c in df.columns]] if not df.empty else dfreturn display_df, status, df, new_pagedef on_row_select(evt: gr.SelectData, df):if evt.index[0] < len(df):row = df.iloc[evt.index[0]]2 unmodified linesattachments = row.get("첨부파일", [])print_file = row.get("본문출력파일", None) # ⭐ AI 분석용 핵심 파일description = row.get("사업개요", "")info_parts = [f"📌 {name}", f"🔗 {url}"]if print_file:info_parts.append(f"\n\n📄 **본문출력파일 (AI 분석 대상)**:")info_parts.append(f" - {print_file.get('filename', '파일')}")if attachments and len(attachments) > 0:info_parts.append(f"\n\n📎 기타 첨부파일 {len(attachments)}개:")for att in attachments:info_parts.append(f" - {att.get('filename', '파일')}")info = "\n".join(info_parts)return url, name, print_file, description, inforeturn "", "", None, "", ""def save_profile_fn(biz_num, corp_num, comp_name, est_date, comp_type, corp_tp, comp_size,venture, innobiz, mainbiz, sme, small_biz, social, startup,sido, sigungu, innov_city, ind_complex, free_z, non_cap,7 unmodified linescore_ind, strat_tech, green, digital, defense,iso, gmp,tax_del, local_tax, gov_fail, bankrupt, fin_def):profile = {"사업자정보": {"사업자등록번호": biz_num, "법인등록번호": corp_num, "상호": comp_name,37 unmodified lines}}return profile, "✅ 프로필이 저장되었습니다."def sync_and_update():result = do_manual_sync()info = get_cache_info()return info, resultsearch_btn.click(fn=search_fn, inputs=[keyword_input, category_dropdown, region_dropdown, org_type_dropdown,sort_dropdown, status_dropdown, page_input, rows_dropdown],outputs=[results_output, status_output, current_df])keyword_input.submit(fn=search_fn, inputs=[keyword_input, category_dropdown, region_dropdown, org_type_dropdown,sort_dropdown, status_dropdown, page_input, rows_dropdown],outputs=[results_output, status_output, current_df])sync_btn.click(fn=sync_and_update, outputs=[cache_status, status_output])prev_btn.click(fn=prev_fn, inputs=[page_input, keyword_input, category_dropdown, region_dropdown,org_type_dropdown, sort_dropdown, status_dropdown, rows_dropdown],outputs=[results_output, status_output, current_df, page_input])next_btn.click(fn=next_fn, inputs=[page_input, keyword_input, category_dropdown, region_dropdown,org_type_dropdown, sort_dropdown, status_dropdown, rows_dropdown],outputs=[results_output, status_output, current_df, page_input])results_output.select(fn=on_row_select, inputs=[current_df],outputs=[selected_url, selected_name, selected_print_file, selected_description, selected_info])analyze_btn.click(fn=analyze_announcement, inputs=[selected_url, selected_name, selected_print_file, selected_description],outputs=[analysis_output])analyze_docs_btn.click(fn=analyze_uploaded_documents, inputs=[file_upload], outputs=[doc_analysis_output])save_profile_btn.click(fn=save_profile_fn,inputs=[biz_number, corp_number, company_name, establish_date, company_type, corp_type, company_size,11 unmodified linestax_delinquent, local_tax_delinquent, gov_project_fail, bankruptcy, financial_default],outputs=[company_profile, profile_status])match_btn.click(fn=match_announcements_with_profile, inputs=[company_profile, current_df], outputs=[match_output])return demoif __name__ == "__main__":if CACHE_AVAILABLE:print("🚀 캐시 시스템 초기화 중...")status = initialize_cache_system()print(f"✅ 캐시 상태: {status}")demo = create_interface()demo.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False)123456782 unmodified lines111213141516171 unmodified line1920212223242526272829303132333435363738394041424344454647484950512 unmodified lines54555657585960616263646566676869707172737475767778798081822 unmodified lines85868788899091922 unmodified lines95969798991001011021031041051069 unmodified lines1161171181191201211221231241251261271282 unmodified lines1311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801813 unmodified lines1851861871881891901911921931941951961971981992002012022032042052062072089 unmodified lines2182192202212222232242252262272282292302312322332342352362372382392401 unmodified line2422432442452462472482496 unmodified lines2562572582592602612622632642652662672682692702713 unmodified lines2752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113125 unmodified lines3183193203213223233243253263273283293302 unmodified lines3333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793801 unmodified line3823833843853863873883893903913923933943953963973983994004014024034044054064074084092 unmodified lines4124134144154164174184194204214224234244254264274284294304314328 unmodified lines4414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025037 unmodified lines51151251351451551651751851952052152252352452552610 unmodified lines5375385395405415425438 unmodified lines5525535545555565575589 unmodified lines5685695705715725735745755765775785795805815825835845855865875882 unmodified lines5915925935945955965975985996006012 unmodified lines6046056066076086096102 unmodified lines6136146156166176186199 unmodified lines6296306316326336346351 unmodified line6376386396406416426435 unmodified lines6496506516526536546551 unmodified line6576586596606616626636646656666676686696706716726736746756766776786796806816 unmodified lines6886896906916926936941 unmodified line6966976986997007017028 unmodified lines7117127137147157167177187197207217227237249 unmodified lines7347357367377387397406 unmodified lines7477487497507517527532 unmodified lines7567577587597607617623 unmodified lines7667677687697707717727737747757767771 unmodified line7797807817827837847857867877887897907911 unmodified line7937947957967977987996 unmodified lines8068078088098108118128138148158168179 unmodified lines82782882983083183283383483583683783883984084184213 unmodified lines8568578588598608618628638648658668678688698708718728738748758768778786 unmodified lines8858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209215 unmodified lines9279289299309319329333 unmodified lines9379389399409419429432 unmodified lines9469479489499509519529539549559569579585 unmodified lines9649659669679689699701 unmodified line9729739749759769779781 unmodified line9809819829839849859869873 unmodified lines9919929939949959969972 unmodified lines100010011002100310041005100610071008100910101011101210133 unmodified lines1017101810191020102110221023102410251026102710281 unmodified line10301031103210331034103510361037103810391040104110421043104410452 unmodified lines1048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810892 unmodified lines10921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911407 unmodified lines114811491150115111521153115437 unmodified lines11921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124511 unmodified lines125712581259126012611262126312641265126612671268126912701271127212731274127512761277"""기업마당 AI 분석기 - 메인 애플리케이션- 벡터 DB 캐시 통합으로 빠른 로딩- KST 10:00/22:00 자동 동기화"""import gradio as grimport pandas as pdimport json2 unmodified linesfrom pathlib import Pathfrom typing import Optional, Tuple, List, Dict, Generatorfrom datetime import datetimefrom utils import (CATEGORY_CODES, REGION_LIST, SIDO_LIST, ORG_TYPE_OPTIONS, SORT_OPTIONS, STATUS_OPTIONS,COMPANY_TYPE_OPTIONS, CORP_TYPE_OPTIONS, COMPANY_SIZE_OPTIONS, INDUSTRY_MAJOR_OPTIONS,1 unmodified lineISO_CERT_OPTIONS, extract_region_from_text, extract_region_from_hashtags,classify_org_type, parse_deadline, is_ongoing, calculate_age, calculate_company_age)from file_api import (fetch_all_from_api, fetch_with_cache, download_file, extract_text_from_file, extract_zip_files,call_groq_api_stream, fetch_announcement_detail, CACHE_AVAILABLE)# 캐시 시스템 임포트if CACHE_AVAILABLE:from cache_db import (initialize_cache_system, get_sync_status, manual_sync,get_cached_announcements, get_cache)# ============================================================# 공고 조회 함수 (캐시 통합)# ============================================================def fetch_announcements(keyword="", category="전체", region="전체(지역)", org_type="전체",sort_by="등록일순", status_filter="진행중", page=1, rows=20) -> Tuple[pd.DataFrame, str]:"""기업마당 API로 공고 목록 조회 (캐시 우선)"""try:# ⭐ 항상 캐시 우선 사용 (필터가 있어도 캐시에서 필터링 - 빠름!)items, status_prefix = fetch_with_cache(category, region, keyword)if not items:return pd.DataFrame(), f"⚠️ 검색 결과가 없습니다. {status_prefix}"data = []for item in items:if not isinstance(item, dict):2 unmodified linestitle = item.get("title", "") or item.get("pblancNm", "")exec_org = item.get("excInsttNm", "") or ""hash_tags = item.get("hashTags", "")item_region = extract_region_from_hashtags(hash_tags)if not item_region:item_region = extract_region_from_text(title)if not item_region:item_region = extract_region_from_text(author)item_org_type = classify_org_type(author)req_dt = item.get("reqstDt", "") or item.get("reqstBeginEndDe", "")item_ongoing = is_ongoing(req_dt)pub_date = item.get("pubDate", "") or item.get("creatPnttm", "") or ""if pub_date and len(str(pub_date)) >= 10:pub_date = str(pub_date)[:10]link = item.get("link", "") or item.get("pblancUrl", "")pblanc_id = item.get("seq", "") or item.get("pblancId", "")# 일반 첨부파일 (서식, 양식 등)attachments = []file_url = item.get("flpthNm", "") or ""file_name = item.get("fileNm", "") or ""if file_url and file_name:# 여러 파일이 @로 구분되어 있을 수 있음urls = file_url.split("@") if "@" in file_url else [file_url]names = file_name.split("@") if "@" in file_name else [file_name]for i, (url, name) in enumerate(zip(urls, names)):2 unmodified linesif url and name:ext = Path(name).suffix.lower()[1:] if Path(name).suffix else "unknown"attachments.append({"url": url, "filename": name, "type": ext})# ⭐ 본문출력파일 (공고 본문 PDF/HWP) - AI 분석용 핵심 파일print_file = Noneprint_url = item.get("printFlpthNm", "") or ""print_name = item.get("printFileNm", "") or ""2 unmodified linesprint_name = print_name.strip()ext = Path(print_name).suffix.lower()[1:] if Path(print_name).suffix else "unknown"print_file = {"url": print_url, "filename": print_name, "type": ext}description = item.get("description", "") or item.get("bsnsSumryCn", "")if description:import redescription = re.sub(r'<[^>]+>', '', description).strip()deadline = parse_deadline(req_dt)row = {"지원분야": item.get("lcategory", "") or item.get("pldirSportRealmLclasCodeNm", ""),9 unmodified lines"_pub_date": pub_date, "_region": item_region,}data.append(row)if not data:return pd.DataFrame(), f"⚠️ 검색 결과가 없습니다. {status_prefix}"df = pd.DataFrame(data)total_before_filter = len(df)if org_type == "중앙부처":df = df[df["_org_type"] == "중앙부처"]elif org_type == "지자체":2 unmodified linesdf = df[df["_region"] == region]if status_filter == "진행중":df = df[df["_ongoing"] == True]if sort_by == "등록일순":df = df.sort_values(by="_pub_date", ascending=False)elif sort_by == "마감일순":df = df.sort_values(by="_deadline", ascending=True, na_position='last')if len(df) == 0:return pd.DataFrame(), f"⚠️ 필터 조건에 맞는 결과가 없습니다. (전체 {total_before_filter}건 중)"total_filtered = len(df)start_idx = (page - 1) * rowsend_idx = start_idx + rowsdf_page = df.iloc[start_idx:end_idx].copy()df_page.insert(0, "번호", range(total_filtered - start_idx, total_filtered - start_idx - len(df_page), -1))# ⭐ 원본 데이터 보존 (AI 분석용)df_full = df_page.copy()# 표시용 DataFrame 생성internal_cols = [c for c in df_page.columns if c.startswith("_")]df_display = df_page.drop(columns=internal_cols)# 표시용에서 불필요한 컬럼 숨기기hide_cols = ["공고ID", "첨부파일", "본문출력파일", "사업개요", "문의처", "신청URL"]for col in hide_cols:if col in df_display.columns:df_display = df_display.drop(columns=[col])status = f"✅ {len(df_page)}건 표시 (페이지 {page}) | 필터 결과: {total_filtered}건 | 수집: {total_before_filter}건"if status_prefix:status = f"{status_prefix} | {status}"# 표시용 df, 상태, 원본 df 반환return df_display, status, df_fullexcept Exception as e:import tracebackreturn pd.DataFrame(), f"❌ 오류: {str(e)[:80]}", pd.DataFrame()# ============================================================# AI 분석 함수# ============================================================def analyze_announcement(detail_url, project_name, print_file=None, api_description="", progress=gr.Progress()):"""공고 본문출력파일을 다운로드하고 AI로 분석Args:detail_url: 공고 상세 링크project_name: 공고명3 unmodified linesif not detail_url:yield "❌ 분석할 공고를 선택해주세요."returnoutput = f"# 📄 {project_name}\n\n---\n\n"all_text = f"## 공고명: {project_name}\n\n"if api_description:all_text += f"### 사업개요:\n{api_description}\n\n"output += f"📋 **사업개요**\n{api_description}\n\n"yield output# ⭐ 본문출력파일이 없으면 상세 페이지에서 추출 시도if not print_file or not isinstance(print_file, dict) or not print_file.get("url"):progress(0.1, desc="상세 페이지에서 본문출력파일 검색 중...")output += "🔍 **상세 페이지에서 본문출력파일 검색 중...**\n"yield outputtry:content, attachments, scraped_print_file = fetch_announcement_detail(detail_url)if scraped_print_file:print_file = scraped_print_fileoutput += f" ✅ 본문출력파일 발견: `{print_file.get('filename')}`\n\n"9 unmodified linesexcept Exception as e:output += f" ❌ 상세 페이지 조회 실패: {str(e)}\n\n"yield outputextracted_text = None# ⭐ 본문출력파일 분석 (핵심!)if print_file and isinstance(print_file, dict) and print_file.get("url"):output += f"📄 **본문출력파일 발견**\n"output += f" - 파일명: `{print_file.get('filename', '알 수 없음')}`\n"output += f" - 형식: {print_file.get('type', 'unknown').upper()}\n\n"yield outputwith tempfile.TemporaryDirectory() as tmp_dir:progress(0.2, desc="본문출력파일 다운로드 중...")output += f"📥 다운로드 중...\n"yield outputfile_path, error = download_file(print_file['url'], tmp_dir, print_file.get('filename'))if error:output += f" - ⚠️ 다운로드 실패: {error}\n"yield output1 unmodified lineprogress(0.5, desc="텍스트 추출 중...")output += f" - ✅ 다운로드 완료\n"yield output# 텍스트 추출text, err = extract_text_from_file(file_path)if text:extracted_text = text6 unmodified linesoutput += "⚠️ **본문출력파일이 없습니다.**\n"output += "사업개요만으로 분석을 진행합니다.\n\n"yield outputif len(all_text) < 100 and not extracted_text:output += "\n❌ **분석할 내용이 충분하지 않습니다.**\n"output += "본문출력파일이 없거나 텍스트 추출에 실패했습니다.\n"yield outputreturnoutput += f"\n📊 **분석 준비 완료** (총 {len(all_text):,}자)\n\n---\n\n## 🤖 AI 분석 결과\n\n"yield outputprogress(0.7, desc="AI 분석 중...")system_prompt = """당신은 정부 지원사업 공고 분석 전문가입니다.주어진 공고 내용을 분석하여 다음 항목을 명확하게 정리해주세요:3 unmodified lines- 신청 기간, 신청 방법, 제출 서류- 중요 유의사항, 제한 사항- 이 사업의 핵심 포인트를 3줄로 요약"""messages = [{"role": "system", "content": system_prompt},{"role": "user", "content": f"다음 지원사업 공고를 분석해주세요:\n\n{all_text[:15000]}"}]for chunk in call_groq_api_stream(messages):output += chunkyield outputoutput += "\n\n---\n✅ **분석 완료**"yield output# ============================================================# 맞춤 과제 매칭 함수# ============================================================def analyze_uploaded_documents(files, progress=gr.Progress()):"""업로드된 문서들을 분석하여 기업 정보 추출"""if not files:yield "❌ 분석할 파일을 업로드해주세요."returnoutput = "# 📄 업로드 문서 분석 결과\n\n"all_extracted_text = []for i, file in enumerate(files):progress((i + 1) / len(files), desc=f"파일 분석 중... ({i+1}/{len(files)})")filename = os.path.basename(file.name) if hasattr(file, 'name') else f"파일_{i+1}"output += f"## 📎 {filename}\n\n"yield outputtry:text, error = extract_text_from_file(file.name if hasattr(file, 'name') else file)if text:5 unmodified linesexcept Exception as e:output += f"❌ 오류: {str(e)}\n\n"yield outputif all_extracted_text:output += "---\n\n## 🤖 AI 기업정보 추출\n\n"yield outputcombined_text = "\n\n".join([f"[{item['filename']}]\n{item['text'][:3000]}" for item in all_extracted_text])system_prompt = """당신은 기업 서류 분석 전문가입니다.주어진 문서들에서 다음 정보를 추출해주세요:1. 사업자 정보 (사업자등록번호, 법인등록번호, 상호, 대표자, 설립일, 주소, 업종)2 unmodified lines4. 인증/등록 정보 (부설연구소, 벤처기업 인증 등)5. 기타 특이사항JSON 형식으로 정리해주세요."""messages = [{"role": "system", "content": system_prompt},{"role": "user", "content": f"다음 기업 서류들을 분석해주세요:\n\n{combined_text[:12000]}"}]for chunk in call_groq_api_stream(messages):output += chunkyield outputoutput += "\n\n---\n✅ **문서 분석 완료**"yield outputdef match_announcements_with_profile(profile_data, announcements_df, progress=gr.Progress()):"""기업 프로필과 공고를 매칭"""if not profile_data:yield "❌ 기업 프로필을 먼저 입력해주세요."returnif announcements_df is None or (isinstance(announcements_df, pd.DataFrame) and announcements_df.empty):yield "❌ 매칭할 공고 데이터가 없습니다. 먼저 공고를 검색해주세요."returnoutput = "# 🎯 맞춤 과제 매칭 결과\n\n"output += "## 📋 입력된 기업 프로필\n\n"output += f"```json\n{json.dumps(profile_data, ensure_ascii=False, indent=2)[:2000]}\n```\n\n"output += "---\n\n## 🔍 AI 매칭 분석 중...\n\n"yield outputannouncements_text = ""df_to_use = announcements_df if isinstance(announcements_df, pd.DataFrame) else pd.DataFrame()for idx, row in df_to_use.head(20).iterrows():announcements_text += f"""### {row.get('지원사업명', '')}- 지원분야: {row.get('지원분야', '')}- 소관부처: {row.get('소관부처', '')}- 신청기간: {row.get('신청기간', '')}- 지원대상: {row.get('지원대상', '')}---"""system_prompt = """당신은 정부 지원사업 매칭 전문가입니다.기업 프로필과 공고 목록을 분석하여 신청 가능한 과제를 추천해주세요.각 공고에 대해:1 unmodified line- ⚠️ 확인필요: 일부 조건 확인 필요- ❌ 부적합: 자격 미달추천 순위와 이유를 설명해주세요."""messages = [{"role": "system", "content": system_prompt},{"role": "user", "content": f"기업 프로필:\n{json.dumps(profile_data, ensure_ascii=False)}\n\n공고 목록:\n{announcements_text[:8000]}"}]for chunk in call_groq_api_stream(messages):output += chunkyield outputoutput += "\n\n---\n✅ **매칭 분석 완료**"yield output# ============================================================# 캐시 관리 함수# ============================================================def get_cache_info():"""캐시 상태 정보 반환"""if not CACHE_AVAILABLE:return "⚠️ 캐시 시스템 미사용 (API 직접 호출)"status = get_sync_status()info = f"""📦 **캐시 상태**- 총 캐시: {status.get('total_count', 0):,}건2 unmodified lines- 스케줄러: {'✅ 활성' if status.get('scheduler_available') else '❌ 비활성'}"""return infodef do_manual_sync():"""수동 동기화 실행"""if not CACHE_AVAILABLE:return "⚠️ 캐시 시스템을 사용할 수 없습니다."return manual_sync()# ============================================================# CSS 스타일 - Neumorphism Design# ============================================================CUSTOM_CSS = """@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;500;700&display=swap');/* ═══════════════════════════════════════════════════════════🔘 NEUMORPHISM 핵심 변수═══════════════════════════════════════════════════════════ */8 unmodified lines--neu-success: #48bb78;--neu-warning: #ed8936;}/* ═══════════════════════════════════════════════════════════📦 기본 컨테이너═══════════════════════════════════════════════════════════ */.gradio-container {font-family: 'Noto Sans KR', sans-serif !important;background: var(--neu-bg) !important;max-width: 100% !important;width: 100% !important;margin: 0 auto !important;min-height: 100vh;padding: 20px !important;}body, .dark {background: var(--neu-bg) !important;}/* ═══════════════════════════════════════════════════════════📐 전체 폭 강제 (탭 전환 시 폭 변화 방지)════════════════════════════════════════════════���══════════ */.gr-tabs, .tabs, .tabitem, .tab-content {width: 100% !important;max-width: 100% !important;}.gr-tab-item, .tab-nav button {flex-shrink: 0 !important;}.gr-row, .gr-column, .row, .column {width: 100% !important;max-width: 100% !important;}.gr-block, .block {width: 100% !important;max-width: 100% !important;}/* 탭 패널 내부 컨텐츠 */.gr-tabitem > div, .tabitem > div {width: 100% !important;max-width: 100% !important;}/* 컨테이너 내부 요소들 */.contain {width: 100% !important;max-width: 100% !important;}#component-0 {width: 100% !important;max-width: 100% !important;}/* ═══════════════════════════════════════════════════════════🎯 헤더 배너 (Neumorphism)═══════════════════════════════════════════════════════════ */7 unmodified lines12px 12px 24px var(--neu-shadow-dark),-12px -12px 24px var(--neu-shadow-light);}.header-banner h1 {color: var(--neu-text-dark) !important;text-shadow: 2px 2px 4px var(--neu-shadow-light), -1px -1px 3px rgba(0,0,0,0.1);}.header-banner p {color: var(--neu-text) !important;}/* ═══════════════════════════════════════════════════════════🏷️ 배지 스타일═══════════════════════════════════════════════════════════ */10 unmodified lines4px 4px 8px var(--neu-shadow-dark),-4px -4px 8px var(--neu-shadow-light);}/* ═══════════════════════════════════════════════════════════📋 섹션 헤더═══════════════════════════════════════════════════════════ */8 unmodified lines6px 6px 12px var(--neu-shadow-dark),-6px -6px 12px var(--neu-shadow-light);}/* ═══════════════════════════════════════════════════════════🔘 버튼 스타일═══════════════════════════════════════════════════════════ */9 unmodified lines-6px -6px 12px var(--neu-shadow-light) !important;transition: all 0.2s ease !important;}.gr-button:hover, button.primary:hover, button.secondary:hover {box-shadow:4px 4px 8px var(--neu-shadow-dark),-4px -4px 8px var(--neu-shadow-light) !important;transform: translateY(-1px);}.gr-button:active, button.primary:active, button.secondary:active {box-shadow:inset 4px 4px 8px var(--neu-shadow-dark),inset -4px -4px 8px var(--neu-shadow-light) !important;transform: translateY(0);}/* 🟢 분석 버튼 */.analyze-btn button, .analyze-btn {background: linear-gradient(145deg, #52c992, #3ea87a) !important;2 unmodified lines6px 6px 12px var(--neu-shadow-dark),-6px -6px 12px var(--neu-shadow-light) !important;}.analyze-btn:hover button, .analyze-btn:hover {background: linear-gradient(145deg, #3ea87a, #359968) !important;}/* 🟣 매칭 버튼 */.match-btn button, .match-btn {background: linear-gradient(145deg, #9f7aea, #805ad5) !important;2 unmodified lines6px 6px 12px var(--neu-shadow-dark),-6px -6px 12px var(--neu-shadow-light) !important;}/* 🟠 동기화 버튼 */.sync-btn button, .sync-btn {background: linear-gradient(145deg, #f6ad55, #ed8936) !important;2 unmodified lines4px 4px 8px var(--neu-shadow-dark),-4px -4px 8px var(--neu-shadow-light) !important;}/* ═══════════════════════════════════════════════════════════📝 입력 필드 (Inset 효과)═══════════════════════════════════════════════════════════ */9 unmodified linesinset 4px 4px 8px var(--neu-shadow-dark),inset -4px -4px 8px var(--neu-shadow-light) !important;}.gr-textbox textarea:focus, .gr-textbox input:focus,input[type="text"]:focus, textarea:focus {outline: none !important;1 unmodified lineinset 6px 6px 12px var(--neu-shadow-dark),inset -6px -6px 12px var(--neu-shadow-light) !important;}/* ═══════════════════════════════════════════════════════════📊 데이터프레임 테이블═══════════════════════════════════════════════════════════ */5 unmodified lines8px 8px 16px var(--neu-shadow-dark),-8px -8px 16px var(--neu-shadow-light) !important;}.gr-dataframe th, .dataframe th {background: var(--neu-bg) !important;color: var(--neu-text-dark) !important;1 unmodified linepadding: 14px 12px !important;border-bottom: 2px solid var(--neu-shadow-dark) !important;}.gr-dataframe td, .dataframe td {background: var(--neu-bg) !important;color: var(--neu-text) !important;padding: 12px !important;border-bottom: 1px solid rgba(163, 177, 198, 0.3) !important;}.gr-dataframe tr:hover td, .dataframe tr:hover td {background: rgba(74, 125, 189, 0.1) !important;}/* ═══════════════════════════════════════════════════════════📁 탭 스타일═══════════════════════════════════════════════════════════ */.gr-tabs, .tabs {background: var(--neu-bg) !important;}.gr-tab-item, .tab-nav button {background: var(--neu-bg) !important;border: none !important;6 unmodified lines4px -4px 8px var(--neu-shadow-dark),-4px -4px 8px var(--neu-shadow-light) !important;}.gr-tab-item.selected, .tab-nav button.selected {background: var(--neu-bg) !important;color: var(--neu-primary) !important;1 unmodified lineinset 3px 3px 6px var(--neu-shadow-dark),inset -3px -3px 6px var(--neu-shadow-light) !important;}/* ═══════════════════════════════════════════════════════════✅ 체크박스═══════════════════════════════════════════════════════════ */8 unmodified linesinset -3px -3px 6px var(--neu-shadow-light);cursor: pointer;}.gr-checkbox input[type="checkbox"]:checked {background: linear-gradient(145deg, #48bb78, #38a169);box-shadow:3px 3px 6px var(--neu-shadow-dark),-3px -3px 6px var(--neu-shadow-light);}/* ═══════════════════════════════════════════════════════════📋 캐시 정보 박스═══════════════════════════════════════════════════════════ */9 unmodified linesinset 4px 4px 8px var(--neu-shadow-dark),inset -4px -4px 8px var(--neu-shadow-light) !important;}/* ═══════════════════════════════════════════════════════════📄 카드/패널 스타일═══════════════════════════════════════════════════════════ */6 unmodified lines8px 8px 16px var(--neu-shadow-dark),-8px -8px 16px var(--neu-shadow-light) !important;}/* ═══════════════════════════════════════════════════════════📊 라벨 스타일═══════════════════════════════════════════════════════════ */2 unmodified linesfont-weight: 600 !important;text-shadow: 1px 1px 2px var(--neu-shadow-light);}/* ═════════════════════════════════��═════════════════════════🔗 링크 스타일═══════════════════════════════════════════════════════════ */3 unmodified linesfont-weight: 600;transition: all 0.2s ease;}a:hover {color: #3a6aa8 !important;text-shadow: 0 0 8px rgba(74, 125, 189, 0.3);}/* ═══════════════════════════════════════════════════════════📱 스크롤바 스타일═══════════════════════════════════════════════════════════ */1 unmodified linewidth: 10px;height: 10px;}::-webkit-scrollbar-track {background: var(--neu-bg);border-radius: 10px;box-shadow: inset 2px 2px 4px var(--neu-shadow-dark);}::-webkit-scrollbar-thumb {background: linear-gradient(145deg, #d1d9e6, #b8c0cc);border-radius: 10px;1 unmodified line2px 2px 4px var(--neu-shadow-dark),-2px -2px 4px var(--neu-shadow-light);}/* ═══════════════════════════════════════════════════════════🎨 마크다운 출력 영역═══════════════════════════════════════════════════════════ */6 unmodified linesinset 4px 4px 8px var(--neu-shadow-dark),inset -4px -4px 8px var(--neu-shadow-light) !important;}.gr-markdown h1, .gr-markdown h2, .gr-markdown h3 {color: var(--neu-text-dark) !important;text-shadow: 2px 2px 4px var(--neu-shadow-light);}/* ═══════════════════════════════════════════════════════════✨ 애니메이션═══════════════════════════════════════════════════════════ */9 unmodified lines-12px -12px 24px var(--neu-shadow-light);}}.loading {animation: pulse-neu 1.5s ease-in-out infinite;}"""# ============================================================# 메인 인터페이스# ============================================================def create_interface():with gr.Blocks(title="기업마당 AI 분석기", css=CUSTOM_CSS) as demo:gr.HTML("""13 unmodified lines</div></div>""")# 상태 변수selected_url = gr.State("")selected_name = gr.State("")selected_print_file = gr.State(None) # ⭐ 본문출력파일 (dict)selected_description = gr.State("")current_df = gr.State(value=pd.DataFrame())company_profile = gr.State(value={})with gr.Tabs():# 탭 1: 공고 검색with gr.Tab("🔍 공고 검색"):# 캐시 상태 표시with gr.Row():cache_status = gr.Markdown(value=get_cache_info(), elem_classes=["cache-info"])sync_btn = gr.Button("🔄 수동 동기화", size="sm", elem_classes=["sync-btn"])with gr.Row():keyword_input = gr.Textbox(label="🔍 검색어", placeholder="예: AI, 스타트업, R&D", scale=3)category_dropdown = gr.Dropdown(label="📂 지원분야", choices=list(CATEGORY_CODES.keys()), value="전체", scale=1)6 unmodified linespage_input = gr.Number(label="📄 페이지", value=1, minimum=1, scale=1)rows_dropdown = gr.Dropdown(label="📊 표시개수", choices=[10, 15, 20, 30, 50], value=20, scale=1)search_btn = gr.Button("🔎 검색", variant="primary", scale=2)status_output = gr.Textbox(label="📊 조회 결과", interactive=False)results_output = gr.Dataframe(label="📋 공고 목록 (행 클릭으로 선택)", wrap=True, interactive=False)with gr.Row():prev_btn = gr.Button("◀️ 이전", size="sm")next_btn = gr.Button("다음 ▶️", size="sm")open_link_btn = gr.Button("🔗 선택 공고 열기", size="sm", variant="secondary")# 선택된 공��� 링크를 표시하는 HTML (JavaScript로 새 탭 열기)link_output = gr.HTML(value="<div style='padding: 10px; color: #5a6677;'>📌 공고를 선택하면 여기에 링크가 표시됩니다</div>")# 탭 2: AI 분석with gr.Tab("🤖 AI 분석"):with gr.Row(equal_height=False):with gr.Column(scale=1, min_width=300):selected_info = gr.Textbox(label="📌 선택된 공고", placeholder="공고 검색 탭에서 선택", lines=5, interactive=False)analyze_btn = gr.Button("🚀 AI 분석 시작", variant="primary", size="lg", elem_classes=["analyze-btn"])with gr.Column(scale=3, min_width=600):analysis_output = gr.Markdown(value="### 📊 분석 결과\n\n*공고를 선택하고 분석 버튼을 클릭하세요*", height=600)# 탭 3: 맞춤 과제 추출with gr.Tab("🎯 맞춤 과제 추출"):gr.HTML("""<div style="background: var(--neu-bg, #e0e5ec); color: #3d4856; padding: 24px 28px; border-radius: 20px; margin-bottom: 24px; box-shadow: 8px 8px 16px #a3b1c6, -8px -8px 16px #ffffff;"><h2 style="margin: 0 0 8px 0; text-shadow: 2px 2px 4px #ffffff;">🎯 나만의 맞춤 과제 추출</h2><p style="margin: 0; color: #5a6677;">기업 정보를 입력하고 문서를 업로드하면 AI가 신청 가능한 과제를 자동으로 매칭해드립니다.</p></div>""")with gr.Tabs():# 서브탭 1: 기업 기본정보with gr.Tab("1️⃣ 기업 기본정보"):with gr.Row():with gr.Column():5 unmodified linescompany_type = gr.Dropdown(label="기업형태", choices=COMPANY_TYPE_OPTIONS, value="법인사업자")corp_type = gr.Dropdown(label="법인 종류", choices=CORP_TYPE_OPTIONS, value="주식회사")company_size = gr.Dropdown(label="기업규모", choices=COMPANY_SIZE_OPTIONS, value="소기업")with gr.Column():gr.HTML('<div class="section-header">🏆 인증 현황</div>')venture_cert = gr.Checkbox(label="벤처기업 인증")3 unmodified linessmall_biz_cert = gr.Checkbox(label="소상공인확인서 보유")social_venture = gr.Checkbox(label="소셜벤처")startup_flag = gr.Checkbox(label="스타트업")with gr.Column():gr.HTML('<div class="section-header">📍 소재지 정보</div>')hq_sido = gr.Dropdown(label="본사 소재지 (시/도)", choices=SIDO_LIST, value="서울특별시")2 unmodified linesindustrial_complex = gr.Checkbox(label="산업단지 입주")free_zone = gr.Checkbox(label="규제자유특구 소재")non_capital = gr.Checkbox(label="비수도권 (지방기업)")gr.HTML('<div class="section-header">📊 업종 정보</div>')industry_major = gr.Dropdown(label="주업종 (대분류)", choices=INDUSTRY_MAJOR_OPTIONS, value="C. 제조업")is_manufacturing = gr.Checkbox(label="제조업 여부")is_knowledge_service = gr.Checkbox(label="지식서비스업 여부")# 서브탭 2: 대표자/인력 정보with gr.Tab("2️⃣ 대표자/인력 정보"):with gr.Row():with gr.Column():5 unmodified linessenior_ceo = gr.Checkbox(label="시니어창업자 (만40세 이상)")women_company = gr.Checkbox(label="여성기업확인서 보유")disabled_company = gr.Checkbox(label="장애인기업확인서 보유")with gr.Column():gr.HTML('<div class="section-header">👥 고용 현황</div>')insurance_employees = gr.Number(label="4대보험 가입자 수", value=0, minimum=0)1 unmodified lineyouth_employees = gr.Number(label="청년고용 인원", value=0, minimum=0)female_ratio = gr.Slider(label="여성고용 비율 (%)", minimum=0, maximum=100, value=0)new_hire_plan = gr.Number(label="신규채용 계획 (명)", value=0, minimum=0)with gr.Column():gr.HTML('<div class="section-header">🔬 연구인력/역량</div>')rd_personnel = gr.Number(label="연구인력 수", value=0, minimum=0)1 unmodified lineresearch_center = gr.Checkbox(label="기업부설연구소 등록")rd_dept = gr.Checkbox(label="연구개발전담부서 등록")patent_count = gr.Number(label="보유 특허 수", value=0, minimum=0)# 서브탭 3: 재무 정보with gr.Tab("3️⃣ 재무 정보"):with gr.Row():with gr.Column():3 unmodified linesoperating_profit = gr.Number(label="영업이익 (백만원)", value=0)net_income = gr.Number(label="당기순이익 (백만원)", value=0)export_amount = gr.Number(label="수출액 (천달러)", value=0, minimum=0)with gr.Column():gr.HTML('<div class="section-header">📊 재무건전성</div>')capital = gr.Number(label="자본금 (백만원)", value=0, minimum=0)2 unmodified linescredit_grade = gr.Dropdown(label="신용등급", choices=CREDIT_GRADE_OPTIONS, value="미평가")tcb_grade = gr.Dropdown(label="TCB 등급", choices=TCB_GRADE_OPTIONS, value="미평가")capital_impairment = gr.Checkbox(label="자본잠식 여부")with gr.Column():gr.HTML('<div class="section-header">🔬 R&D 투자</div>')rd_investment = gr.Number(label="연간 R&D 투자액 (백만원)", value=0, minimum=0)gov_project_exp = gr.Checkbox(label="정부과제 수행 경험")gov_support_3yr = gr.Number(label="최근 3년 정부지원금 (백만원)", value=0, minimum=0)# 서브탭 4: 기술분야/제한사항with gr.Tab("4️⃣ 기술분야/제한사항"):with gr.Row():with gr.Column():3 unmodified linesgreen_tech = gr.Checkbox(label="녹색기술 분야")digital_transform = gr.Checkbox(label="디지털전환 분야")defense_industry = gr.Checkbox(label="국방/방산 분야")with gr.Column():gr.HTML('<div class="section-header">📜 인증/ISO</div>')iso_certs = gr.CheckboxGroup(label="ISO 인증", choices=ISO_CERT_OPTIONS)gmp_cert = gr.Checkbox(label="GMP 인증")with gr.Column():gr.HTML('<div class="section-header">⚠️ 결격사유 확인</div>')tax_delinquent = gr.Checkbox(label="국세 체납")1 unmodified linegov_project_fail = gr.Checkbox(label="정부과제 불성실")bankruptcy = gr.Checkbox(label="휴/폐업 이력")financial_default = gr.Checkbox(label="금융기관 연체")# 서브탭 5: 문서 업로드 및 매칭with gr.Tab("5️⃣ 문서 ���로드 & 매칭"):gr.HTML("""<div style="background: var(--neu-bg, #e0e5ec); border-radius: 15px; padding: 18px 22px; margin-bottom: 16px; box-shadow: inset 4px 4px 8px #a3b1c6, inset -4px -4px 8px #ffffff;"><h3 style="margin: 0 0 8px 0; color: #3d4856;">📁 문서 업로드</h3><p style="margin: 0; color: #5a6677;">사업자등록증, 등기부등본, 재무제표, 중소기업확인서 등을 업로드하면 AI가 자동으로 정보를 추출합니다.</p></div>""")with gr.Row():with gr.Column(scale=1):file_upload = gr.File(2 unmodified linesfile_types=[".hwp", ".hwpx", ".pdf", ".txt", ".xlsx", ".xls"])analyze_docs_btn = gr.Button("📄 문서 분석", variant="secondary", size="lg")with gr.Column(scale=2):doc_analysis_output = gr.Markdown(value="### 📄 문서 분석 결과\n\n*문서를 업로드하고 분석 버튼을 클릭하세요*", height=400)gr.HTML('<hr style="margin: 24px 0;">')with gr.Row():save_profile_btn = gr.Button("💾 프로필 저장", variant="secondary", size="lg")match_btn = gr.Button("🎯 맞춤 과제 매칭 시작", variant="primary", size="lg", elem_classes=["match-btn"])profile_status = gr.Textbox(label="프로필 저장 상태", interactive=False)match_output = gr.Markdown(value="### 🎯 매칭 결과\n\n*프로필을 저장하고 매칭 버튼을 클릭하세요*", height=500)# ============================================================# 이벤트 핸들러# ============================================================def search_fn(keyword, category, region, org_type, sort_by, status_filter, page, rows):display_df, status, full_df = fetch_announcements(keyword or "", category or "전체", region or "전체(지역)",org_type or "전체", sort_by or "등록일순",status_filter or "진행중", int(page) if page else 1, int(rows) if rows else 20)return display_df, status, full_dfdef prev_fn(page, keyword, category, region, org_type, sort_by, status_filter, rows):new_page = max(1, int(page) - 1) if page else 1display_df, status, full_df = fetch_announcements(keyword or "", category or "전체", region or "전체(지역)",org_type or "전체", sort_by or "등록일순",status_filter or "진행중", new_page, int(rows) if rows else 20)return display_df, status, full_df, new_pagedef next_fn(page, keyword, category, region, org_type, sort_by, status_filter, rows):new_page = int(page) + 1 if page else 2display_df, status, full_df = fetch_announcements(keyword or "", category or "전체", region or "전체(지역)",org_type or "전체", sort_by or "등록일순",status_filter or "진행중", new_page, int(rows) if rows else 20)return display_df, status, full_df, new_pagedef on_row_select(evt: gr.SelectData, df):if evt.index[0] < len(df):row = df.iloc[evt.index[0]]2 unmodified linesattachments = row.get("첨부파일", [])print_file = row.get("본문출력파일", None) # ⭐ AI 분석용 핵심 파일description = row.get("사업개요", "")# URL 정규화full_url = urlif url and url.startswith('/'):full_url = f"https://www.bizinfo.go.kr{url}"# 정보 표시 (AI 분석 탭용)info_parts = [f"📌 {name}", f"🔗 {full_url}"]# 본문출력파일 (AI 분석 대상)if print_file:info_parts.append(f"\n\n📄 **본문출력파일 (AI 분석 대상)**:")info_parts.append(f" - {print_file.get('filename', '파일')}")# 일반 첨부파일 (서식, 양식)if attachments and len(attachments) > 0:info_parts.append(f"\n\n📎 기타 첨부파일 {len(attachments)}개:")for att in attachments:info_parts.append(f" - {att.get('filename', '파일')}")info = "\n".join(info_parts)# 링크 HTML (첫 번째 탭용)if full_url:link_html = f'''<div style="background: var(--neu-bg, #e0e5ec); padding: 16px 20px; border-radius: 15px;box-shadow: inset 4px 4px 8px #a3b1c6, inset -4px -4px 8px #ffffff;"><div style="font-weight: 700; color: #3d4856; margin-bottom: 8px;">📌 {name}</div><a href="{full_url}" target="_blank"style="display: inline-block; background: linear-gradient(145deg, #4a7dbd, #3a6aa8);color: white !important; padding: 10px 20px; border-radius: 25px;text-decoration: none; font-weight: 600; margin-top: 8px;box-shadow: 4px 4px 8px #a3b1c6, -4px -4px 8px #ffffff;">🔗 기업마당에서 상세보기</a></div>'''else:link_html = "<div style='padding: 10px; color: #5a6677;'>⚠️ 링크 정보가 없습니다</div>"return url, name, print_file, description, info, link_htmlreturn "", "", None, "", "", "<div style='padding: 10px; color: #5a6677;'>📌 공고를 선택하세요</div>"def save_profile_fn(biz_num, corp_num, comp_name, est_date, comp_type, corp_tp, comp_size,venture, innobiz, mainbiz, sme, small_biz, social, startup,sido, sigungu, innov_city, ind_complex, free_z, non_cap,7 unmodified linescore_ind, strat_tech, green, digital, defense,iso, gmp,tax_del, local_tax, gov_fail, bankrupt, fin_def):profile = {"사업자정보": {"사업자등록번호": biz_num, "법인등록번호": corp_num, "상호": comp_name,37 unmodified lines}}return profile, "✅ 프로필이 저장되었습니다."def sync_and_update():result = do_manual_sync()info = get_cache_info()return info, result# 이벤트 연결search_btn.click(fn=search_fn, inputs=[keyword_input, category_dropdown, region_dropdown, org_type_dropdown,sort_dropdown, status_dropdown, page_input, rows_dropdown],outputs=[results_output, status_output, current_df])keyword_input.submit(fn=search_fn, inputs=[keyword_input, category_dropdown, region_dropdown, org_type_dropdown,sort_dropdown, status_dropdown, page_input, rows_dropdown],outputs=[results_output, status_output, current_df])# 수동 동기화 버튼sync_btn.click(fn=sync_and_update, outputs=[cache_status, status_output])# 페이지네이션 이벤트prev_btn.click(fn=prev_fn, inputs=[page_input, keyword_input, category_dropdown, region_dropdown,org_type_dropdown, sort_dropdown, status_dropdown, rows_dropdown],outputs=[results_output, status_output, current_df, page_input])next_btn.click(fn=next_fn, inputs=[page_input, keyword_input, category_dropdown, region_dropdown,org_type_dropdown, sort_dropdown, status_dropdown, rows_dropdown],outputs=[results_output, status_output, current_df, page_input])# 행 선택 시 link_output도 업데이트results_output.select(fn=on_row_select, inputs=[current_df],outputs=[selected_url, selected_name, selected_print_file, selected_description, selected_info, link_output])# 바로가기 버튼 클릭 시 - JavaScript로 새 탭 열기def open_selected_link(url):if url:full_url = url if url.startswith('http') else f"https://www.bizinfo.go.kr{url}"return f'''<script>window.open("{full_url}", "_blank");</script><div style="padding: 10px; color: #48bb78;">✅ 새 탭에서 열렸습니다</div>'''return "<div style='padding: 10px; color: #ed8936;'>⚠️ 먼저 공고를 선택하세요</div>"open_link_btn.click(fn=open_selected_link, inputs=[selected_url], outputs=[link_output])analyze_btn.click(fn=analyze_announcement, inputs=[selected_url, selected_name, selected_print_file, selected_description],outputs=[analysis_output])analyze_docs_btn.click(fn=analyze_uploaded_documents, inputs=[file_upload], outputs=[doc_analysis_output])save_profile_btn.click(fn=save_profile_fn,inputs=[biz_number, corp_number, company_name, establish_date, company_type, corp_type, company_size,11 unmodified linestax_delinquent, local_tax_delinquent, gov_project_fail, bankruptcy, financial_default],outputs=[company_profile, profile_status])match_btn.click(fn=match_announcements_with_profile, inputs=[company_profile, current_df], outputs=[match_output])return demo# ============================================================# 앱 시작# ============================================================if __name__ == "__main__":# 캐시 시스템 초기화 (백그라운드 스케줄러 시작)if CACHE_AVAILABLE:print("🚀 캐시 시스템 초기화 중...")status = initialize_cache_system()print(f"✅ 캐시 상태: {status}")demo = create_interface()demo.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False)
app.py+333-50