Spaces:
Sleeping
Sleeping
Update backend/main.py
Browse files11 unmodified lines1213141516171819202 unmodified lines23242526272829303132333435363738394041424344454647484950515253547 unmodified lines6263646566676869707172732 unmodified lines767778798081823 unmodified lines868788899091929394953 unmodified lines9910010110210310410510610710810911011111215 unmodified lines12812913013113211 unmodified linesimport refrom typing import List, Optionalapp = FastAPI()# 允許所有來源的跨域請求,方便前後端分離的開發和部署app.add_middleware(CORSMiddleware,allow_origins=["*"],2 unmodified linesallow_headers=["*"],)@app.post("/api/search")async def search_documents(word_files: List[UploadFile] = File(...),keyword_file: UploadFile = File(...),fund_file: Optional[UploadFile] = File(None),agency_file: Optional[UploadFile] = File(None),search_mode: str = Form("簡單版"),):def read_list_from_uploadfile(file: Optional[UploadFile]):if not file: return []try:content = file.file.read().decode('utf-8')return [line.strip() for line in content.splitlines() if line.strip()]except Exception:return []keywords = read_list_from_uploadfile(keyword_file)funds = read_list_from_uploadfile(fund_file)agencies = read_list_from_uploadfile(agency_file) if search_mode == "含機關版" else []if not keywords:raise HTTPException(status_code=400, detail="關鍵字清單不可為空。")results = []for word_file in word_files:content_full = ""tmp_path = ""try:7 unmodified linesfinally:if os.path.exists(tmp_path):os.remove(tmp_path)# 核心搜尋邏輯found_keywords_set = set()context_sentences = []# 分割句子sentences = re.split(r'([.?!。?!…\n])', content_full)sentences = ["".join(i) for i in zip(sentences[0::2], sentences[1::2])]2 unmodified linescontinuesentence_lower = sentence.lower()keywords_in_sentence = [k for k in keywords if k.lower() in sentence_lower]if keywords_in_sentence:found_keywords_set.update(keywords_in_sentence)3 unmodified linescontext_sentences.append(highlighted_sentence.strip())content_lower = content_full.lower()found_funds = [f for f in funds if f.lower() in content_lower]found_agencies = []if search_mode == "含機關版":found_agencies = [a for a in agencies if a.lower() in content_lower]result_item = {"檔案名稱": word_file.filename,3 unmodified lines"既有基金": "、".join(found_funds) if found_funds else "無",}if search_mode == "含機關版":result_item["涉及機關"] = "、".join(found_agencies) if found_agencies else "無"results.append(result_item)if not results:return JSONResponse(content={"message": "處理完成,但未找到任何匹配項。", "results": []})# 使用 Pandas DataFrame 進行排序cols_order_simple = ["檔案名稱", "出現關鍵字內容", "關鍵字上下文", "關鍵字統計", "既有基金"]cols_order_agency = ["檔案名稱", "涉及機關", "出現關鍵字內容", "關鍵字上下文", "關鍵字統計", "既有基金"]15 unmodified lines"results": json_results})# 掛載靜態文件目錄,讓 FastAPI 同時作為 Web Server 提供前端頁面app.mount("/", StaticFiles(directory="frontend", html=True), name="static")11 unmodified lines121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556572 unmodified lines60616263646566676869707172737475767778798081828384858687888990919293949596977 unmodified lines1051061071081091101111121131141152 unmodified lines1181191201211221231241253 unmodified lines1291301311321331341351361371381393 unmodified lines14314414514614714814915015115215315415515615 unmodified lines17217317417517617711 unmodified linesimport refrom typing import List, Optional# --- 內建清單 ---DEFAULT_KEYWORDS = ["國庫", "撥補", "設立", "設置", "基金", "附屬單位預算", "國營事業","收支保管", "基金來源", "基金用途", "循預算程序之撥款", "財團法人","行政法人", "非營業特種基金", "公庫", "預算法"]DEFAULT_FUNDS = ["行政院國家發展基金", "營建建設基金", "實施平均地權基金", "國軍生產及服務作業基金","國軍老舊眷村改建基金", "國防醫學院軍事教育基金", "法務部矯正機關作業基金","經濟作業基金", "水資源作業基金", "交通作業基金", "國軍退除役官兵安置基金","榮民醫療作業基金", "科學園區管理局作業基金", "農業作業基金", "農田水利事業作業基金","勞工保險局作業基金", "醫療藥品基金", "管制藥品製藥工廠作業基金", "全民健康保險基金","國民年金保險基金", "國立文化機構作業基金", "故宮文物藝術發展基金","原住民族綜合發展基金", "國立大學校院校務基金", "考選業務基金","國立臺灣大學附設醫院作業基金", "國立成功大學附設醫院作業基金","國立陽明交通大學附設醫院作業基金", "教育部所屬機構作業基金", "國立高級中等學校校務基金","中央政府債務基金", "國軍營舍及設施改建基金", "中央研究院科學研究基金","行政院國家科學技術發展基金", "離島建設基金", "花東地區永續發展基金", "促進轉型正義基金","新住民發展基金", "研發及產業訓儲替代役基金", "警察消防海巡移民空勤人員及協勤民力安全基金","國土永續發展基金", "學產基金", "運動發展基金", "私立高級中等以上學校退場基金","毒品防制基金", "經濟特別收入基金", "核能發電後端營運基金", "航港建設基金","核子事故緊急應變基金", "農業特別收入基金", "就業安定基金", "衛生福利特別收入基金","環境保護基金", "文化發展基金", "金融監督管理基金", "海洋污染防治基金","通訊傳播監督管理基金", "有線廣播電視事業發展基金", "反托拉斯基金"]DEFAULT_AGENCIES = ["行政院", "行政院人事行政總處", "行政院主計總處", "行政院公共工程委員會", "內政部","外交部", "領事事務局", "國防部", "財政部", "教育部", "法務部", "經濟部", "交通部","衛生福利部", "文化部", "勞動部", "數位發展部", "農業部", "環境部","國家科學及技術委員會", "僑務委員會", "客家委員會", "金融監督管理委員會","國家發展委員會", "國軍退除役官兵輔導委員會", "原住民族委員會", "海洋委員會","中央選舉委員會", "核能安全委員會", "公平交易委員會", "國家通訊傳播委員會","中央銀行", "國立故宮博物院", "不當黨產處理委員會", "國家運輸安全調查委員會"]app = FastAPI()app.add_middleware(CORSMiddleware,allow_origins=["*"],2 unmodified linesallow_headers=["*"],)def parse_text_to_list(text: str) -> List[str]:"""從多行文字字串解析出列表,並過濾空行"""if not text:return []return [line.strip() for line in text.splitlines() if line.strip()]@app.post("/api/search")async def search_documents(word_files: List[UploadFile] = File(...),# 修改 API 輸入,從檔案改為文字字串keywords_text: str = Form(""),funds_text: str = Form(""),agencies_text: str = Form(""),search_mode: str = Form("簡單版"),):# 合併內建清單和使用者輸入的清單user_keywords = parse_text_to_list(keywords_text)user_funds = parse_text_to_list(funds_text)user_agencies = parse_text_to_list(agencies_text)# 使用集合來確保唯一性final_keywords = sorted(list(set(DEFAULT_KEYWORDS + user_keywords)))final_funds = sorted(list(set(DEFAULT_FUNDS + user_funds)))final_agencies = sorted(list(set(DEFAULT_AGENCIES + user_agencies)))if not final_keywords:raise HTTPException(status_code=400, detail="關鍵字清單不可為空。")results = []for word_file in word_files:# (這一段讀取和處理 word_file 的邏輯保持不變,直接複製即可)content_full = ""tmp_path = ""try:7 unmodified linesfinally:if os.path.exists(tmp_path):os.remove(tmp_path)# --- 核心搜尋邏輯,使用 final_* 變數 ---found_keywords_set = set()context_sentences = []sentences = re.split(r'([.?!。?!…\n])', content_full)sentences = ["".join(i) for i in zip(sentences[0::2], sentences[1::2])]2 unmodified linescontinuesentence_lower = sentence.lower()# 使用 final_keywords 進行搜尋keywords_in_sentence = [k for k in final_keywords if k.lower() in sentence_lower]if keywords_in_sentence:found_keywords_set.update(keywords_in_sentence)3 unmodified linescontext_sentences.append(highlighted_sentence.strip())content_lower = content_full.lower()# 使用 final_funds 和 final_agencies 進行搜尋found_funds = [f for f in final_funds if f.lower() in content_lower]found_agencies_list = []if search_mode == "含機關版":found_agencies_list = [a for a in final_agencies if a.lower() in content_lower]result_item = {"檔案名稱": word_file.filename,3 unmodified lines"既有基金": "、".join(found_funds) if found_funds else "無",}if search_mode == "含機關版":result_item["涉及機關"] = "、".join(found_agencies_list) if found_agencies_list else "無"results.append(result_item)# (後續的排序和返回 JSON 的邏輯保持不變)if not results:return JSONResponse(content={"message": "處理完成,但未找到任何匹配項。", "results": []})cols_order_simple = ["檔案名稱", "出現關鍵字內容", "關鍵字上下文", "關鍵字統計", "既有基金"]cols_order_agency = ["檔案名稱", "涉及機關", "出現關鍵字內容", "關鍵字上下文", "關鍵字統計", "既有基金"]15 unmodified lines"results": json_results})# 掛載靜態文件app.mount("/", StaticFiles(directory="frontend", html=True), name="static")
backend/main.py+72-27