Update app.py
Browse files123451232 unmodified lines67814910111 unmodified line1314152216171819272820212223243435363738252627284329453031483233342 unmodified lines37383957404142434463454647484950705152737453545556795758592 unmodified lines62636488896566672 unmodified lines70717298737475761037778799 unmodified lines899091119929312294951259697982 unmodified lines1011021031341041051061071391081091421101111121131141481491151161171 unmodified line1191201211571221591601231621241251261271281291691301311721731321331341351781361371381 unmodified line1401411421861871881891901431441931451461473 unmodified lines1511521532031541552061561571581592112121601611621632171641652201661671689 unmodified lines1781791802361812382391821831841851862451871881891902501912521921931941 unmodified line1961971982602611992002016 unmodified lines2082092102742112122132142152802162172832182192203 unmodified lines2242252262932272282292302982312322333022342353053063073083092362372382392403152412423182432442452462473242482492505 unmodified lines2562572583362592602613402623422632642652 unmodified lines2682692703512712722732743562752762773602782793633642802812822832843702852862873742882892902912923802932942952963852972982993003013023923033043051 unmodified line3073083094003103113123134053143153164093173184124134144154163193203213224213233243252 unmodified lines3283293304304313313323333343354374384394404413363374443383393408 unmodified lines3493503514593523533544 unmodified lines3593603614703623633644743653663677 unmodified lines37537637748837837938038149338238338449738538638710 unmodified lines3983994005144014024038 unmodified lines4124134145294154164179 unmodified lines4274284295454304314324334344355524364374384394404415594424434442 unmodified lines4474484495684504514525724534544552 unmodified lines4584594605814614624632 unmodified lines4664674685904694704719 unmodified lines4814824836064844854861 unmodified line4884894906144914924935 unmodified lines4995005016265025035041 unmodified line5065075086345095105115125135146415155165176455185195205215225236525245255266 unmodified lines5335345356655365375381 unmodified line5405415426735435445458 unmodified lines5545555566885575585595605615626955635645659 unmodified lines5755765777115785795806 unmodified lines5875885897245905915922 unmodified lines5955965977335985996003 unmodified lines6046056067436076086096107486116126131 unmodified line6156166177566186196206216227626236246251 unmodified line6276286297706306316326 unmodified lines6396406417836426436446457886466476489 unmodified lines65865966080466166266366480981081181281366566666713 unmodified lines6816826838338346846856866876886898416908436918456926936948496956966976 unmodified lines7047057068627077087097107118688697127137141 unmodified line7167177188778787197207211 unmodified line7237247258867268887277287295 unmodified lines7357367379007387397403 unmodified lines7447457469107477487492 unmodified lines7527537549197557567577589249257597607615 unmodified lines7677687699377707717721 unmodified line7747757769457777787791 unmodified line7817827839539547847857863 unmodified lines7907917929647937947952 unmodified lines7987998009738018028038048059799808068078083 unmodified lines8128138149908158168178189958198208211 unmodified line823824825100310048268278281 unmodified line83083183210128338348352 unmodified lines838839840102184184210248431026844845846103084784810331034103510368498508511 unmodified line85385485510448568578582 unmodified lines86186286310538648658662 unmodified lines86987087110628728738742 unmodified lines877878879107110728801074107588188288310791080884885886887108588888989010898918928937 unmodified lines901902903110390490590637 unmodified lines944945946114794794894995011521153951952953115795495595611611162957116411659589599601169961962963117396496511769669671179968118196997097111 unmodified lines983984985119998612019871203120412051206120798812099899909919921214993994"""기업마당 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 datetime
from 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 line ISO_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 lines title = 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 lines if 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 = None print_url = item.get("printFlpthNm", "") or "" print_name = item.get("printFileNm", "") or ""2 unmodified lines print_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 re description = 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 lines df = 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) * rows end_idx = start_idx + rows df_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:1 unmodified line 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}"1 unmodified line except Exception as e: import traceback return pd.DataFrame(), f"❌ 오류: {str(e)[:80]}"
# ============================================================# AI 분석 함수# ============================================================def analyze_announcement(detail_url, project_name, print_file=None, api_description="", progress=gr.Progress()): """공고 본문출력파일을 다운로드하고 AI로 분석 Args: detail_url: 공고 상세 링크 project_name: 공고명3 unmodified lines if not detail_url: yield "❌ 분석할 공고를 선택해주세요." return output = 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 output try: content, attachments, scraped_print_file = fetch_announcement_detail(detail_url) if scraped_print_file: print_file = scraped_print_file output += f" ✅ 본문출력파일 발견: `{print_file.get('filename')}`\n\n"9 unmodified lines except Exception as e: output += f" ❌ 상세 페이지 조회 실패: {str(e)}\n\n" yield output extracted_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 output with tempfile.TemporaryDirectory() as tmp_dir: progress(0.2, desc="본문출력파일 다운로드 중...") output += f"📥 다운로드 중...\n" yield output file_path, error = download_file(print_file['url'], tmp_dir, print_file.get('filename')) if error: output += f" - ⚠️ 다운로드 실패: {error}\n" yield output1 unmodified line progress(0.5, desc="텍스트 추출 중...") output += f" - ✅ 다운로드 완료\n" yield output # 텍스트 추출 text, err = extract_text_from_file(file_path) if text: extracted_text = text6 unmodified lines output += "⚠️ **본문출력파일이 없습니다.**\n" output += "사업개요만으로 분석을 진행합니다.\n\n" yield output if len(all_text) < 100 and not extracted_text: output += "\n❌ **분석할 내용이 충분하지 않습니다.**\n" output += "본문출력파일이 없거나 텍스트 추출에 실패했습니다.\n" yield output return output += f"\n📊 **분석 준비 완료** (총 {len(all_text):,}자)\n\n---\n\n## 🤖 AI 분석 결과\n\n" yield output progress(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 += chunk yield output output += "\n\n---\n✅ **분석 완료**" yield output
# ============================================================# 맞춤 과제 매칭 함수# ============================================================def analyze_uploaded_documents(files, progress=gr.Progress()): """업로드된 문서들을 분석하여 기업 정보 추출""" if not files: yield "❌ 분석할 파일을 업로드해주세요." return output = "# 📄 업로드 문서 분석 결과\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 output try: text, error = extract_text_from_file(file.name if hasattr(file, 'name') else file) if text:5 unmodified lines except Exception as e: output += f"❌ 오류: {str(e)}\n\n" yield output if all_extracted_text: output += "---\n\n## 🤖 AI 기업정보 추출\n\n" yield output combined_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 += chunk yield output output += "\n\n---\n✅ **문서 분석 완료**" yield output
def match_announcements_with_profile(profile_data, announcements_df, progress=gr.Progress()): """기업 프로필과 공고를 매칭""" if not profile_data: yield "❌ 기업 프로필을 먼저 입력해주세요." return if announcements_df is None or (isinstance(announcements_df, pd.DataFrame) and announcements_df.empty): yield "❌ 매칭할 공고 데이터가 없습니다. 먼저 공고를 검색해주세요." return output = "# 🎯 맞춤 과제 매칭 결과\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 output announcements_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 += chunk yield output output += "\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 info
def 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;}
/* ═══════════════════════════════════════════════════════════ 📦 기본 컨테이너 ═══════════════════════════════════════════════════════════ */4 unmodified lines margin: 0 auto !important; min-height: 100vh;}
body, .dark { background: var(--neu-bg) !important;}
/* ═══════════════════════════════════════════════════════════ 🎯 헤더 배너 (Neumorphism) ═══════════════════════════════════════════════════════════ */7 unmodified lines 12px 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 lines 4px 4px 8px var(--neu-shadow-dark), -4px -4px 8px var(--neu-shadow-light);}
/* ═══════════════════════════════════════════════════════════ 📋 섹션 헤더 ═══════════════════════════════════════════════════════════ */8 unmodified lines 6px 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 lines 6px 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 lines 6px 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 lines 4px 4px 8px var(--neu-shadow-dark), -4px -4px 8px var(--neu-shadow-light) !important;}
/* ═══════════════════════════════════════════════════════════ 📝 입력 필드 (Inset 효과) ═══════════════════════════════════════════════════════════ */9 unmodified lines inset 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 line inset 6px 6px 12px var(--neu-shadow-dark), inset -6px -6px 12px var(--neu-shadow-light) !important;}
/* ═══════════════════════════════════════════════════════════ 📊 데이터프레임 테이블 ═══════════════════════════════════════════════════════════ */5 unmodified lines 8px 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 line padding: 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 lines 4px -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 line inset 3px 3px 6px var(--neu-shadow-dark), inset -3px -3px 6px var(--neu-shadow-light) !important;}
/* ═══════════════════════════════════════════════════════════ ✅ 체크박스 ═══════════════════════════════════════════════════════════ */8 unmodified lines inset -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 lines inset 4px 4px 8px var(--neu-shadow-dark), inset -4px -4px 8px var(--neu-shadow-light) !important;}
/* ═══════════════════════════════════════════════════════════ 📄 카드/패널 스타일 ═══════════════════════════════════════════════════════════ */6 unmodified lines 8px 8px 16px var(--neu-shadow-dark), -8px -8px 16px var(--neu-shadow-light) !important;}
/* ═══════════════════════════════════════════════════════════ 📊 라벨 스타일 ═══════════════════════════════════════════════════════════ */2 unmodified lines font-weight: 600 !important; text-shadow: 1px 1px 2px var(--neu-shadow-light);}
/* ═══════════════════════════════════════════════════════════ 🔗 링크 스타일 ═══════════════════════════════════════════════════════════ */3 unmodified lines font-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 line width: 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 line 2px 2px 4px var(--neu-shadow-dark), -2px -2px 4px var(--neu-shadow-light);}
/* ═══════════════════════════════════════════════════════════ 🎨 마크다운 출력 영역 ═══════════════════════════════════════════════════════════ */6 unmodified lines inset 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 lines page_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") # 탭 2: AI 분석 with gr.Tab("🤖 AI 분석"): with gr.Row(): with gr.Column(scale=1):1 unmodified line 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) # 탭 3: 맞춤 과제 추출 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;">1 unmodified line <p style="margin: 0; opacity: 0.9;">기업 정보를 입력하고 문서를 업로드하면 AI가 신청 가능한 과제를 자동으로 매칭해드립니다.</p> </div> """) with gr.Tabs(): # 서브탭 1: 기업 기본정보 with gr.Tab("1️⃣ 기업 기본정보"): with gr.Row(): with gr.Column():5 unmodified lines company_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 lines small_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 lines industrial_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 lines senior_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 line youth_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 line research_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 lines operating_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 lines credit_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 lines green_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 line gov_project_fail = gr.Checkbox(label="정부과제 불성실") bankruptcy = gr.Checkbox(label="휴/폐업 이력") financial_default = gr.Checkbox(label="금융기관 연체") # 서브탭 5: 문서 업로드 및 매칭 with gr.Tab("5️⃣ 문서 업로드 & 매칭"): gr.HTML(""" <div style="background: #EBF5FF; border: 1px solid #3B82F6; border-radius: 8px; padding: 16px; margin-bottom: 16px;">1 unmodified line <p style="margin: 0; color: #1E3A8A;">사업자등록증, 등기부등본, 재무제표, 중소기업확인서 등을 업로드하면 AI가 자동으로 정보를 추출합니다.</p> </div> """) with gr.Row(): with gr.Column(scale=1): file_upload = gr.File(2 unmodified lines file_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 "등록일순",1 unmodified line display_cols = ["번호", "지원분야", "지원사업명", "신청기간", "소관부처", "등록일", "지원대상"] display_df = df[[c for c in display_cols if c in df.columns]] if not df.empty else df return display_df, status, df def prev_fn(page, keyword, category, region, org_type, sort_by, status_filter, rows): new_page = max(1, int(page) - 1) if page else 1 df, status = fetch_announcements(keyword or "", category or "전체", region or "전체(지역)",2 unmodified lines display_cols = ["번호", "지원분야", "지원사업명", "신청기간", "소관부처", "등록일", "지원대상"] display_df = df[[c for c in display_cols if c in df.columns]] if not df.empty else df return display_df, status, df, new_page def next_fn(page, keyword, category, region, org_type, sort_by, status_filter, rows): new_page = int(page) + 1 if page else 2 df, status = fetch_announcements(keyword or "", category or "전체", region or "전체(지역)",2 unmodified lines display_cols = ["번호", "지원분야", "지원사업명", "신청기간", "소관부처", "등록일", "지원대상"] display_df = df[[c for c in display_cols if c in df.columns]] if not df.empty else df return display_df, status, df, new_page def on_row_select(evt: gr.SelectData, df): if evt.index[0] < len(df): row = df.iloc[evt.index[0]]2 unmodified lines attachments = row.get("첨부파일", []) print_file = row.get("본문출력파일", None) # ⭐ AI 분석용 핵심 파일 description = row.get("사업개요", "") # 정보 표시 info_parts = [f"📌 {name}", f"🔗 {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) return url, name, print_file, description, info return "", "", 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 lines core_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]) 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 lines tax_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-222