File size: 10,150 Bytes
7ab84cb 3a9dbab 7ab84cb 3a9dbab 7ab84cb 3a9dbab 7ab84cb 3a9dbab 7ab84cb 3a9dbab 7ab84cb 3a9dbab 7ab84cb 3a9dbab 7ab84cb 3a9dbab 7ab84cb 3a9dbab 7ab84cb |
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 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 |
import gradio as gr import openai import fitz # PyMuPDF for PDF processing import os import tempfile # Variable to store API key api_key = "" # Function to update API key def set_api_key(key): global api_key api_key = key return "API Key Set Successfully!" # Function to extract text from PDF def extract_text_from_pdf(pdf_path): try: doc = fitz.open(pdf_path) text = "\n".join([page.get_text("text") for page in doc]) return text except Exception as e: return f"Error extracting text from PDF: {str(e)}" # Function to interact with OpenAI API for systematic review def generate_systematic_review(pdf_files, review_question, include_tables=True): if not api_key: return "Please enter your OpenAI API key first." if not pdf_files: return "Please upload at least one PDF file." if not review_question: return "Please enter a review question." try: openai.api_key = api_key # Create the system message with systematic review guidelines 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 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. 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. Step-11: Please include references in the form of citation and also link to the reference papers. """ # Extract text from each PDF pdf_texts = [] pdf_names = [] for pdf_file in pdf_files: if isinstance(pdf_file, str): # If it's already a path pdf_path = pdf_file else: # If it's a file object pdf_path = pdf_file.name pdf_name = os.path.basename(pdf_path) pdf_text = extract_text_from_pdf(pdf_path) pdf_texts.append(pdf_text) pdf_names.append(pdf_name) # Prepare the user prompt with the review question and instructions table_instruction = "" if include_tables: table_instruction = " Please include important new generated tables in your review." user_prompt = f"Please generate a systematic review of the following {len(pdf_files)} papers: {', '.join(pdf_names)}.{table_instruction}\n\nReview Question: {review_question}" # Create the messages for the API call messages = [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt + "\n\n" + "\n\n".join([f"Paper {i+1} - {pdf_names[i]}:\n{pdf_texts[i]}" for i in range(len(pdf_texts))])} ] # Call the API with temperature=1 and top_p=1 as specified response = openai.ChatCompletion.create( model="gpt-4.1", messages=messages, temperature=0.7, top_p=1, max_tokens=16384 ) # Format the response in HTML review_content = response["choices"][0]["message"]["content"] # Create a basic HTML structure html_output = f""" <h2>Systematic Review</h2> <p>{review_content}</p> """ return html_output except Exception as e: return f"Error generating systematic review: {str(e)}" # Function to save uploaded files def save_uploaded_files(files): if not files: return [] saved_paths = [] for file in files: if file is not None: # Create a temporary file with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file: tmp_file.write(file) saved_paths.append(tmp_file.name) return saved_paths # Add CSS styling custom_css = """ <style> #generate_button { background: linear-gradient(135deg, #4a00e0 0%, #8e2de2 100%); /* Purple gradient */ color: white; font-weight: bold; } #generate_button:hover { background: linear-gradient(135deg, #5b10f1 0%, #9f3ef3 100%); /* Slightly lighter */ } #api_key_button { background: linear-gradient(135deg, #68d391 0%, #48bb78 100%); /* Green gradient */ color: white; font-weight: bold; margin-top: 27px; } #api_key_button:hover { background: linear-gradient(135deg, #38a169 0%, #68d391 100%); /* Slightly darker green */ } .gradio-container { font-family: 'Arial', sans-serif; background-color: #f0f4f8; } </style> """ # Gradio UI Layout with gr.Blocks(css=custom_css) as demo: gr.Markdown("# Systematic Review Generator for Research Papers") with gr.Accordion("How to Use This App", open=True): gr.Markdown(""" ### Getting Started: 1. Enter your OpenAI API key in the field below and click "Set API Key" 2. Upload multiple PDF research papers (2 or more recommended) 3. Enter your review question or topic 4. Check the "Include Tables" option if you want the review to include comparison tables 5. Click "Generate Systematic Review" to start the process ### Tips: - For best results, upload papers that are related to the same research topic or field - Be specific in your review question to get more focused results - The generated review will follow a systematic structure including research field identification, data extraction, analysis, and conclusions - The more papers you upload, the more comprehensive the review will be """) # API Key Input with gr.Row(): api_key_input = gr.Textbox(label="Enter OpenAI API Key", type="password") api_key_button = gr.Button("Set API Key", elem_id="api_key_button") api_key_output = gr.Textbox(label="API Key Status", interactive=False) # PDF Upload and Review Settings with gr.Row(): with gr.Column(): pdf_files = gr.File(label="Upload PDF Research Papers", file_count="multiple", type="binary") review_question = gr.Textbox(label="Review Question or Topic", value="Please Generate a systematic review of the following papers.") include_tables = gr.Checkbox(label="Include Comparison Tables", value=True) generate_button = gr.Button("Generate Systematic Review", elem_id="generate_button") # Output review_output = gr.HTML(label="Systematic Review") # Button actions api_key_button.click(set_api_key, inputs=[api_key_input], outputs=[api_key_output]) # Generate systematic review def process_files_and_generate_review(files, question, include_tables): if not files: return "Please upload at least one PDF file." # Save uploaded files saved_paths = save_uploaded_files(files) # Generate review review = generate_systematic_review(saved_paths, question, include_tables) # Clean up temporary files for path in saved_paths: try: os.remove(path) except: pass return review generate_button.click( process_files_and_generate_review, inputs=[pdf_files, review_question, include_tables], outputs=[review_output] ) # Launch the app if __name__ == "__main__": demo.launch(share=True) |