CoolFace
Apppublic

VerdictAI/Legal_Document_Summarization

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py134 linesDownload Raw Back to root
1import gradio2print("Gradio version:", gradio.__version__)3 4import re5import pytesseract6from pdfminer.high_level import extract_text7from PIL import Image8from transformers import pipeline9import gradio as gr10 11 12# Load Summarization Model13summarizer = pipeline("summarization", model="facebook/bart-large-cnn")14 15def clean_text(text):16    text = re.sub(r'http[s]?://\S+', '', text)17    text = re.sub(r'www\.\S+', '', text)18    text = re.sub(r'\n+', ' ', text).strip()19    return text20 21def extract_text_from_pdf(pdf_file):22    text = extract_text(pdf_file.name)23    return clean_text(text)24 25def extract_text_from_image(image_file):26    image = Image.open(image_file)27    text = pytesseract.image_to_string(image)28    return clean_text(text)29 30def chunk_text(text, chunk_size=1000):31    return [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]32 33def summarize_text(text, max_length=200, min_length=50):34    chunks = chunk_text(text)35    summaries = []36    for chunk in chunks:37        try:38            summary = summarizer(chunk, max_length=max_length, min_length=min_length, do_sample=False)39            summaries.append(summary[0]['summary_text'])40        except Exception as e:41            print(f"Error summarizing chunk: {e}")42    return " ".join(summaries)43 44def gradio_handle_input(input_type, text_input, image_input, pdf_input):45    if input_type == "Text":46        text = text_input47    elif input_type == "Image":48        if image_input is None:49            return "", "Please upload an image."50        text = extract_text_from_image(image_input)51    elif input_type == "Pdf":52        if pdf_input is None:53            return "", "Please upload a PDF file."54        text = extract_text_from_pdf(pdf_input)55    else:56        return "", "Invalid input type."57 58    text = clean_text(text)59    if not text.strip():60        return "", "Error: extracted text is empty."61 62    summary = summarize_text(text)63    return text, summary64 65def toggle_inputs(choice):66    return (67        gr.update(visible=choice == "Text", value=""),68        gr.update(visible=choice == "Image"),69        gr.update(visible=choice == "Pdf"),70        gr.update(value=""),  # Clear preview if needed71        "", ""72    )73 74def download_summary(summary):75    if not summary.strip():76        return gr.update(visible=False), None77 78    file_path = "summary.txt"79    with open(file_path, "w", encoding="utf-8") as f:80        f.write(summary)81    return gr.update(visible=True, value=file_path)82 83with gr.Blocks(css="footer {visibility: hidden;}", title="Legal Document Summarization") as demo:84    gr.Markdown("## ๐Ÿ“„ Legal Document Summarization")85    gr.Markdown("""86### ๐Ÿ“˜ Steps to Use:87 881. Choose input type (โœ๏ธ Text / ๐Ÿ“„ PDF / ๐Ÿ–ผ๏ธ Image)  892. Enter your text or upload a file  903. Click **๐Ÿ“ Summarize**  914. View original input and โœ‚๏ธ summary below  92""")93 94    with gr.Row():95        with gr.Column(scale=1):96            input_type = gr.Radio(choices=["Text", "Pdf", "Image"], label="Select Input Type", value="Text")97            text_input = gr.Textbox(label="โœ๏ธ Enter Text", lines=15)98            image_input = gr.Image(label="๐Ÿ“ท Upload Image", visible=False, type="filepath")99            pdf_input = gr.File(label="๐Ÿ“„ Upload PDF", file_types=[".pdf"], visible=False)100            submit_btn = gr.Button("๐Ÿ“ Summarize")101        with gr.Column(scale=1):102            gr.Markdown("โณ *Note: Summarization may take some time depending on file size and system performance.*")103            gr.Markdown("๐Ÿ” **Summary Output**")104            output = gr.Textbox(label="", lines=15, interactive=False)105            download_btn = gr.Button("โฌ‡๏ธ Download Summary")106            file_output = gr.File(label="Download Summary", visible=False)107 108    gr.Markdown("""109> โš ๏ธ **Disclaimer:** This tool provides automatic summarizations of legal documents **for educational purposes only.**110> It does **not** constitute legal advice or professional consultation.111> Please consult a qualified legal professional for any legal matters.112""")113 114    input_type.change(115        fn=toggle_inputs,116        inputs=input_type,117        outputs=[text_input, image_input, pdf_input, output, text_input, output]118    )119 120    submit_btn.click(121        fn=gradio_handle_input,122        inputs=[input_type, text_input, image_input, pdf_input],123        outputs=[text_input, output]124    )125 126    download_btn.click(127        fn=download_summary,128        inputs=output,129        outputs=file_output130    )131 132if __name__ == "__main__":133    demo.launch()134