Spaces:
Sleeping
Sleeping
Update streamlit_app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119import streamlit as stimport requestsfrom bs4 import BeautifulSoupimport reimport pdfplumberfrom io import BytesIOfrom transformers import pipeline@st.cache_resourcedef get_summarizer():return pipeline("summarization", model="facebook/bart-large-cnn")summarizer = get_summarizer()st.title("Auto RBI Circular Scraper & Summarizer")st.markdown("""Automatically fetches and summarizes the latest RBI circular from the official RBI circular index.Supports both PDF and HTML circular content extraction.""")INDEX_URL = "https://www.rbi.org.in/scripts/bs_circularindexdisplay.aspx"def fetch_latest_circular_url(index_url):try:resp = requests.get(index_url, timeout=15)resp.raise_for_status()soup = BeautifulSoup(resp.text, "html.parser")links = []for a in soup.find_all("a", href=True):text = (a.get_text() or "").lower()href = a["href"]if "circular" in text or "circular" in href:full_url = href if href.startswith("http") else requests.compat.urljoin(index_url, href)links.append((text.strip(), full_url))if links:# Sort to get the latest circular by the most recent date detected in the link textdef extract_date(txt):m = re.search(r'(\d{4}-\d{2}-\d{2})', txt)if m:return m.group(1)return ""links.sort(key=lambda x: extract_date(x[0]), reverse=True)return links[0][1]except Exception as e:st.error(f"Error fetching circular index: {e}")return Noneif st.button("Fetch & Summarize Latest RBI Circular"):latest_circular_url = fetch_latest_circular_url(INDEX_URL)if latest_circular_url:st.write(f"Latest circular URL: {latest_circular_url}")try:resp = requests.get(latest_circular_url, timeout=20)resp.raise_for_status()content_type = resp.headers.get("Content-Type", "")full_text = ""if 'pdf' in content_type.lower() or latest_circular_url.lower().endswith('.pdf'):with pdfplumber.open(BytesIO(resp.content)) as pdf:for page in pdf.pages:text = page.extract_text()if text:full_text += text + "\n"else:soup = BeautifulSoup(resp.text, "html.parser")paragraphs = [p.get_text() for p in soup.find_all("p")]full_text = "\n".join(paragraphs)if full_text.strip():input_text = full_text[:6000] # Truncate if too longwith st.spinner("Generating summary..."):summary_result = summarizer(input_text, min_length=60, max_length=300, do_sample=False)summary = summary_result[0]['summary_text']st.subheader("Summary of Latest RBI Circular")st.write(summary)actionables = st.text_area("Actionable Items for Compliance Review", height=150)verified = st.checkbox("Compliance Team Verified & Approved")if verified:st.success("Compliance team has verified the content.")else:st.warning("Unable to extract meaningful text from the circular document.")except Exception as e:st.error(f"Error downloading or processing the latest circular: {e}")else:st.warning("Could not find the latest circular URL on the RBI site.")st.markdown("---")st.subheader("Alternatively, upload an RBI Circular PDF manually:")pdf_file = st.file_uploader("Upload RBI Circular PDF", type=["pdf"])if pdf_file:try:with pdfplumber.open(pdf_file) as pdf:pdf_text = ""for page in pdf.pages:page_text = page.extract_text()if page_text:pdf_text += page_text + " "if pdf_text:if st.button("Summarize Uploaded PDF"):with st.spinner("Generating summary..."):input_text = pdf_text[:6000]result = summarizer(input_text, min_length=60, max_length=300, do_sample=False)st.subheader("Summary of Uploaded Circular")st.write(result[0]['summary_text'])actionables = st.text_area("Actionable Items for Compliance Review", height=150)verified = st.checkbox("Mark as Verified")if verified:st.success("Content verified by compliance team.")else:st.warning("Could not extract text from uploaded PDF.")except Exception as e:st.error(f"Error processing uploaded file: {e}")st.caption("Built with Streamlit, Hugging Face Transformers, pdfplumber, and BeautifulSoup")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495import streamlit as stimport pdfplumberimport textwrapfrom transformers import pipeline# ------------------------------------------------------------# Load summarizer pipeline# ------------------------------------------------------------@st.cache_resourcedef load_model():# Using a lightweight model for faster, safer inferencereturn pipeline("summarization", model="sshleifer/distilbart-cnn-12-6")summarizer = load_model()# ------------------------------------------------------------# Helper: Chunk long text safely for summarization# ------------------------------------------------------------def generate_safe_summary(long_text, chunk_size=2500):"""Breaks lengthy text into smaller chunks and summarizes each section.Avoids token overflow and 'index out of range' errors."""chunks = textwrap.wrap(long_text, chunk_size)summaries = []for i, chunk in enumerate(chunks):try:# Run summarization with truncation and safe limitsresult = summarizer(chunk,min_length=50,max_length=250,do_sample=False,truncation=True)summaries.append(result[0]["summary_text"])except Exception as e:st.warning(f"Skipped chunk {i+1} due to error: {e}")continueif not summaries:return "No summary could be generated (empty or scanned PDF detected)."return "\n\n".join(summaries)# ------------------------------------------------------------# Streamlit UI# ------------------------------------------------------------st.title("RBI Circular PDF Summarizer & Compliance Workflow")st.markdown("""Upload any **RBI circular PDF** to automatically extract the text,generate an AI summary, and list compliance actionables for verification.""")# PDF upload block -----------------------------------------------------------pdf_file = st.file_uploader("Upload RBI Circular (PDF)", type=["pdf"])if pdf_file:try:extracted_text = ""with pdfplumber.open(pdf_file) as pdf:for page in pdf.pages:text = page.extract_text()if text:extracted_text += text + " "if extracted_text.strip() == "":st.error("No readable text found — this PDF may be scanned or image-based.")else:st.info("Text successfully extracted from the PDF!")if st.button("Summarize Circular"):with st.spinner("Generating summary safely..."):summary = generate_safe_summary(extracted_text)st.subheader("Summary")st.write(summary)actionables = st.text_area("Compliance Actionables (editable)",height=120,placeholder="List steps your bank must take to align with this circular...")verified = st.checkbox("Mark as Verified by Compliance Team")if verified:st.success("Verified and approved by the compliance team.")except Exception as e:st.error(f"Error processing uploaded file: {e}")else:st.info("Upload a PDF file to begin analysis.")# Footer ---------------------------------------------------------------------st.markdown("---")st.caption("Built with Streamlit, pdfplumber, and Hugging Face Transformers.")
streamlit_app.py+73-97