Ronak0 commited on
Commit
d12f5bd
·
verified ·
1 Parent(s): c8c50d3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -10
app.py CHANGED
@@ -1,15 +1,15 @@
1
  import os
2
  import re
3
- import uvicorn
4
  from fastapi import FastAPI, UploadFile, File
5
  from fastapi.middleware.cors import CORSMiddleware
6
  import pymupdf
7
  import torch
8
  from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
 
9
 
 
10
  app = FastAPI(title="CaseLoop PDF Simplifier Engine")
11
 
12
- # Allow frontend cross-origin requests
13
  app.add_middleware(
14
  CORSMiddleware,
15
  allow_origins=["*"],
@@ -18,7 +18,7 @@ app.add_middleware(
18
  allow_headers=["*"],
19
  )
20
 
21
- # 1. Load Tokenizer & Model
22
  MODEL_ID = "Ronak0/last-caseloop-pdf-simplifier"
23
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
24
  model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_ID)
@@ -35,7 +35,6 @@ def extract_clean_text(pdf_bytes: bytes) -> str:
35
  return " ".join(full_text)[:2000]
36
 
37
  def clean_and_split_bullets(raw_output: str) -> list[str]:
38
- # Replace numbered prefixes and bullet symbols with newlines
39
  normalized = re.sub(r'(?:^\d+\.|\n\d+\.|\s*•\s*)', '\n', raw_output)
40
  lines = [line.strip() for line in normalized.split('\n') if line.strip()]
41
 
@@ -48,9 +47,9 @@ def clean_and_split_bullets(raw_output: str) -> list[str]:
48
 
49
  return cleaned_points
50
 
51
- @app.get("/")
52
- def health_check():
53
- return {"status": "online", "model": MODEL_ID, "device": device}
54
 
55
  @app.post("/simplify")
56
  async def simplify_pdf(file: UploadFile = File(...)):
@@ -78,7 +77,37 @@ async def simplify_pdf(file: UploadFile = File(...)):
78
  "simplified_points": formatted_bullets
79
  }
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  if __name__ == "__main__":
82
- # Hugging Face Spaces mandates port 7860
83
- port = int(os.environ.get("PORT", 7860))
84
- uvicorn.run(app, host="0.0.0.0", port=port)
 
1
  import os
2
  import re
 
3
  from fastapi import FastAPI, UploadFile, File
4
  from fastapi.middleware.cors import CORSMiddleware
5
  import pymupdf
6
  import torch
7
  from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
8
+ import gradio as gr
9
 
10
+ # 1. FastAPI App Initialization
11
  app = FastAPI(title="CaseLoop PDF Simplifier Engine")
12
 
 
13
  app.add_middleware(
14
  CORSMiddleware,
15
  allow_origins=["*"],
 
18
  allow_headers=["*"],
19
  )
20
 
21
+ # 2. Load Model & Tokenizer
22
  MODEL_ID = "Ronak0/last-caseloop-pdf-simplifier"
23
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
24
  model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_ID)
 
35
  return " ".join(full_text)[:2000]
36
 
37
  def clean_and_split_bullets(raw_output: str) -> list[str]:
 
38
  normalized = re.sub(r'(?:^\d+\.|\n\d+\.|\s*•\s*)', '\n', raw_output)
39
  lines = [line.strip() for line in normalized.split('\n') if line.strip()]
40
 
 
47
 
48
  return cleaned_points
49
 
50
+ @app.get("/health")
51
+ def health():
52
+ return {"status": "online", "model": MODEL_ID}
53
 
54
  @app.post("/simplify")
55
  async def simplify_pdf(file: UploadFile = File(...)):
 
77
  "simplified_points": formatted_bullets
78
  }
79
 
80
+ # 3. Mount Gradio interface to satisfy HF Gradio-SDK health probes (/api/config)
81
+ def gradio_simplify(pdf_file):
82
+ if not pdf_file:
83
+ return "Upload a PDF document to test."
84
+ with open(pdf_file.name, "rb") as f:
85
+ raw_text = extract_clean_text(f.read())
86
+ prompt = f"Simplify civic/RTI document:\n{raw_text}"
87
+ inputs = tokenizer(prompt, return_tensors="pt", max_length=512, truncation=True).to(device)
88
+ with torch.no_grad():
89
+ outputs = model.generate(
90
+ **inputs,
91
+ max_new_tokens=300,
92
+ no_repeat_ngram_size=3,
93
+ repetition_penalty=1.2,
94
+ temperature=0.2,
95
+ num_beams=2,
96
+ do_sample=False
97
+ )
98
+ gen = tokenizer.decode(outputs[0], skip_special_tokens=True)
99
+ return "\n".join(clean_and_split_bullets(gen))
100
+
101
+ demo = gr.Interface(
102
+ fn=gradio_simplify,
103
+ inputs=gr.File(label="Upload PDF Document", file_types=[".pdf"]),
104
+ outputs=gr.Textbox(label="Simplified Takeaways"),
105
+ title="CaseLoop PDF Simplifier"
106
+ )
107
+
108
+ # Mounts Gradio on top of FastAPI and launches on 7860
109
+ app = gr.mount_gradio_app(app, demo, path="/")
110
+
111
  if __name__ == "__main__":
112
+ import uvicorn
113
+ uvicorn.run(app, host="0.0.0.0", port=7860)