Lucas ARRIESSE commited on
Commit ·
5ef0f8d
1
Parent(s): 035141c
Migrate API modules to api routers
Browse filesFiles changed (5)
- api/docs.py+438
- api/requirements.pyAdded+35
- app.py+12-482
- dependencies.pyAdded+42
- static/js/script.js+5-5
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442import asynciofrom typing import Literalfrom fastapi.routing import APIRouterimport loggingimport stringimport ioimport tracebackimport zipfileimport jsonimport osfrom pydantic import BaseModelimport requestsimport subprocessimport pandas as pdimport refrom lxml import etreefrom nltk.tokenize import word_tokenizefrom bs4 import BeautifulSoupfrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizerfrom fastapi import Depends, BackgroundTasks, HTTPException, Requestfrom dependencies import get_llm_routerfrom fastapi.responses import StreamingResponsefrom litellm.router import Router
from schemas import DataRequest, DataResponse, DocRequirements, DownloadRequest, MeetingsRequest, MeetingsResponse, RequirementsRequest, RequirementsResponse
# API router for requirement extraction from docs / doc list retrieval / downloadrouter = APIRouter()
# ==================================================== Utilities =================================================================
lemmatizer = WordNetLemmatizer()
NSMAP = { 'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main', 'v': 'urn:schemas-microsoft-com:vml'}
def lemma(text: str): stop_words = set(stopwords.words('english')) txt = text.translate(str.maketrans('', '', string.punctuation)).strip() tokens = [token for token in word_tokenize( txt.lower()) if token not in stop_words] return [lemmatizer.lemmatize(token) for token in tokens]
def get_docx_archive(url: str) -> zipfile.ZipFile: """Récupère le docx depuis l'URL et le retourne comme objet ZipFile""" if not url.endswith("zip"): raise ValueError("URL doit pointer vers un fichier ZIP") doc_id = os.path.splitext(os.path.basename(url))[0] resp = requests.get(url, verify=False, headers={ "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' }) resp.raise_for_status()
with zipfile.ZipFile(io.BytesIO(resp.content)) as zf: for file_name in zf.namelist(): if file_name.endswith(".docx"): docx_bytes = zf.read(file_name) return zipfile.ZipFile(io.BytesIO(docx_bytes)) elif file_name.endswith(".doc"): input_path = f"/tmp/{doc_id}.doc" output_path = f"/tmp/{doc_id}.docx" docx_bytes = zf.read(file_name)
with open(input_path, "wb") as f: f.write(docx_bytes)
subprocess.run([ "libreoffice", "--headless", "--convert-to", "docx", "--outdir", "/tmp", input_path ], check=True)
with open(output_path, "rb") as f: docx_bytes = f.read()
os.remove(input_path) os.remove(output_path)
return zipfile.ZipFile(io.BytesIO(docx_bytes))
raise ValueError("Aucun fichier docx/doc trouvé dans l'archive")
def parse_document_xml(docx_zip: zipfile.ZipFile) -> etree._ElementTree: """Parse le document.xml principal""" xml_bytes = docx_zip.read('word/document.xml') parser = etree.XMLParser(remove_blank_text=True) return etree.fromstring(xml_bytes, parser=parser)
def clean_document_xml(root: etree._Element) -> None: """Nettoie le XML en modifiant l'arbre directement""" # Suppression des balises <w:del> et leur contenu for del_elem in root.xpath('//w:del', namespaces=NSMAP): parent = del_elem.getparent() if parent is not None: parent.remove(del_elem)
# Désencapsulation des balises <w:ins> for ins_elem in root.xpath('//w:ins', namespaces=NSMAP): parent = ins_elem.getparent() index = parent.index(ins_elem) for child in ins_elem.iterchildren(): parent.insert(index, child) index += 1 parent.remove(ins_elem)
# Nettoyage des commentaires for tag in ['w:commentRangeStart', 'w:commentRangeEnd', 'w:commentReference']: for elem in root.xpath(f'//{tag}', namespaces=NSMAP): parent = elem.getparent() if parent is not None: parent.remove(elem)
def create_modified_docx(original_zip: zipfile.ZipFile, modified_root: etree._Element) -> bytes: """Crée un nouveau docx avec le XML modifié""" output = io.BytesIO()
with zipfile.ZipFile(output, 'w', compression=zipfile.ZIP_DEFLATED) as new_zip: # Copier tous les fichiers non modifiés for file in original_zip.infolist(): if file.filename != 'word/document.xml': new_zip.writestr(file, original_zip.read(file.filename))
# Ajouter le document.xml modifié xml_str = etree.tostring( modified_root, xml_declaration=True, encoding='UTF-8', pretty_print=True ) new_zip.writestr('word/document.xml', xml_str)
output.seek(0) return output.getvalue()
def docx_to_txt(doc_id: str, url: str): docx_zip = get_docx_archive(url) root = parse_document_xml(docx_zip) clean_document_xml(root) modified_bytes = create_modified_docx(docx_zip, root)
input_path = f"/tmp/{doc_id}_cleaned.docx" output_path = f"/tmp/{doc_id}_cleaned.txt" with open(input_path, "wb") as f: f.write(modified_bytes)
subprocess.run([ "libreoffice", "--headless", "--convert-to", "txt", "--outdir", "/tmp", input_path ], check=True)
with open(output_path, "r", encoding="utf-8") as f: txt_data = [line.strip() for line in f if line.strip()]
os.remove(input_path) os.remove(output_path) return txt_data
# ============================================= Doc routes =========================================================
@router.post("/get_meetings", response_model=MeetingsResponse)def get_meetings(req: MeetingsRequest): working_group = req.working_group tsg = 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_" + tsg logging.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 = None for folder in wg_folders: if "wg" + str(wg_number) in folder.lower(): selected_folder = folder break
url += "/" + selected_folder logging.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())] all_meetings = [working_group + "#" + meeting.split("_", 1)[1].replace("_", " ").replace( "-", " ") if meeting.startswith('TSG') else meeting.replace("-", "#") for meeting in meeting_folders]
return MeetingsResponse(meetings=dict(zip(all_meetings, meeting_folders)))
# ============================================================================================================================================
@router.post("/get_dataframe", response_model=DataResponse)def get_change_request_dataframe(req: DataRequest): 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) soup = BeautifulSoup(resp.text, "html.parser") wg_folders = [item.get_text() for item in soup.select("tr td a")] selected_folder = None for folder in wg_folders: if "wg" + str(wg_number) in folder.lower(): selected_folder = folder break
url += "/" + 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")]
if files == []: raise HTTPException(status_code=404, detail="No XLSX has been found")
def gen_url(tdoc: str): 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")) & ~( 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)
df = filtered_df.fillna("") return DataResponse(data=df[["TDoc", "Title", "Type", "TDoc Status", "Agenda item description", "URL"]].to_dict(orient="records"))
# ==================================================================================================================================
@router.post("/download_tdocs")def download_tdocs(req: DownloadRequest): """Download the specified TDocs and zips them in a single archive""" documents = req.documents
logging.info(f"Downloading TDocs: {documents}")
def process_document(doc: str): doc_id = doc url = requests.post( 'https://organizedprogrammers-3gppdocfinder.hf.space/find', headers={"Content-Type": "application/json"}, data=json.dumps({"doc_id": doc_id}), verify=False ) logging.info( f"Retrieving URL for doc {doc_id} returned http status {url.status_code}") url = url.json()['url'] logging.debug(f"Doc URL for {doc_id} is {url}")
try: txt = "\n".join(docx_to_txt(doc_id, url)) except Exception as e: txt = f"Document {doc_id} text extraction failed: {e}" return doc_id, txt.encode("utf-8")
# PERF: use asyncio? def process_batch(batch): results = {} for doc in batch: try: doc_id, file_bytes = process_document(doc) results[doc_id] = file_bytes except Exception as e: traceback.print_exception(e) results[doc] = b"Erreur" return results
documents_bytes = process_batch(documents)
zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, mode='w', compression=zipfile.ZIP_DEFLATED) as zip_file: for doc_id, txt_data in documents_bytes.items(): zip_file.writestr(f'{doc_id}.txt', txt_data)
zip_buffer.seek(0) return StreamingResponse( zip_buffer, media_type="application/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)
# ======================================================================================================================================================================================
class ProgressUpdate(BaseModel): """Defines the structure of a single SSE message.""" status: Literal["progress", "complete"] data: dict total_docs: int processed_docs: int
@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.documents n_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 limits concurrency_sema = asyncio.Semaphore(4)
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) -> list[DocRequirements]: doc_id = doc.document url = doc.url
# convert the docx to txt for use try: full = "\n".join(docx_to_txt(doc_id, url)) except Exception as e: logging.error( f"Failed to process document {doc_id}", e, stack_info=True) return [DocRequirements(document=doc_id, context="Error LLM", requirements=[])]
try: await concurrency_sema.acquire()
model_used = "gemini-v2" resp_ai = await llm_router.acompletion( model=model_used, 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: return [DocRequirements(document=doc_id, context="Error LLM", requirements=[])] finally: concurrency_sema.release()
# futures for all processed documents process_futures = [_process_document(doc) for doc in documents]
# lambda to print progress def progress_update(x): return f"data: {x.model_dump_json()}\n\n"
# async generator that generates the SSE events for progress async def _stream_generator(docs: list[asyncio.Future]): items = [] n_processed = 0
yield progress_update(ProgressUpdate(status="progress", data={}, total_docs=n_docs, processed_docs=0))
for doc in asyncio.as_completed(docs): result = await doc items.extend(result) n_processed += 1 yield 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))
return StreamingResponse(_stream_generator(process_futures), media_type="text/event-stream")1234567891011121314151617181920212223242526272829303132333435from fastapi import APIRouter, Depends, HTTPExceptionfrom litellm.router import Routerfrom dependencies import get_llm_routerfrom schemas import ReqSearchLLMResponse, ReqSearchRequest, ReqSearchResponse
# Router for all requirementsrouter = APIRouter()
@router.post("/get_reqs_from_query", response_model=ReqSearchResponse)def find_requirements_from_problem_description(req: ReqSearchRequest, llm_router: Router = Depends(get_llm_router)): """Finds the requirements that adress a given problem description from an extracted list"""
requirements = req.requirements query = req.query
requirements_text = "\n".join( [f"[Selection ID: {r.req_id} | Document: {r.document} | Context: {r.context} | Requirement: {r.requirement}]" for r in requirements]) print("Called the LLM") resp_ai = llm_router.completion( model="gemini-v2", messages=[{"role": "user", "content": f"Given all the requirements : \n {requirements_text} \n and the problem description \"{query}\", return a list of 'Selection ID' for the most relevant corresponding requirements that reference or best cover the problem. If none of the requirements covers the problem, simply return an empty list"}], response_format=ReqSearchLLMResponse ) print("Answered") print(resp_ai.choices[0].message.content)
out_llm = ReqSearchLLMResponse.model_validate_json( resp_ai.choices[0].message.content).selected
if max(out_llm) > len(requirements) - 1: raise HTTPException( status_code=500, detail="LLM error : Generated a wrong index, please try again.")
return ReqSearchResponse(requirements=[requirements[i] for i in out_llm])123454667897111213141516171819202122891011121314151617281819204 unmodified lines2526272829303132335 unmodified lines39404150515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864243489490491492493494495496497498499500501502503504505506507508509510511512513514515444546import asyncioimport loggingfrom dotenv import load_dotenvfrom typing import Literalimport nltkimport stringimport warningsimport ioimport tracebackimport zipfileimport jsonimport osimport requestsimport subprocessimport pandas as pdimport refrom lxml import etreefrom typing import Literalfrom dotenv import load_dotenvfrom nltk.tokenize import word_tokenizefrom bs4 import BeautifulSoupfrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizerfrom fastapi import FastAPI, BackgroundTasks, HTTPException, Requestfrom fastapi import Depends, FastAPI, BackgroundTasks, HTTPException, Requestfrom fastapi.staticfiles import StaticFilesfrom dependencies import get_llm_router, init_dependenciesimport api.docsimport api.requirementsfrom api.docs import docx_to_txtfrom schemas import *from fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponse, StreamingResponsefrom litellm.router import Routerfrom aiolimiter import AsyncLimiter
load_dotenv()
4 unmodified lines datefmt='%Y-%m-%d %H:%M:%S')
# Initialize global dependenciesinit_dependencies()
# Download required packages for NLTKnltk.download('stopwords')nltk.download('punkt_tab')5 unmodified linesapp.add_middleware(CORSMiddleware, allow_credentials=True, allow_headers=[ "*"], allow_methods=["*"], allow_origins=["*"])
llm_router = Router(model_list=[ { "model_name": "gemini-v1", "litellm_params": { "model": "gemini/gemini-2.0-flash", "api_key": os.environ.get("GEMINI"), "max_retries": 5, "rpm": 15, "allowed_fails": 1, "cooldown": 30, } }, { "model_name": "gemini-v2", "litellm_params": { "model": "gemini/gemini-2.5-flash", "api_key": os.environ.get("GEMINI"), "max_retries": 5, "rpm": 10, "allowed_fails": 1, "cooldown": 30, } }], fallbacks=[{"gemini-v2": ["gemini-v1"]}], num_retries=10, retry_after=30)
lemmatizer = WordNetLemmatizer()
NSMAP = { 'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main', 'v': 'urn:schemas-microsoft-com:vml'}
def lemma(text: str): stop_words = set(stopwords.words('english')) txt = text.translate(str.maketrans('', '', string.punctuation)).strip() tokens = [token for token in word_tokenize( txt.lower()) if token not in stop_words] return [lemmatizer.lemmatize(token) for token in tokens]
def get_docx_archive(url: str) -> zipfile.ZipFile: """Récupère le docx depuis l'URL et le retourne comme objet ZipFile""" if not url.endswith("zip"): raise ValueError("URL doit pointer vers un fichier ZIP") doc_id = os.path.splitext(os.path.basename(url))[0] resp = requests.get(url, verify=False, headers={ "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' }) resp.raise_for_status()
with zipfile.ZipFile(io.BytesIO(resp.content)) as zf: for file_name in zf.namelist(): if file_name.endswith(".docx"): docx_bytes = zf.read(file_name) return zipfile.ZipFile(io.BytesIO(docx_bytes)) elif file_name.endswith(".doc"): input_path = f"/tmp/{doc_id}.doc" output_path = f"/tmp/{doc_id}.docx" docx_bytes = zf.read(file_name)
with open(input_path, "wb") as f: f.write(docx_bytes)
subprocess.run([ "libreoffice", "--headless", "--convert-to", "docx", "--outdir", "/tmp", input_path ], check=True)
with open(output_path, "rb") as f: docx_bytes = f.read()
os.remove(input_path) os.remove(output_path)
return zipfile.ZipFile(io.BytesIO(docx_bytes))
raise ValueError("Aucun fichier docx/doc trouvé dans l'archive")
def parse_document_xml(docx_zip: zipfile.ZipFile) -> etree._ElementTree: """Parse le document.xml principal""" xml_bytes = docx_zip.read('word/document.xml') parser = etree.XMLParser(remove_blank_text=True) return etree.fromstring(xml_bytes, parser=parser)
def clean_document_xml(root: etree._Element) -> None: """Nettoie le XML en modifiant l'arbre directement""" # Suppression des balises <w:del> et leur contenu for del_elem in root.xpath('//w:del', namespaces=NSMAP): parent = del_elem.getparent() if parent is not None: parent.remove(del_elem)
# Désencapsulation des balises <w:ins> for ins_elem in root.xpath('//w:ins', namespaces=NSMAP): parent = ins_elem.getparent() index = parent.index(ins_elem) for child in ins_elem.iterchildren(): parent.insert(index, child) index += 1 parent.remove(ins_elem)
# Nettoyage des commentaires for tag in ['w:commentRangeStart', 'w:commentRangeEnd', 'w:commentReference']: for elem in root.xpath(f'//{tag}', namespaces=NSMAP): parent = elem.getparent() if parent is not None: parent.remove(elem)
def create_modified_docx(original_zip: zipfile.ZipFile, modified_root: etree._Element) -> bytes: """Crée un nouveau docx avec le XML modifié""" output = io.BytesIO()
with zipfile.ZipFile(output, 'w', compression=zipfile.ZIP_DEFLATED) as new_zip: # Copier tous les fichiers non modifiés for file in original_zip.infolist(): if file.filename != 'word/document.xml': new_zip.writestr(file, original_zip.read(file.filename))
# Ajouter le document.xml modifié xml_str = etree.tostring( modified_root, xml_declaration=True, encoding='UTF-8', pretty_print=True ) new_zip.writestr('word/document.xml', xml_str)
output.seek(0) return output.getvalue()
def docx_to_txt(doc_id: str, url: str): docx_zip = get_docx_archive(url) root = parse_document_xml(docx_zip) clean_document_xml(root) modified_bytes = create_modified_docx(docx_zip, root)
input_path = f"/tmp/{doc_id}_cleaned.docx" output_path = f"/tmp/{doc_id}_cleaned.txt" with open(input_path, "wb") as f: f.write(modified_bytes)
subprocess.run([ "libreoffice", "--headless", "--convert-to", "txt", "--outdir", "/tmp", input_path ], check=True)
with open(output_path, "r", encoding="utf-8") as f: txt_data = [line.strip() for line in f if line.strip()]
os.remove(input_path) os.remove(output_path) return txt_data
# ============================================= Doc routes =========================================================
@app.post("/get_meetings", response_model=MeetingsResponse)def get_meetings(req: MeetingsRequest): working_group = req.working_group tsg = 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_" + tsg logging.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 = None for folder in wg_folders: if "wg" + str(wg_number) in folder.lower(): selected_folder = folder break
url += "/" + selected_folder logging.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())] all_meetings = [working_group + "#" + meeting.split("_", 1)[1].replace("_", " ").replace( "-", " ") if meeting.startswith('TSG') else meeting.replace("-", "#") for meeting in meeting_folders]
return MeetingsResponse(meetings=dict(zip(all_meetings, meeting_folders)))
# ============================================================================================================================================
@app.post("/get_dataframe", response_model=DataResponse)def get_change_request_dataframe(req: DataRequest): 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) soup = BeautifulSoup(resp.text, "html.parser") wg_folders = [item.get_text() for item in soup.select("tr td a")] selected_folder = None for folder in wg_folders: if "wg" + str(wg_number) in folder.lower(): selected_folder = folder break
url += "/" + 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")]
if files == []: raise HTTPException(status_code=404, detail="No XLSX has been found")
def gen_url(tdoc: str): 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")) & ~( 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)
df = filtered_df.fillna("") return DataResponse(data=df[["TDoc", "Title", "Type", "TDoc Status", "Agenda item description", "URL"]].to_dict(orient="records"))
# ==================================================================================================================================
@app.post("/download_tdocs")def download_tdocs(req: DownloadRequest): """Download the specified TDocs and zips them in a single archive""" documents = req.documents
logging.info(f"Downloading TDocs: {documents}")
def process_document(doc: str): doc_id = doc url = requests.post( 'https://organizedprogrammers-3gppdocfinder.hf.space/find', headers={"Content-Type": "application/json"}, data=json.dumps({"doc_id": doc_id}), verify=False ) logging.info( f"Retrieving URL for doc {doc_id} returned http status {url.status_code}") url = url.json()['url'] logging.debug(f"Doc URL for {doc_id} is {url}")
try: txt = "\n".join(docx_to_txt(doc_id, url)) except Exception as e: txt = f"Document {doc_id} text extraction failed: {e}" return doc_id, txt.encode("utf-8")
# PERF: use asyncio? def process_batch(batch): results = {} for doc in batch: try: doc_id, file_bytes = process_document(doc) results[doc_id] = file_bytes except Exception as e: traceback.print_exception(e) results[doc] = b"Erreur" return results
documents_bytes = process_batch(documents)
zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, mode='w', compression=zipfile.ZIP_DEFLATED) as zip_file: for doc_id, txt_data in documents_bytes.items(): zip_file.writestr(f'{doc_id}.txt', txt_data)
zip_buffer.seek(0) return StreamingResponse( zip_buffer, media_type="application/zip" )
# ========================================================================================================================
@app.post("/generate_requirements", response_model=RequirementsResponse)async def gen_reqs(req: RequirementsRequest, background_tasks: BackgroundTasks): """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: traceback.print_exception(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)
# ======================================================================================================================================================================================
class ProgressUpdate(BaseModel): """Defines the structure of a single SSE message.""" status: Literal["progress", "complete"] data: dict total_docs: int processed_docs: int
@app.post("/generate_requirements/sse")async def gen_reqs(req: RequirementsRequest, con: Request): """Extract requirements from the specified TDocs 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]))
# limit max concurrency of LLM requests to prevent a huge pile of errors because of small rate limits concurrency_sema = asyncio.Semaphore(4)
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) -> list[DocRequirements]: doc_id = doc.document url = doc.url
# convert the docx to txt for use try: full = "\n".join(docx_to_txt(doc_id, url)) except Exception as e: traceback.print_exception(e) return [DocRequirements(document=doc_id, context="Error LLM", requirements=[])]
try: await concurrency_sema.acquire()
model_used = "gemini-v2" resp_ai = await llm_router.acompletion( model=model_used, 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: return [DocRequirements(document=doc_id, context="Error LLM", requirements=[])] finally: concurrency_sema.release()
# futures for all processed documents process_futures = [_process_document(doc) for doc in documents]
# lambda to print progress def progress_update(x): return f"data: {x.model_dump_json()}\n\n"
# async generator that generates the SSE events for progress async def _stream_generator(docs: list[asyncio.Future]): items = [] n_processed = 0
yield progress_update(ProgressUpdate(status="progress", data={}, total_docs=n_docs, processed_docs=0))
for doc in asyncio.as_completed(docs): result = await doc items.extend(result) n_processed += 1 yield 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))
return StreamingResponse(_stream_generator(process_futures), media_type="text/event-stream")# =======================================================================================================================================================================================
@app.post("/get_reqs_from_query", response_model=ReqSearchResponse)def find_requirements_from_problem_description(req: ReqSearchRequest): requirements = req.requirements query = req.query
requirements_text = "\n".join( [f"[Selection ID: {r.req_id} | Document: {r.document} | Context: {r.context} | Requirement: {r.requirement}]" for r in requirements]) print("Called the LLM") resp_ai = llm_router.completion( model="gemini-v2", messages=[{"role": "user", "content": f"Given all the requirements : \n {requirements_text} \n and the problem description \"{query}\", return a list of 'Selection ID' for the most relevant corresponding requirements that reference or best cover the problem. If none of the requirements covers the problem, simply return an empty list"}], response_format=ReqSearchLLMResponse ) print("Answered") print(resp_ai.choices[0].message.content)
out_llm = ReqSearchLLMResponse.model_validate_json( resp_ai.choices[0].message.content).selected
if max(out_llm) > len(requirements) - 1: raise HTTPException( status_code=500, detail="LLM error : Generated a wrong index, please try again.")
return ReqSearchResponse(requirements=[requirements[i] for i in out_llm])
app.include_router(api.docs.router, prefix="/docs")app.include_router(api.requirements.router, prefix="/requirements")app.mount("/", StaticFiles(directory="static", html=True), name="static")123456789101112131415161718192021222324252627282930313233343536373839404142import osfrom litellm.router import Router
# Declare all global app dependencies here# - Setup your dependency global inside init_dependencies()# - Create a get_xxxx_() function to retrieve the dependency inside the FastAPI router
def init_dependencies(): """Initialize the application global dependencies"""
global llm_router llm_router = Router(model_list=[ { "model_name": "gemini-v1", "litellm_params": { "model": "gemini/gemini-2.0-flash", "api_key": os.environ.get("GEMINI"), "max_retries": 5, "rpm": 15, "allowed_fails": 1, "cooldown": 30, } }, { "model_name": "gemini-v2", "litellm_params": { "model": "gemini/gemini-2.5-flash", "api_key": os.environ.get("GEMINI"), "max_retries": 5, "rpm": 10, "allowed_fails": 1, "cooldown": 30, } }], fallbacks=[{"gemini-v2": ["gemini-v1"]}], num_retries=10, retry_after=30)
def get_llm_router() -> Router: """Retrieves the LLM router""" return llm_router31 unmodified lines323334353536373824 unmodified lines6364656666676869168 unmodified lines23823924024124124224324477 unmodified lines322323324325325326327328334 unmodified lines66366466566666666766866931 unmodified lines toggleElementsEnabled(['get-meetings-btn'], false);
try { const response = await fetch('/get_meetings', { const response = await fetch('/docs/get_meetings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ working_group: workingGroup })24 unmodified lines toggleElementsEnabled(['get-tdocs-btn'], false);
try { const response = await fetch('/get_dataframe', { const response = await fetch('/docs/get_dataframe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ working_group: workingGroup, meeting: meeting })168 unmodified lines // Transformer au format requis: [{tdoc_id: url}, ...] const documents = selectedData.map(obj => obj.document)
const response = await fetch('/download_tdocs', { const response = await fetch('/docs/download_tdocs', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ documents: documents })77 unmodified lines toggleElementsEnabled(['extract-requirements-btn'], false);
try { const response = await postWithSSE('/generate_requirements/sse', { documents: selectedData }, { const response = await postWithSSE('/docs/generate_requirements/sse', { documents: selectedData }, { onMessage: (msg) => { console.log("SSE message:"); console.log(msg);334 unmodified lines
try { // Préparer les requirements pour la recherche const response = await fetch('/get_reqs_from_query', { const response = await fetch('/requirements/get_reqs_from_query', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({api/docs.py+438
api/requirements.pyAdded+35
app.py+12-482
dependencies.pyAdded+42
static/js/script.js+5-5