File size: 6,521 Bytes
24a9f83
6db081f
cfba4fe
35bfd69
c5c8ef0
24a9f83
cfba4fe
 
 
 
 
 
 
6db081f
cfba4fe
 
6db081f
cfba4fe
 
 
 
8267fce
cfba4fe
 
6db081f
 
cfba4fe
6db081f
cfba4fe
 
99fac0a
cfba4fe
 
8267fce
 
 
99fac0a
b94d84a
 
 
 
 
cfba4fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8267fce
6db081f
8267fce
cfba4fe
 
8267fce
cfba4fe
6db081f
cfba4fe
 
 
 
24a9f83
cfba4fe
24a9f83
cfba4fe
 
 
 
 
6db081f
cfba4fe
 
8267fce
cfba4fe
 
 
 
 
 
 
 
 
24a9f83
b94d84a
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
import gradio as gr
import openai
import fitz  # PyMuPDF
import os
import tempfile

# API Key input and status
def set_api_key(api_key):
    if api_key:
        openai.api_key = api_key
        return "API Key Set"
    else:
        return "API Key not set"

# PDF text extraction function
def extract_text_from_pdf(pdf_file):
    try:
        with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
            tmp_file.write(pdf_file.read())
            tmp_file_path = tmp_file.name
        doc = fitz.open(tmp_file_path)
        text = "\n".join([page.get_text("text") for page in doc])
        doc.close()
        os.remove(tmp_file_path)
        return text
    except Exception as e:
        return f"Error extracting text: {e}"

# Review generator function
def generate_review(api_key, uploaded_files, review_question, include_tables):
    if not api_key:
        return "Please enter your OpenAI API key."
    if not uploaded_files:
        return "Please upload at least one PDF file."
    if not review_question:
        return "Please enter a review question."
    
    # File type validation: check if all uploaded files are PDFs
    for file in uploaded_files:
        if not file.name.lower().endswith('.pdf'):
            return f"Invalid file type. Please upload a PDF file, but '{file.name}' is not a PDF."
    
    system_prompt = """
    You are an expert academic assistant. Create a systematic review in HTML format using <h2>, <h3>, <p>, <ul>, and <table> tags. The Systematic Review must be in great details. Structure it using these steps:
    Step 1: Identify a Research Field
    The first step in writing a systematic review paper is to identify a research field. This involves selecting a specific area of study that you are interested in and want to explore further.
    Step 2: Generate a Research Question
    Once you have identified your research field, the next step is to generate a research question. This question should be specific, measurable, achievable, relevant, and time-bound (SMART).
    Step 3: Create a Protocol
    After generating your research question, the next step is to create a protocol. A protocol is a detailed plan of how you will conduct your research, including the methods you will use, the data you will collect, and the analysis you will perform.
    Step 4: Evaluate Relevant Literature
    The fourth step is to evaluate relevant literature. This involves searching for and reviewing existing studies related to your research question. You should critically evaluate the quality of these studies and identify any gaps or limitations in the current literature.
    Step 5: Investigate Sources for Answers
    The fifth step is to investigate sources for answers. This involves searching for and accessing relevant data and information that will help you answer your research question. This may include conducting interviews, surveys, or experiments, or analyzing existing data.
    Step 6: Collect Data as per Protocol
    The sixth step is to collect data as per protocol. This involves implementing the methods outlined in your protocol and collecting the data specified. You should ensure that your data collection methods are rigorous and reliable.
    Step 7: Data Extraction
    The seventh step is to extract the data. This involves organizing and analyzing the data you have collected, and extracting the relevant information that will help you answer your research question.
    Step 8: Critical Analysis of Results
    The eighth step is to conduct a critical analysis of your results. This involves interpreting your findings, identifying patterns and trends, and drawing conclusions based on your data.
    Step 9: Interpreting Derivations
    The ninth step is to interpret the derivations. This involves taking the conclusions you have drawn from your data and interpreting them in the context of your research question.
    Step 10: Concluding Statements
    The final step is to make concluding statements. This involves summarizing your findings and drawing conclusions based on your research. You should also provide recommendations for future research and implications for practice.
    By following these steps, you can ensure that your systematic review paper is well-written, well-organized, and provides valuable insights into your research question.
    """

    texts = []
    filenames = []

    for file in uploaded_files:
        filenames.append(file.name)
        texts.append(extract_text_from_pdf(file))

    table_note = " Include relevant tables to compare methodologies, results, and limitations." if include_tables else ""
    user_prompt = (
        f"Generate a polished and structured systematic review in HTML using the following papers: {', '.join(filenames)}.\n"
        f"Review Question: {review_question}.{table_note}\n\n"
        + "\n\n".join([f"Paper {i+1}: {filenames[i]}\n{texts[i]}" for i in range(len(texts))])
    )

    try:
        response = openai.ChatCompletion.create(
            model="gpt-4.1",
            messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}],
            temperature=0.7,
            top_p=1,
            max_tokens=8192
        )
        review_html = response["choices"][0]["message"]["content"]
        download_button = gr.File(file_name="systematic_review.html", data=review_html)

        return [review_html, download_button]
    except Exception as e:
        return f"Error generating systematic review: {e}"

# Gradio Interface
api_key_input = gr.Textbox(label="API Key", type="password", placeholder="Enter OpenAI API Key", lines=1)
file_input = gr.File(label="Upload PDF Research Papers", file_count="multiple", file_types=["pdf"])
review_question_input = gr.Textbox(label="Review Question or Topic", placeholder="Please Generate a systematic review of the following papers.")
include_tables_input = gr.Checkbox(label="Include Comparison Tables", value=True)

output_review = gr.HTML(label="Generated Systematic Review")
output_download = gr.File(label="Download Review as .html")

# Create Interface
interface = gr.Interface(
    fn=generate_review,
    inputs=[api_key_input, file_input, review_question_input, include_tables_input],
    outputs=[output_review, output_download],
    live=True,
    title="Systematic Review Generator for Research Papers",
    description="Generate a polished and structured systematic review from multiple uploaded research papers."
)

interface.launch(share=True)