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 lines8910111213149 unmodified lines2425262627282930143 unmodified lines1741751761761771781791801811821831841851861871851861881891901911921931941951961971981993 unmodified lines2032042052012062072082096 unmodified lines2162172182142192202212222232242252262272282292302212312322332343 unmodified lines2382392402312412422432445 unmodified lines2502512522432532542552564 unmodified lines26126226325426426526626725826826927027117 unmodified lines28929029128229229329429544 unmodified lines3403413423333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923433443456 unmodified lines35235335440540635535635735835936041141236136236336421 unmodified lines38638738844038939044239139239339418 unmodified lines4134144154674164174184197 unmodified linesimport zipfileimport jsonimport osfrom httpx import AsyncClientfrom pydantic import BaseModelimport requestsimport subprocess9 unmodified linesfrom fastapi.responses import StreamingResponsefrom litellm.router import Router
from schemas import DataRequest, DataResponse, DocRequirements, DownloadRequest, MeetingsRequest, MeetingsResponse, RequirementsRequest, RequirementsResponsefrom 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)def get_meetings(req: MeetingsRequest):async def get_meetings(req: MeetingsRequest, http_client: AsyncClient = Depends(get_http_client)): # Extracting WG working_group = req.working_group tsg = re.sub(r"\d+", "", working_group) wg_number = re.search(r"\d", working_group).group(0)
# building corresponding FTP url logging.debug(tsg, wg_number) url = "https://www.3gpp.org/ftp/tsg_" + tsg logging.debug(url)
resp = requests.get(url, verify=False) soup = BeautifulSoup(resp.text, "html.parser") 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 directories for folder in wg_folders: if "wg" + str(wg_number) in folder.lower(): selected_folder = folder3 unmodified lines logging.debug(url)
if selected_folder: resp = requests.get(url, verify=False) 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)def get_change_request_dataframe(req: DataRequest):async def get_docs_df(req: DataRequest, http_client: AsyncClient = Depends(get_http_client)): """ Downloads the document list dataframe for a given meeting """
# Extracting WG working_group = req.working_group tsg = re.sub(r"\d+", "", working_group) wg_number = re.search(r"\d", working_group).group(0) url = "https://www.3gpp.org/ftp/tsg_" + tsg logging.info("Fetching TDocs dataframe")
resp = requests.get(url, verify=False) 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 lines break
url += "/" + selected_folder + "/" + req.meeting + "/docs" resp = requests.get(url, verify=False) 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 lines return 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")) & ~( 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: DownloadRequest):def download_tdocs(req: DocDownloadRequest): """Download the specified TDocs and zips them in a single archive"""
# Document IDs to download document_ids = req.documents document_ids = [doc.document for doc in req.documents]
logging.info(f"Downloading TDocs: {document_ids}")
17 unmodified lines
raise 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 lines headers={"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.documents n_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.document url = doc.url try: 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=[])]).requirements
try: 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).requirements
except 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=[])]).requirements
async 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 = 30 batches = [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"""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.documents n_docs = len(documents)
logging.info("Generating requirements for documents: {}".format( [doc.document for doc in 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 limits concurrency_sema = asyncio.Semaphore(4)21 unmodified lines model=model_used, messages=[ {"role": "user", "content": prompt(doc_id, full)}], response_format=RequirementsResponse response_format=ExtractRequirementsResponse ) return RequirementsResponse.model_validate_json(resp_ai.choices[0].message.content).requirements return ExtractRequirementsResponse.model_validate_json(resp_ai.choices[0].message.content).requirements except Exception as e: return [DocRequirements(document=doc_id, context="Error LLM", requirements=[])] finally:18 unmodified lines n_processed += 1 yield progress_update(ProgressUpdate(status="progress", data={}, total_docs=n_docs, processed_docs=n_processed))
final_response = RequirementsResponse(requirements=items) final_response = ExtractRequirementsResponse(requirements=items)
yield progress_update(ProgressUpdate(status="complete", data=final_response.model_dump(), total_docs=n_docs, processed_docs=n_processed))
12347 unmodified lines1213141516171830 unmodified lines4950515051525354555657import 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 lines prompt_templates = Environment(loader=FileSystemLoader( "prompts"), enable_async=True, undefined=StrictUndefined)
http_client = AsyncClient(verify=os.environ.get( "NO_SSL", "0") == "1", timeout=None) 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 lines232425262728293031323334353630373839403 unmodified lines444546404748495022 unmodified lines73747569707176777879808122 unmodified lines
class DocInfo(BaseModel): """ Schema for describing a document to download. """ # Document name document: str # Document URL url: str # Document type type: str
class RequirementsRequest(BaseModel):class ExtractRequirementsRequest(BaseModel): documents: List[DocInfo]
3 unmodified lines requirements: List[str]
class RequirementsResponse(BaseModel):class ExtractRequirementsResponse(BaseModel): requirements: List[DocRequirements]
# --------------------------------------22 unmodified lines# --------------------------------------
class DownloadRequest(BaseModel): documents: List[str] = Field( description="List of document IDs to download")class DocDownloadRequest(BaseModel): documents: List[DocInfo] = Field( description="List of documents to download")
class ReqGroupingCategory(BaseModel):155 unmodified lines156157158159159160161162163164165166167168161162163164165166167168169171172173170171172155 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"> <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"> <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 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> <button id="download-tdocs-btn" class="text-sm rounded px-3 py-1 shadow cursor-pointer"> 📦 Download Selected TDocs </button> </div>
<!-- document counts -->160 unmodified lines16116216316416516616716816917017116416516658 unmodified lines22522622723622822923023123223323423524324423623723823924024124224324425025124524624724824969 unmodified lines319320321327322323324325326327328329330331332333334335336337338337339340341342160 unmodified lines document.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 * 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 TDoc et URL const selectedData = extractTableData({ 'TDoc': 'document', 'URL': 'url' }); // 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; }
// Transformer au format requis: [{tdoc_id: url}, ...] const documents = selectedData.map(obj => obj.document) // on prend tout const 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' }); 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 minuscules const 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: selectedData }, { 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