Lucas ARRIESSE commited on
Commit ·
8ac47d4
1
Parent(s): adf98e8
Allow listing other document types than xxxxCRs
Browse filesFiles changed (5)
- api/docs.py+28-79
- dependencies.py+5-2
- schemas.py+12-5
- static/index.html+8-12
- static/js/app.js+17-15
7 unmodified lines89101112139 unmodified lines23242526272829143 unmodified lines1731741751761771781791801811821831841851861871881891901911921931943 unmodified lines1981992002012022032046 unmodified lines2112122132142152162172182192202212222232243 unmodified lines2282292302312322332345 unmodified lines2402412422432442452464 unmodified lines25125225325425525625725825926026117 unmodified lines27928028128228328428544 unmodified lines3303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943956 unmodified lines40240340440540640740840941041141241341441521 unmodified lines43743843944044144244344444518 unmodified lines4644654664674684694707 unmodified linesimport zipfileimport jsonimport osfrom pydantic import BaseModelimport requestsimport subprocess9 unmodified linesfrom fastapi.responses import StreamingResponsefrom litellm.router import Routerfrom schemas import DataRequest, DataResponse, DocRequirements, DownloadRequest, MeetingsRequest, MeetingsResponse, RequirementsRequest, RequirementsResponse# API router for requirement extraction from docs / doc list retrieval / downloadrouter = APIRouter(tags=["document extraction"])143 unmodified lines# ============================================= Doc routes =========================================================@router.post("/get_meetings", response_model=MeetingsResponse)def get_meetings(req: MeetingsRequest):working_group = req.working_grouptsg = re.sub(r"\d+", "", working_group)wg_number = re.search(r"\d", working_group).group(0)logging.debug(tsg, wg_number)url = "https://www.3gpp.org/ftp/tsg_" + tsglogging.debug(url)resp = requests.get(url, verify=False)soup = BeautifulSoup(resp.text, "html.parser")meeting_folders = []all_meetings = []wg_folders = [item.get_text() for item in soup.select("tr td a")]selected_folder = Nonefor folder in wg_folders:if "wg" + str(wg_number) in folder.lower():selected_folder = folder3 unmodified lineslogging.debug(url)if selected_folder:resp = requests.get(url, verify=False)soup = BeautifulSoup(resp.text, "html.parser")meeting_folders = [item.get_text() for item in soup.select("tr td a") if item.get_text().startswith("TSG") or (item.get_text().startswith("CT") and "-" in item.get_text())]6 unmodified lines@router.post("/get_dataframe", response_model=DataResponse)def get_change_request_dataframe(req: DataRequest):working_group = req.working_grouptsg = re.sub(r"\d+", "", working_group)wg_number = re.search(r"\d", working_group).group(0)url = "https://www.3gpp.org/ftp/tsg_" + tsglogging.info("Fetching TDocs dataframe")resp = requests.get(url, verify=False)soup = BeautifulSoup(resp.text, "html.parser")wg_folders = [item.get_text() for item in soup.select("tr td a")]selected_folder = None3 unmodified linesbreakurl += "/" + selected_folder + "/" + req.meeting + "/docs"resp = requests.get(url, verify=False)soup = BeautifulSoup(resp.text, "html.parser")files = [item.get_text() for item in soup.select("tr td a")if item.get_text().endswith(".xlsx")]5 unmodified linesreturn f"{url}/{tdoc}.zip"df = pd.read_excel(str(url + "/" + files[0]).replace("#", "%23"))filtered_df = df[(((df["Type"] == "CR") & ((df["CR category"] == "B") | (df["CR category"] == "C"))) | (df["Type"] == "pCR")) & ~(df["Uploaded"].isna())][["TDoc", "Title", "CR category", "Source", "Type", "Agenda item", "Agenda item description", "TDoc Status"]]filtered_df["URL"] = filtered_df["TDoc"].apply(gen_url)4 unmodified lines@router.post("/download_tdocs")def download_tdocs(req: DownloadRequest):"""Download the specified TDocs and zips them in a single archive"""# Document IDs to downloaddocument_ids = req.documentslogging.info(f"Downloading TDocs: {document_ids}")17 unmodified linesraise HTTPException(status_code=501, detail="Got no URL results for docs {documents}. 3GPP index may not be up to date")documents_content: Dict[str, bytes] = {}failed_documents: List[str] = []44 unmodified linesheaders={"Content-Disposition": "attachment; filename=tdocs.zip"})@router.post("/generate_requirements", response_model=RequirementsResponse)async def gen_reqs(req: RequirementsRequest, background_tasks: BackgroundTasks, llm_router: Router = Depends(get_llm_router)):"""Extract requirements from the specified TDocs using a LLM"""documents = req.documentsn_docs = len(documents)logging.info("Generating requirements for documents: {}".format([doc.document for doc in documents]))def prompt(doc_id, full):return f"Here's the document whose ID is {doc_id} : {full}\n\nExtract all requirements and group them by context, returning a list of objects where each object includes a document ID, a concise description of the context where the requirements apply (not a chapter title or copied text), and a list of associated requirements; always return the result as a list, even if only one context is found. Remove the errors"async def process_document(doc):doc_id = doc.documenturl = doc.urltry:full = "\n".join(docx_to_txt(doc_id, url))except Exception as e:logging.error(f"Failed to process doc {doc_id}", e)return RequirementsResponse(requirements=[DocRequirements(document=doc_id, context="Error LLM", requirements=[])]).requirementstry:resp_ai = await llm_router.acompletion(model="gemini-v2",messages=[{"role": "user", "content": prompt(doc_id, full)}],response_format=RequirementsResponse)return RequirementsResponse.model_validate_json(resp_ai.choices[0].message.content).requirementsexcept Exception as e:logging.error(f"Failed to process document {doc_id}", e, stack_info=True)return RequirementsResponse(requirements=[DocRequirements(document=doc_id, context="Error LLM", requirements=[])]).requirementsasync def process_batch(batch):results = await asyncio.gather(*(process_document(doc) for doc in batch))return [item for sublist in results for item in sublist]all_requirements = []if n_docs <= 30:batch_results = await process_batch(documents)all_requirements.extend(batch_results)else:batch_size = 30batches = [documents[i:i + batch_size]for i in range(0, n_docs, batch_size)]for i, batch in enumerate(batches):batch_results = await process_batch(batch)all_requirements.extend(batch_results)if i < len(batches) - 1:background_tasks.add_task(asyncio.sleep, 60)return RequirementsResponse(requirements=all_requirements)# ======================================================================================================================================================================================6 unmodified lines@router.post("/generate_requirements/sse")async def gen_reqs(req: RequirementsRequest, con: Request, llm_router: Router = Depends(get_llm_router)):"""Extract requirements from the specified TDocs using a LLM and returns SSE events about the progress of ongoing operations"""documents = req.documentsn_docs = len(documents)logging.info("Generating requirements for documents: {}".format([doc.document for doc in documents]))# limit max concurrency of LLM requests to prevent a huge pile of errors because of small rate limitsconcurrency_sema = asyncio.Semaphore(4)21 unmodified linesmodel=model_used,messages=[{"role": "user", "content": prompt(doc_id, full)}],response_format=RequirementsResponse)return RequirementsResponse.model_validate_json(resp_ai.choices[0].message.content).requirementsexcept Exception as e:return [DocRequirements(document=doc_id, context="Error LLM", requirements=[])]finally:18 unmodified linesn_processed += 1yield progress_update(ProgressUpdate(status="progress", data={}, total_docs=n_docs, processed_docs=n_processed))final_response = RequirementsResponse(requirements=items)yield progress_update(ProgressUpdate(status="complete", data=final_response.model_dump(), total_docs=n_docs, processed_docs=n_processed))7 unmodified lines8910111213149 unmodified lines24252627282930143 unmodified lines1741751761771781791801811821831841851861871881891901911921931941951961971981993 unmodified lines2032042052062072082096 unmodified lines2162172182192202212222232242252262272282292302312322332343 unmodified lines2382392402412422432445 unmodified lines2502512522532542552564 unmodified lines26126226326426526626726826927027117 unmodified lines28929029129229329429544 unmodified lines3403413423433443456 unmodified lines35235335435535635735835936036136236336421 unmodified lines38638738838939039139239339418 unmodified lines4134144154164174184197 unmodified linesimport zipfileimport jsonimport osfrom httpx import AsyncClientfrom pydantic import BaseModelimport requestsimport subprocess9 unmodified linesfrom fastapi.responses import StreamingResponsefrom litellm.router import Routerfrom schemas import DataRequest, DataResponse, DocRequirements, DocDownloadRequest, MeetingsRequest, MeetingsResponse, ExtractRequirementsRequest, ExtractRequirementsResponse# API router for requirement extraction from docs / doc list retrieval / downloadrouter = APIRouter(tags=["document extraction"])143 unmodified lines# ============================================= Doc routes =========================================================@router.post("/get_meetings", response_model=MeetingsResponse)async def get_meetings(req: MeetingsRequest, http_client: AsyncClient = Depends(get_http_client)):# Extracting WGworking_group = req.working_grouptsg = re.sub(r"\d+", "", working_group)wg_number = re.search(r"\d", working_group).group(0)# building corresponding FTP urllogging.debug(tsg, wg_number)url = "https://www.3gpp.org/ftp/tsg_" + tsglogging.debug(url)ftp_request = await http_client.get(url)soup = BeautifulSoup(ftp_request.text, "html.parser")meeting_folders = []all_meetings = []wg_folders = [item.get_text() for item in soup.select("tr td a")]selected_folder = None# sanity check to ensure the requested workgroup is present in the ftp directoriesfor folder in wg_folders:if "wg" + str(wg_number) in folder.lower():selected_folder = folder3 unmodified lineslogging.debug(url)if selected_folder:resp = await http_client.get(url)soup = BeautifulSoup(resp.text, "html.parser")meeting_folders = [item.get_text() for item in soup.select("tr td a") if item.get_text().startswith("TSG") or (item.get_text().startswith("CT") and "-" in item.get_text())]6 unmodified lines@router.post("/get_dataframe", response_model=DataResponse)async def get_docs_df(req: DataRequest, http_client: AsyncClient = Depends(get_http_client)):"""Downloads the document list dataframe for a given meeting"""# Extracting WGworking_group = req.working_grouptsg = re.sub(r"\d+", "", working_group)wg_number = re.search(r"\d", working_group).group(0)url = "https://www.3gpp.org/ftp/tsg_" + tsglogging.info("Fetching TDocs dataframe")resp = await http_client.get(url)soup = BeautifulSoup(resp.text, "html.parser")wg_folders = [item.get_text() for item in soup.select("tr td a")]selected_folder = None3 unmodified linesbreakurl += "/" + selected_folder + "/" + req.meeting + "/docs"resp = await http_client.get(url)soup = BeautifulSoup(resp.text, "html.parser")files = [item.get_text() for item in soup.select("tr td a")if item.get_text().endswith(".xlsx")]5 unmodified linesreturn f"{url}/{tdoc}.zip"df = pd.read_excel(str(url + "/" + files[0]).replace("#", "%23"))filtered_df = df[~(df["Uploaded"].isna())][["TDoc", "Title", "CR category", "Source", "Type", "Agenda item", "Agenda item description", "TDoc Status"]]filtered_df["URL"] = filtered_df["TDoc"].apply(gen_url)4 unmodified lines@router.post("/download_tdocs")def download_tdocs(req: DocDownloadRequest):"""Download the specified TDocs and zips them in a single archive"""# Document IDs to downloaddocument_ids = [doc.document for doc in req.documents]logging.info(f"Downloading TDocs: {document_ids}")17 unmodified linesraise HTTPException(status_code=501, detail="Got no URL results for docs {documents}. 3GPP index may not be up to date")documents_content: Dict[str, bytes] = {}failed_documents: List[str] = []44 unmodified linesheaders={"Content-Disposition": "attachment; filename=tdocs.zip"})# ======================================================================================================================================================================================6 unmodified lines@router.post("/generate_requirements/sse")async def gen_reqs(req: ExtractRequirementsRequest, llm_router: Router = Depends(get_llm_router)):"""Extract requirements from the specified xxxxCR docs using a LLM and returns SSE events about the progress of ongoing operations"""documents = req.documentsn_docs = len(documents)logging.info("Generating requirements for documents: {}".format(req.documents))# limit max concurrency of LLM requests to prevent a huge pile of errors because of small rate limitsconcurrency_sema = asyncio.Semaphore(4)21 unmodified linesmodel=model_used,messages=[{"role": "user", "content": prompt(doc_id, full)}],response_format=ExtractRequirementsResponse)return ExtractRequirementsResponse.model_validate_json(resp_ai.choices[0].message.content).requirementsexcept Exception as e:return [DocRequirements(document=doc_id, context="Error LLM", requirements=[])]finally:18 unmodified linesn_processed += 1yield progress_update(ProgressUpdate(status="progress", data={}, total_docs=n_docs, processed_docs=n_processed))final_response = ExtractRequirementsResponse(requirements=items)yield progress_update(ProgressUpdate(status="complete", data=final_response.model_dump(), total_docs=n_docs, processed_docs=n_processed))
1237 unmodified lines11121314151630 unmodified lines4748495051525354import osfrom httpx import AsyncClientfrom litellm.router import Router7 unmodified linesINSIGHT_FINDER_BASE_URL = "https://organizedprogrammers-insight-finder.hf.space/"DOC_FINDER_BASE_URL = "https://organizedprogrammers-docfinder.hf.space/"def init_dependencies():"""Initialize the application global dependencies"""30 unmodified linesprompt_templates = Environment(loader=FileSystemLoader("prompts"), enable_async=True, undefined=StrictUndefined)http_client = AsyncClient(verify=os.environ.get("NO_SSL", "0") == "1", timeout=None)def get_llm_router() -> Router:12347 unmodified lines1213141516171830 unmodified lines495051525354555657import loggingimport osfrom httpx import AsyncClientfrom litellm.router import Router7 unmodified linesINSIGHT_FINDER_BASE_URL = "https://organizedprogrammers-insight-finder.hf.space/"DOC_FINDER_BASE_URL = "https://organizedprogrammers-docfinder.hf.space/"def init_dependencies():"""Initialize the application global dependencies"""30 unmodified linesprompt_templates = Environment(loader=FileSystemLoader("prompts"), enable_async=True, undefined=StrictUndefined)enable_ssl = not os.environ.get("NO_SSL", "0") == "1"logging.debug(f"SSL cert check is {enable_ssl}")http_client = AsyncClient(verify=enable_ssl, timeout=None)def get_llm_router() -> Router:
22 unmodified lines23242526272829303132333 unmodified lines3738394041424322 unmodified lines66676869707172737422 unmodified linesclass DocInfo(BaseModel):document: strurl: strclass RequirementsRequest(BaseModel):documents: List[DocInfo]3 unmodified linesrequirements: List[str]class RequirementsResponse(BaseModel):requirements: List[DocRequirements]# --------------------------------------22 unmodified lines# --------------------------------------class DownloadRequest(BaseModel):documents: List[str] = Field(description="List of document IDs to download")class ReqGroupingCategory(BaseModel):22 unmodified lines2324252627282930313233343536373839403 unmodified lines4445464748495022 unmodified lines73747576777879808122 unmodified linesclass DocInfo(BaseModel):"""Schema for describing a document to download."""# Document namedocument: str# Document URLurl: str# Document typetype: strclass ExtractRequirementsRequest(BaseModel):documents: List[DocInfo]3 unmodified linesrequirements: List[str]class ExtractRequirementsResponse(BaseModel):requirements: List[DocRequirements]# --------------------------------------22 unmodified lines# --------------------------------------class DocDownloadRequest(BaseModel):documents: List[DocInfo] = Field(description="List of documents to download")class ReqGroupingCategory(BaseModel):
155 unmodified lines156157158159160161162163164165166167168169170171172173174175176155 unmodified lines<!-- Data Table Informations --><div class="flex justify-between items-center mb-2 pt-5" id="data-table-info-container"><div class="flex gap-2 items-center"><div class="tooltip" data-tip="Extract requirements from selected documents"><button id="extract-requirements-btn"class="bg-orange-300 text-white text-sm rounded px-3 py-1 shadow hover:bg-orange-600"><svg class="w-6 h-6 text-gray-800 dark:text-white" aria-hidden="true"xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none"viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"stroke-width="2"d="M9 8h6m-6 4h6m-6 4h6M6 3v18l2-2 2 2 2-2 2 2 2-2 2 2V3l-2 2-2-2-2 2-2-2-2 2-2-2Z" /></svg>Extract Requirements</button></div><button id="download-tdocs-btn" class="text-sm rounded px-3 py-1 shadow cursor-pointer">📦 Download Selected TDocs</button></div><!-- document counts -->155 unmodified lines156157158159160161162163164165166167168169170171172155 unmodified lines<!-- Data Table Informations --><div class="flex justify-between items-center mb-2 pt-5" id="data-table-info-container"><div class="flex gap-2 items-center"><div class="tooltip" data-tip="Extract requirements from selected pCR / CR documents"><button id="extract-requirements-btn"class="bg-orange-300 text-white text-sm rounded px-3 py-1 shadow hover:bg-orange-600">💉Extract Requirements</button></div><div class="tooltip" data-tip="Download all selected TDocs as text files"><button id="download-tdocs-btn" class="text-sm rounded px-3 py-1 shadow cursor-pointer">📦 Download Selected TDocs</button></div></div><!-- document counts -->
160 unmodified lines16116216316416516616716816917017117217317458 unmodified lines23323423523623723823924024124224324424524624724824925025125225325469 unmodified lines324325326327328329330331332333334335336337338339340160 unmodified linesdocument.getElementById('status-filter-label').textContent = 'Status (Tous)';document.getElementById('agenda-filter-label').textContent = 'Agenda Item (Tous)';}/*** Configure les événements des filtres*/function setupFilterEvents() {['doc-type-filter', 'doc-status-filter', 'agenda-item-filter'].forEach(filterId => {document.getElementById(filterId).addEventListener('change', applyFilters);});}function updateSelectedAndDisplayedCount() {// Lignes visibles (après filtrage)58 unmodified lines}/*** Télécharge les TDocs sélectionnés*/async function downloadTDocs() {showLoadingOverlay('Downloading TDocs...');toggleElementsEnabled(['download-tdocs-btn', 'extract-requirements-btn'], false);try {// Extraire les données du tableau avec TDoc et URLconst selectedData = extractTableData({ 'TDoc': 'document', 'URL': 'url' });if (selectedData.length === 0) {alert('Please select at least one document');return;}// Transformer au format requis: [{tdoc_id: url}, ...]const documents = selectedData.map(obj => obj.document)const response = await fetch('/docs/download_tdocs', {method: 'POST',69 unmodified lines* Extrait les requirements des documents sélectionnés*/async function extractRequirements() {const selectedData = extractTableData({ 'TDoc': 'document', 'URL': 'url' });if (selectedData.length === 0) {alert('Please select at least one document');return;}showLoadingOverlay('Extracting requirements...');toggleElementsEnabled(['extract-requirements-btn'], false);try {const response = await postWithSSE('/docs/generate_requirements/sse', { documents: selectedData }, {onMessage: (msg) => {console.log("SSE message:");console.log(msg);160 unmodified lines16116216316416516658 unmodified lines22522622722822923023123223323423523623723823924024124224324424524624724824969 unmodified lines319320321322323324325326327328329330331332333334335336337338339340341342160 unmodified linesdocument.getElementById('status-filter-label').textContent = 'Status (Tous)';document.getElementById('agenda-filter-label').textContent = 'Agenda Item (Tous)';}function updateSelectedAndDisplayedCount() {// Lignes visibles (après filtrage)58 unmodified lines}/*** Télécharge les pCR / CR / draftCR dans TDocs sélectionnés.* Le JS filtre les tdocs sélectionnés pour recup uniquement les xxxxxCR*/async function downloadTDocs() {showLoadingOverlay('Downloading TDocs...');toggleElementsEnabled(['download-tdocs-btn', 'extract-requirements-btn'], false);try {// Extraire les données du tableau avec le format suivant pour la requete backend// { document: "nom_doc", url: "url_doc", type: "type_de_doc"}const selectedData = extractTableData({ 'TDoc': 'document', 'URL': 'url', 'Type': "type" });if (selectedData.length === 0) {alert('Please select at least one document');return;}// on prend toutconst documents = selectedData;const response = await fetch('/docs/download_tdocs', {method: 'POST',69 unmodified lines* Extrait les requirements des documents sélectionnés*/async function extractRequirements() {const selectedData = extractTableData({ 'TDoc': 'document', 'URL': 'url', 'Type': 'type' });console.log("Selected docs data");console.log(selectedData);if (selectedData.length === 0) {alert('Please select at least one document');return;}// ne prendre que les documents avec un type qui contient xxxxCR en minusculesconst documents = selectedData.filter(d => d.type.toLowerCase().includes("cr"));showLoadingOverlay('Extracting requirements...');toggleElementsEnabled(['extract-requirements-btn'], false);try {const response = await postWithSSE('/docs/generate_requirements/sse', { documents: documents }, {onMessage: (msg) => {console.log("SSE message:");console.log(msg);
api/docs.py+28-79
dependencies.py+5-2
schemas.py+12-5
static/index.html+8-12
static/js/app.js+17-15