File size: 3,930 Bytes
494f6e7
 
 
 
 
e8c9ac3
494f6e7
 
e8c9ac3
 
 
 
 
 
 
 
494f6e7
 
 
 
e8c9ac3
 
 
 
494f6e7
 
 
 
 
 
 
 
 
 
 
 
 
 
e8c9ac3
 
494f6e7
 
 
 
 
 
 
 
 
 
 
e8c9ac3
 
494f6e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddf1fe2
494f6e7
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import streamlit as st
import fitz  # PyMuPDF
import openai
from fpdf import FPDF
import os
import tempfile

# Function to extract text from a PDF file
def extract_text_from_pdf(pdf_file):
    # Save the uploaded file to a temporary location
    temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
    temp_file.write(pdf_file.read())
    temp_file.close()  # Close the file to ensure it's saved

    # Open the saved PDF file
    doc = fitz.open(temp_file.name)
    text = ""
    for page_num in range(len(doc)):
        page = doc.load_page(page_num)
        text += page.get_text()

    # Delete the temporary file after reading (clean up)
    os.remove(temp_file.name)

    return text

# Function to ensure the summary ends with a full stop
def ensure_full_stop(text):
    text = text.strip()
    if not text.endswith(('.', '!', '?')):
        text += '.'
    return text

# Function to summarize text using OpenAI GPT model
def summarize_text(api_key, text):
    openai.api_key = api_key
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",  # Use "gpt-4" if you have access
        messages=[{"role": "system", "content": "You are a helpful assistant."},
                  {"role": "user", "content": f"Summarize the following text:\n\n{text}"}],
        max_tokens=500,
        temperature=0.5
    )
    summary = response.choices[0].message['content'].strip()
    return ensure_full_stop(summary)

# Function to predict the main topic of the text
def predict_topic(api_key, text):
    openai.api_key = api_key
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",  # Use "gpt-4" if you have access
        messages=[{"role": "system", "content": "You are a helpful assistant."},
                  {"role": "user", "content": f"What is the main topic of the following text?\n\n{text}"}],
        max_tokens=500,
        temperature=0.5
    )
    topic = response.choices[0].message['content'].strip()
    return topic

# Function to generate a PDF with summary and topic
def create_pdf(summary, topic, original_file_name):
    base_name = os.path.splitext(original_file_name)[0]  # Remove the .pdf extension
    pdf_file_name = f"{base_name} summary.pdf"  # Create the new filename

    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size=12)

    pdf.cell(200, 10, txt="Summary", ln=True, align='C')
    pdf.multi_cell(0, 10, txt=summary)

    pdf.cell(200, 10, txt="Predicted Main Topic", ln=True, align='C')
    pdf.multi_cell(0, 10, txt=topic)

    # Save the PDF to a file in memory
    pdf_file_path = f"/tmp/{pdf_file_name}"
    pdf.output(pdf_file_path)

    return pdf_file_path

# Streamlit UI
st.title("Research Paper Summarizer")

# API Key input
api_key = st.text_input("Enter your OpenAI API Key:", type="password")

# File upload
uploaded_file = st.file_uploader("Upload your research paper (PDF)", type=["pdf"])

if uploaded_file is not None:
    # Extract text from the uploaded PDF
    text = extract_text_from_pdf(uploaded_file)

    if len(text) > 1000:
        # Summarize the text
        summary = summarize_text(api_key, text)
        
        # Predict the main topic
        topic = predict_topic(api_key, text)

        # Display the results
        st.subheader("Summary")
        st.write(summary)
        
        st.subheader("Predicted Main Topic")
        st.write(topic)

        # Button to download results as a PDF
        if st.button("Get the Summary PDF"):
            pdf_path = create_pdf(summary, topic, uploaded_file.name)
            st.download_button(
                label="Download Summary PDF",
                data=open(pdf_path, "rb").read(),
                file_name=os.path.basename(pdf_path),
                mime="application/pdf"
            )
    else:
        st.warning("The document is too short for meaningful analysis.")
else:
    st.info("Please upload a valid PDF file to proceed.")