Update app.py
Browse files83 unmodified lines848586878889909192939495969798991001017 unmodified lines10911011111211311411543 unmodified lines1591601611621631641651661671681691701711721 unmodified line174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219248 unmodified lines468469470471472473474235 unmodified lines71071171271371471571671771871972072172272372483 unmodified lines80880981081181281381481581683 unmodified lineslink = item.get("link", "") or item.get("pblancUrl", "")pblanc_id = item.get("seq", "") or item.get("pblancId", "")attachments = []file_url = item.get("flpthNm", "")file_name = item.get("fileNm", "")if file_url and file_name:attachments.append({"url": file_url, "filename": file_name, "type": Path(file_name).suffix.lower()[1:] if Path(file_name).suffix else "unknown"})# 추가 첨부파일 (print 파일)print_url = item.get("printFlpthNm", "")print_name = item.get("printFileNm", "")if print_url and print_name:if not any(att['url'] == print_url for att in attachments):attachments.append({"url": print_url, "filename": print_name, "type": Path(print_name).suffix.lower()[1:] if Path(print_name).suffix else "unknown"})description = item.get("description", "") or item.get("bsnsSumryCn", "")if description:7 unmodified lines"수행기관": exec_org, "등록일": pub_date, "조회수": item.get("inqireCo", "") or "","상세링크": link, "공고ID": pblanc_id,"사업개요": description[:200] + "..." if len(description) > 200 else description,"첨부파일": attachments, "지원대상": item.get("trgetNm", ""),"문의처": item.get("refrncNm", ""), "신청URL": item.get("rceptEngnHmpgUrl", ""),"_org_type": item_org_type, "_ongoing": item_ongoing, "_deadline": deadline,"_pub_date": pub_date, "_region": item_region,43 unmodified lines# ============================================================# AI 분석 함수# ============================================================def analyze_announcement(detail_url, project_name, api_attachments=None, api_description="", progress=gr.Progress()):"""공고 첨부파일을 다운로드하고 AI로 분석"""if not detail_url:yield "❌ 분석할 공고를 선택해주세요."returnoutput = f"# 📄 {project_name}\n\n---\n\n"attachments = api_attachments if api_attachments else []all_text = f"## 공고명: {project_name}\n\n"if api_description:1 unmodified lineoutput += f"📋 **사업개요**\n{api_description}\n\n"yield outputoutput += f"📎 **첨부파일 {len(attachments)}개 발견**\n\n"yield outputextracted_texts = []if attachments:with tempfile.TemporaryDirectory() as tmp_dir:for i, att in enumerate(attachments):progress(0.2 + (0.4 * i / len(attachments)), desc=f"파일 다운로드 중... ({i+1}/{len(attachments)})")output += f"📥 다운로드 중: `{att['filename']}`\n"yield outputfile_path, error = download_file(att['url'], tmp_dir, att['filename'])if error:output += f" - ⚠️ {error}\n"yield outputcontinueif file_path and file_path.lower().endswith('.zip'):extracted = extract_zip_files(file_path, tmp_dir)for ext_file in extracted:text, err = extract_text_from_file(ext_file)if text:extracted_texts.append({"filename": os.path.basename(ext_file), "text": text})output += f" - ✅ 텍스트 추출 성공 ({len(text):,} 글자)\n"yield outputelif file_path:text, err = extract_text_from_file(file_path)if text:extracted_texts.append({"filename": os.path.basename(file_path), "text": text})output += f" - ✅ 텍스트 추출 성공 ({len(text):,} 글자)\n"yield outputif extracted_texts:all_text += "### 첨부파일 내용:\n\n"for ext in extracted_texts:text_preview = ext['text'][:5000] if len(ext['text']) > 5000 else ext['text']all_text += f"#### 📄 {ext['filename']}\n{text_preview}\n\n"if len(all_text) < 100 and not extracted_texts:output += "\n❌ **분석할 내용이 충분하지 않습니다.**\n"yield outputreturn248 unmodified lines# 상태 변수selected_url = gr.State("")selected_name = gr.State("")selected_attachments = gr.State([])selected_description = gr.State("")current_df = gr.State(value=pd.DataFrame())company_profile = gr.State(value={})235 unmodified linesurl = row.get("상세링크", "")name = row.get("지원사업명", "")attachments = row.get("첨부파일", [])description = row.get("사업개요", "")att_info = ""if attachments and len(attachments) > 0:att_info = f"\n\n📎 첨부파일 {len(attachments)}개:"for att in attachments:att_info += f"\n - {att.get('filename', '파일')}"info = f"📌 {name}\n\n🔗 {url}{att_info}"return url, name, attachments, description, inforeturn "", "", [], "", ""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,83 unmodified linesexport_btn.click(fn=export_to_csv, inputs=[current_df], outputs=[csv_output])results_output.select(fn=on_row_select, inputs=[current_df],outputs=[selected_url, selected_name, selected_attachments, selected_description, selected_info])analyze_btn.click(fn=analyze_announcement, inputs=[selected_url, selected_name, selected_attachments, selected_description],outputs=[analysis_output])analyze_docs_btn.click(fn=analyze_uploaded_documents, inputs=[file_upload], outputs=[doc_analysis_output])83 unmodified lines848586878889909192939495969798991001011021031041051061071081091101111121137 unmodified lines12112212312412512612712812943 unmodified lines1731741751761771781791801811821831841851861871881891901911921 unmodified line194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240248 unmodified lines489490491492493494495235 unmodified lines73173273373473573673773873974074174274374474574674774874975075175275375475575683 unmodified lines84084184284384484584684784883 unmodified lineslink = 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)):url = url.strip()name = name.strip()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 = Noneprint_url = item.get("printFlpthNm", "") or ""print_name = item.get("printFileNm", "") or ""if print_url and print_name:print_url = print_url.strip()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:7 unmodified lines"수행기관": exec_org, "등록일": pub_date, "조회수": item.get("inqireCo", "") or "","상세링크": link, "공고ID": pblanc_id,"사업개요": description[:200] + "..." if len(description) > 200 else description,"첨부파일": attachments, # 일반 첨부파일 (서식, 양식)"본문출력파일": print_file, # ⭐ AI 분석용 핵심 파일"지원대상": item.get("trgetNm", ""),"문의처": item.get("refrncNm", ""), "신청URL": item.get("rceptEngnHmpgUrl", ""),"_org_type": item_org_type, "_ongoing": item_ongoing, "_deadline": deadline,"_pub_date": pub_date, "_region": item_region,43 unmodified lines# ============================================================# AI 분석 함수# ============================================================def analyze_announcement(detail_url, project_name, print_file=None, api_description="", progress=gr.Progress()):"""공고 본문출력파일을 다운로드하고 AI로 분석Args:detail_url: 공고 상세 링크project_name: 공고명print_file: 본문출력파일 정보 (dict: url, filename, type) - ⭐ 핵심 분석 대상api_description: 사업개요"""if not detail_url:yield "❌ 분석할 공고를 선택해주세요."returnoutput = f"# 📄 {project_name}\n\n---\n\n"all_text = f"## 공고명: {project_name}\n\n"if api_description:1 unmodified lineoutput += f"📋 **사업개요**\n{api_description}\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 outputelif file_path:progress(0.5, desc="텍스트 추출 중...")output += f" - ✅ 다운로드 완료\n"yield output# 텍스트 추출text, err = extract_text_from_file(file_path)if text:extracted_text = textoutput += f" - ✅ 텍스트 추출 성공 ({len(text):,} 글자)\n\n"all_text += f"### 본문출력파일 내용:\n\n{text[:8000]}\n\n"else:output += f" - ⚠️ 텍스트 추출 실패: {err}\n"yield outputelse:output += "⚠️ **본문출력파일이 없습니다.**\n"output += "사업개요만으로 분석을 진행합니다.\n\n"yield outputif len(all_text) < 100 and not extracted_text:output += "\n❌ **분석할 내용이 충분하지 않습니다.**\n"output += "본문출력파일이 없거나 텍스트 추출에 실패했습니다.\n"yield outputreturn248 unmodified lines# 상태 변수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={})235 unmodified linesurl = row.get("상세링크", "")name = row.get("지원사업명", "")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, 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,83 unmodified linesexport_btn.click(fn=export_to_csv, inputs=[current_df], outputs=[csv_output])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])
app.py+87-55