Spaces:
Sleeping
Sleeping
Upload app (8).py
Browse files- app (8).py +54 -0
app (8).py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import fitz
|
| 3 |
+
import torch
|
| 4 |
+
from transformers import pipeline
|
| 5 |
+
import time, logging
|
| 6 |
+
|
| 7 |
+
logging.basicConfig(level=logging.ERROR)
|
| 8 |
+
device = -1 # CPU-only
|
| 9 |
+
print("β οΈ CPU-only. Expect ~20β30s for 300,000 chars.")
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
summarizer = pipeline("summarization", model="t5-small", device=device, torch_dtype=torch.float32)
|
| 13 |
+
except Exception as e:
|
| 14 |
+
print(f"β Model loading failed: {str(e)}")
|
| 15 |
+
exit(1)
|
| 16 |
+
|
| 17 |
+
def summarize_file(file_bytes):
|
| 18 |
+
start = time.time()
|
| 19 |
+
print(f"File type: {type(file_bytes)}")
|
| 20 |
+
try:
|
| 21 |
+
text = "".join(page.get_text("text", flags=16) for page in fitz.open(stream=file_bytes, filetype="pdf")) if file_bytes[:4].startswith(b'%PDF') else file_bytes.decode("utf-8", errors="ignore")
|
| 22 |
+
except Exception as e:
|
| 23 |
+
return f"β Text extraction failed: {str(e)}"
|
| 24 |
+
if not text.strip(): return "β No text found"
|
| 25 |
+
text = text[:300000]
|
| 26 |
+
chunks = [text[i:i+2000] for i in range(0, len(text), 2000)]
|
| 27 |
+
print(f"Chunks created: {len(chunks)}")
|
| 28 |
+
if not chunks: return "β No chunks to summarize"
|
| 29 |
+
summaries = []
|
| 30 |
+
for i, chunk in enumerate(chunks):
|
| 31 |
+
if time.time() - start > 15:
|
| 32 |
+
summaries.append("β οΈ Stopped early")
|
| 33 |
+
break
|
| 34 |
+
try:
|
| 35 |
+
summary = summarizer(chunk, max_length=60, min_length=10, do_sample=False)[0]['summary_text']
|
| 36 |
+
summaries.append(f"**Chunk {i+1}**:\n{summary}")
|
| 37 |
+
except Exception as e:
|
| 38 |
+
summaries.append(f"**Chunk {i+1}**: β Error: {str(e)}")
|
| 39 |
+
return f"**Chars**: {len(text)}\n**Time**: {time.time()-start:.2f}s\n\n" + "\n\n".join(summaries)
|
| 40 |
+
|
| 41 |
+
demo = gr.Interface(
|
| 42 |
+
fn=summarize_file, inputs=gr.File(label="π PDF/TXT Notes", type="binary"),
|
| 43 |
+
outputs=gr.Textbox(label="π Summary"),
|
| 44 |
+
title="Fast Summarizer", description="300,000+ chars in ~20β30s (CPU)"
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
if __name__ == "__main__":
|
| 48 |
+
try:
|
| 49 |
+
demo.launch(share=False, server_port=7860)
|
| 50 |
+
except Exception as e:
|
| 51 |
+
print(f"β Gradio launch failed: {str(e)}")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
|