File size: 32,965 Bytes
24a9f83
6db081f
3bcebbc
35bfd69
3bcebbc
041ff73
 
24a9f83
3bcebbc
 
 
 
 
 
 
 
6db081f
3bcebbc
67b8403
6db081f
67b8403
8267fce
6db081f
 
3bcebbc
6db081f
6fe23ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bcebbc
6fe23ea
99fac0a
0baf74a
99fac0a
3bcebbc
0baf74a
fb22ee6
3bcebbc
0baf74a
b94d84a
8267fce
3bcebbc
 
 
a2df9a3
 
3bcebbc
 
 
 
cb56ae9
3bcebbc
 
cb56ae9
3bcebbc
cb56ae9
 
3bcebbc
cb56ae9
 
3bcebbc
cb56ae9
 
3bcebbc
 
cb56ae9
3bcebbc
cb56ae9
 
3bcebbc
cb56ae9
 
3bcebbc
cb56ae9
 
3bcebbc
cb56ae9
 
a2df9a3
cb56ae9
5dd199c
cb56ae9
 
6fe23ea
 
3bcebbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06265a9
 
 
6fe23ea
 
 
 
 
 
 
 
 
 
 
 
 
 
3bcebbc
6fe23ea
3bcebbc
 
 
 
 
 
 
a2df9a3
6db081f
3bcebbc
 
9727254
8267fce
9727254
6db081f
3bcebbc
a2df9a3
3bcebbc
 
6fe23ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2df9a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06265a9
a2df9a3
 
 
 
 
 
 
 
 
 
 
6fe23ea
 
 
 
 
 
 
a2df9a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bcebbc
0baf74a
a2df9a3
3bcebbc
24a9f83
a2df9a3
 
 
 
 
 
3bcebbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24a9f83
041ff73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2df9a3
1c9f036
 
a2df9a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c9f036
a2df9a3
1c9f036
 
a2df9a3
 
 
1c9f036
 
a2df9a3
 
 
1c9f036
a2df9a3
 
1c9f036
a2df9a3
1c9f036
 
 
a2df9a3
 
 
1c9f036
 
a2df9a3
 
 
1c9f036
a2df9a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
491c5fc
041ff73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6fe23ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2df9a3
 
 
 
 
6fe23ea
 
 
1c9f036
 
 
 
a2df9a3
dc77f2a
6fe23ea
fb22ee6
e56be65
0baf74a
3bcebbc
 
 
 
6fe23ea
 
 
 
 
 
 
 
 
3bcebbc
a2df9a3
 
3bcebbc
 
 
a2df9a3
3bcebbc
fb22ee6
a2df9a3
 
 
 
 
 
3bcebbc
fb22ee6
3bcebbc
a2df9a3
3bcebbc
a2df9a3
 
 
 
 
 
 
06265a9
6fe23ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2df9a3
 
491c5fc
041ff73
 
a2df9a3
 
 
3bcebbc
 
 
 
 
6fe23ea
 
 
 
3bcebbc
041ff73
a2df9a3
 
 
 
041ff73
3bcebbc
 
 
 
a2df9a3
041ff73
a2df9a3
6fe23ea
a2df9a3
 
 
 
 
 
 
 
 
 
 
 
 
041ff73
 
6fe23ea
 
 
 
 
 
 
 
 
 
 
 
 
3bcebbc
491c5fc
041ff73
 
491c5fc
 
041ff73
 
491c5fc
041ff73
 
 
 
 
3bcebbc
 
 
 
 
 
 
491c5fc
3bcebbc
 
 
6fe23ea
 
 
 
041ff73
fb22ee6
24a9f83
3bcebbc
 
a2df9a3
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
import gradio as gr
import openai
import fitz  # PyMuPDF for PDF processing
import os
import tempfile
import base64
from datetime import datetime

# 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 generate PRISMA flow chart SVG
def generate_prisma_flow_chart(records_db, records_other, duplicates, excluded_screening, excluded_fulltext, included_studies, 
                              included_meta=None, fulltext_assessed=None):
    # Calculate values if not provided
    if fulltext_assessed is None:
        fulltext_assessed = excluded_fulltext + included_studies
    
    records_after_duplicates = records_db + records_other - duplicates
    
    # Create SVG content for PRISMA flow chart
    svg_content = f'''
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" width="700" height="700">
        <style>
            .box {{
                fill: #f9f9f9;
                stroke: #333;
                stroke-width: 2;
            }}
            .arrow {{
                stroke: #333;
                stroke-width: 2;
                marker-end: url(#arrowhead);
            }}
            text {{
                font-family: Arial, sans-serif;
                font-size: 14px;
                text-anchor: middle;
            }}
            .box-title {{
                font-weight: bold;
            }}
        </style>
        
        <defs>
            <marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
                <polygon points="0 0, 10 3.5, 0 7" />
            </marker>
        </defs>
        
        <!-- Identification Section -->
        <rect x="250" y="30" width="300" height="60" class="box" />
        <text x="400" y="50" class="box-title">Identification</text>
        <text x="400" y="75">Records identified through database searching</text>
        <text x="400" y="90">(n = {records_db})</text>
        
        <rect x="600" y="30" width="150" height="60" class="box" />
        <text x="675" y="50" class="box-title">Additional</text>
        <text x="675" y="75">Other sources</text>
        <text x="675" y="90">(n = {records_other})</text>
        
        <!-- Arrows -->
        <line x1="400" y1="90" x2="400" y2="130" class="arrow" />
        <line x1="675" y1="90" x2="675" y2="110" class="arrow" />
        <line x1="675" y1="110" x2="400" y2="110" class="arrow" />
        
        <!-- Screening Section -->
        <rect x="250" y="130" width="300" height="60" class="box" />
        <text x="400" y="150" class="box-title">Screening</text>
        <text x="400" y="175">Records after duplicates removed</text>
        <text x="400" y="190">(n = {records_after_duplicates})</text>
        
        <line x1="400" y1="190" x2="400" y2="230" class="arrow" />
        
        <rect x="250" y="230" width="300" height="60" class="box" />
        <text x="400" y="250" class="box-title">Title/Abstract Screening</text>
        <text x="400" y="275">Records screened</text>
        <text x="400" y="290">(n = {records_after_duplicates})</text>
        
        <rect x="600" y="230" width="150" height="60" class="box" />
        <text x="675" y="255">Records excluded</text>
        <text x="675" y="275">(n = {excluded_screening})</text>
        
        <line x1="400" y1="290" x2="400" y2="330" class="arrow" />
        <line x1="550" y1="260" x2="600" y2="260" class="arrow" />
        
        <!-- Eligibility Section -->
        <rect x="250" y="330" width="300" height="60" class="box" />
        <text x="400" y="350" class="box-title">Eligibility</text>
        <text x="400" y="375">Full-text articles assessed for eligibility</text>
        <text x="400" y="390">(n = {fulltext_assessed})</text>
        
        <rect x="600" y="330" width="150" height="60" class="box" />
        <text x="675" y="350">Full-text articles</text>
        <text x="675" y="370">excluded, with reasons</text>
        <text x="675" y="390">(n = {excluded_fulltext})</text>
        
        <line x1="400" y1="390" x2="400" y2="430" class="arrow" />
        <line x1="550" y1="360" x2="600" y2="360" class="arrow" />
        
        <!-- Included Section -->
        <rect x="250" y="430" width="300" height="60" class="box" />
        <text x="400" y="450" class="box-title">Included</text>
        <text x="400" y="475">Studies included in qualitative synthesis</text>
        <text x="400" y="490">(n = {included_studies})</text>
        
        <!-- Optional Meta-Analysis Box -->
        {f'''
        <line x1="400" y1="490" x2="400" y2="530" class="arrow" />
        <rect x="250" y="530" width="300" height="60" class="box" />
        <text x="400" y="550" class="box-title">Meta-Analysis</text>
        <text x="400" y="575">Studies included in quantitative synthesis</text>
        <text x="400" y="590">(n = {included_meta})</text>
        ''' if included_meta is not None else ''}
        
        <!-- PRISMA Title -->
        <text x="150" y="25" style="font-size: 18px; font-weight: bold; text-anchor: start;">PRISMA Flow Diagram</text>
    </svg>
    '''
    
    return svg_content

# Function to interact with OpenAI API for systematic review
def generate_systematic_review(pdf_files, review_question, prisma_numbers, 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 using academic research paper formatting. 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). Consider using the PICO framework (Population, Intervention, Comparison, Outcome) to structure clinical questions.
        
        Step 3: Create a Protocol
        After generating your research question, create a detailed protocol. This is a comprehensive plan outlining your research methodology, including search strategies, databases to be used, and analysis techniques. The protocol should be registered in appropriate databases (e.g., PROSPERO) when applicable and follow PRISMA guidelines.
        
        Step 4: Define Inclusion and Exclusion Criteria
        Clearly articulate the criteria for including or excluding studies in your review. These criteria should be directly tied to your research question and may include: publication date range, study types, population characteristics, intervention specifications, outcome measures, and language restrictions.
        
        Step 5: Evaluate Relevant Literature
        Conduct a comprehensive literature search using multiple databases (e.g., PubMed, Scopus, Web of Science, CINAHL) with clearly defined search terms and Boolean operators. Document your search strategy in detail to ensure reproducibility. Consider both published and unpublished (gray) literature to minimize publication bias.
        
        Step 6: Quality Assessment of Studies
        Apply established quality assessment tools appropriate for your included study designs (e.g., Cochrane Risk of Bias Tool for randomized trials, ROBINS-I for non-randomized studies, CASP checklists). Document quality assessments for all included studies.
        
        Step 7: Data Extraction
        Create and use a standardized data extraction form to systematically collect relevant information from each study. This should include: study characteristics, participant demographics, intervention details, comparison groups, outcome measures, and results. Have multiple reviewers extract data independently when possible.
        
        Step 8: Data Synthesis and Analysis
        Synthesize the extracted data using appropriate methods. If statistical pooling is appropriate, conduct meta-analysis with suitable models (fixed or random effects). If heterogeneity precludes meta-analysis, provide a narrative synthesis with clear explanations.
        
        Step 9: Critical Analysis of Results
        Analyze your findings critically, examining patterns, inconsistencies, and relationships across studies. Address heterogeneity, publication bias (using funnel plots when applicable), and methodological limitations. Consider using the GRADE approach to evaluate certainty of evidence.
        
        Step 10: Interpreting Findings
        Interpret your findings in the context of the original research question. Discuss implications for practice, policy, and future research. Address limitations of your systematic review process and any potential biases.
        
        Step 11: Concluding Statements
        Provide clear, substantiated conclusions based on your review findings. Ensure conclusions are proportionate to the evidence presented and acknowledge uncertainty where appropriate. Offer specific recommendations for future research.
        
        Step 12: References and Documentation
        Include a comprehensive reference list following a specific citation style (APA, Vancouver, etc.). Provide links to source papers when available.
        
        Your response should be formatted in HTML (but avoid showing these tags ```html ```) but generate the content to look like a professional academic paper. Include proper section headers, abstracts, methodology sections, etc. Number all sections like an academic paper. Follow academic journal standards with double spacing, appropriate margins, and consistent formatting throughout.

        Make sure to include that you conducted a PRISMA flow diagram as part of the methodology section. Reference the PRISMA diagram in your methodology section and explain the numbers used in the diagram.
        """
        
        # 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."
        
        # Add PRISMA flow information
        prisma_info = f"""
        Additionally, I have conducted a PRISMA flow diagram with the following data:
        - Records identified through database searching: {prisma_numbers['records_db']}
        - Additional records identified through other sources: {prisma_numbers['records_other']}
        - Records after duplicates removed: {int(prisma_numbers['records_db']) + int(prisma_numbers['records_other']) - int(prisma_numbers['duplicates'])}
        - Records excluded during title/abstract screening: {prisma_numbers['excluded_screening']}
        - Full-text articles excluded with reasons: {prisma_numbers['excluded_fulltext']}
        - Studies included in qualitative synthesis: {prisma_numbers['included_studies']}
        """
        
        if prisma_numbers.get('included_meta') and prisma_numbers['included_meta'].strip():
            prisma_info += f"- Studies included in quantitative synthesis (meta-analysis): {prisma_numbers['included_meta']}\n"
            
        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}\n\n{prisma_info}"
        
        # 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=0.7 and top_p=1
        response = openai.ChatCompletion.create(
            model="gpt-4.1",
            messages=messages,
            temperature=0.7,
            top_p=1,
            max_tokens=16384
        )
        
        # Get the AI response
        review_content = response["choices"][0]["message"]["content"]
        
        # Generate PRISMA flow chart SVG
        prisma_svg = generate_prisma_flow_chart(
            int(prisma_numbers['records_db']),
            int(prisma_numbers['records_other']),
            int(prisma_numbers['duplicates']),
            int(prisma_numbers['excluded_screening']),
            int(prisma_numbers['excluded_fulltext']),
            int(prisma_numbers['included_studies']),
            int(prisma_numbers['included_meta']) if prisma_numbers.get('included_meta') and prisma_numbers['included_meta'].strip() else None
        )
        
        # Find a suitable place to insert the PRISMA flow chart
        # Look for the methodology section or PRISMA mentions
        prisma_html = f'''
        <div class="prisma-flow-chart">
            <h3>Figure 1: PRISMA Flow Diagram</h3>
            {prisma_svg}
        </div>
        '''
        
        # Try to insert PRISMA diagram after methodology section or before results
        if "<h2>3. Methodology" in review_content:
            parts = review_content.split("<h2>3. Methodology", 1)
            if len(parts) > 1:
                # Find the next h2 section after methodology
                next_section = parts[1].find("<h2>")
                if next_section > -1:
                    review_content = parts[0] + "<h2>3. Methodology" + parts[1][:next_section] + prisma_html + parts[1][next_section:]
                else:
                    review_content = parts[0] + "<h2>3. Methodology" + parts[1] + prisma_html
        else:
            # If methodology section not found, insert before results or at the end
            insert_pos = review_content.find("<h2>4.") if "<h2>4." in review_content else len(review_content) - 100
            review_content = review_content[:insert_pos] + prisma_html + review_content[insert_pos:]
        
        # Apply professional academic paper styling
        styled_html = f"""
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Systematic Review</title>
            <style>
                /* Academic Paper Styling */
                body {{
                    font-family: 'Times New Roman', Times, serif;
                    line-height: 1.6;
                    color: #333;
                    margin: 0;
                    padding: 0;
                    background-color: #f9f9f9;
                }}
                .paper-container {{
                    max-width: 800px;
                    margin: 0 auto;
                    padding: 40px;
                    background-color: white;
                    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
                }}
                header {{
                    text-align: center;
                    margin-bottom: 30px;
                    border-bottom: 1px solid #ddd;
                    padding-bottom: 20px;
                }}
                h1 {{
                    font-size: 24px;
                    margin: 0 0 15px;
                    font-weight: bold;
                }}
                .author-info {{
                    font-size: 14px;
                    margin-bottom: 15px;
                }}
                .abstract {{
                    font-style: italic;
                    margin: 20px 0;
                    padding: 15px;
                    background-color: #f8f8f8;
                    border-left: 3px solid #ccc;
                }}
                h2 {{
                    font-size: 18px;
                    margin: 30px 0 15px;
                    border-bottom: 1px solid #eee;
                    padding-bottom: 5px;
                }}
                h3 {{
                    font-size: 16px;
                    margin: 25px 0 10px;
                }}
                p {{
                    margin: 0 0 15px;
                    text-align: justify;
                }}
                .section {{
                    margin-bottom: 30px;
                }}
                table {{
                    width: 100%;
                    border-collapse: collapse;
                    margin: 20px 0;
                    font-size: 14px;
                }}
                table, th, td {{
                    border: 1px solid #ddd;
                }}
                th, td {{
                    padding: 10px;
                    text-align: left;
                }}
                th {{
                    background-color: #f2f2f2;
                }}
                tr:nth-child(even) {{
                    background-color: #f9f9f9;
                }}
                .citation {{
                    font-size: 14px;
                    color: #555;
                }}
                .reference-list {{
                    margin-top: 40px;
                    border-top: 1px solid #ddd;
                    padding-top: 20px;
                }}
                .reference-list h2 {{
                    margin-top: 0;
                }}
                .reference-item {{
                    margin-bottom: 10px;
                    padding-left: 25px;
                    text-indent: -25px;
                }}
                ul, ol {{
                    margin: 15px 0;
                    padding-left: 25px;
                }}
                li {{
                    margin-bottom: 5px;
                }}
                .figure {{
                    margin: 25px 0;
                    text-align: center;
                }}
                .figure img {{
                    max-width: 100%;
                }}
                .figure-caption {{
                    font-size: 14px;
                    color: #666;
                    margin-top: 10px;
                }}
                .footnote {{
                    font-size: 12px;
                    color: #777;
                }}
                .prisma-flow-chart {{
                    margin: 30px 0;
                    text-align: center;
                }}
                .prisma-flow-chart h3 {{
                    margin-bottom: 15px;
                }}
                @media print {{
                    body {{
                        background-color: white;
                    }}
                    .paper-container {{
                        box-shadow: none;
                        padding: 0;
                    }}
                }}
            </style>
        </head>
        <body>
            <div class="paper-container">
                {review_content}
            </div>
        </body>
        </html>
        """
        
        return styled_html
    
    except Exception as e:
        return f"""
        <div style="color: red; padding: 20px; border: 1px solid red; border-radius: 5px; background-color: #ffecec;">
            <h3>Error Generating Systematic Review</h3>
            <p>{str(e)}</p>
        </div>
        """

# 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

# Function to create a downloadable HTML file
def create_html_download_link(html_content):
    if not html_content or "<div style=\"color: red; padding: 20px;" in html_content or "Please upload at least one PDF file" in html_content:
        return None
    
    # Create timestamp for the filename
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"systematic_review_{timestamp}.html"
    
    # Encode the HTML content for download
    b64_html = base64.b64encode(html_content.encode()).decode()
    download_link = f'<a href="data:text/html;base64,{b64_html}" download="{filename}" class="download-button">Download HTML</a>'
    
    return download_link

# Add CSS styling for the Gradio interface
custom_css = """
<style>
    /* Main UI */
    .gradio-container {
        font-family: 'Arial', sans-serif;
        background-color: #f9f9f9;
    }
    
    /* Header */
    h1 {
        font-size: 28px;
        color: #333;
        margin-bottom: 20px;
        text-align: center;
        padding-bottom: 10px;
        border-bottom: 2px solid #4a00e0;
    }
    
    /* Primary Button */
    #generate_button {
        background: linear-gradient(135deg, #4a00e0 0%, #8e2de2 100%);
        color: white;
        font-weight: bold;
        padding: 10px 20px;
        border-radius: 5px;
        transition: all 0.3s ease;
    }
    #generate_button:hover {
        background: linear-gradient(135deg, #5b10f1 0%, #9f3ef3 100%);
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    
    /* API Key Button */
    #api_key_button {
        background: linear-gradient(135deg, #68d391 0%, #48bb78 100%);
        color: white;
        font-weight: bold;
        margin-top: 27px;
        padding: 10px 20px;
        border-radius: 5px;
        transition: all 0.3s ease;
    }
    #api_key_button:hover {
        background: linear-gradient(135deg, #38a169 0%, #68d391 100%);
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    
    /* Form Elements */
    .input-container {
        background-color: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        margin-bottom: 20px;
    }
    
    /* Labels */
    label {
        font-weight: 600;
        color: #555;
        margin-bottom: 8px;
    }
    
    /* Instructions Accordion */
    .accordion {
        background-color: white;
        border: 1px solid #e0e0e0;
        border-radius: 8px;
        margin-bottom: 20px;
    }
    
    /* Output Container */
    .output-container {
        background-color: white;
        padding: 15px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    }
    
    /* File Upload Area */
    .file-upload {
        border: 2px dashed #ccc;
        border-radius: 5px;
        padding: 20px;
        text-align: center;
        margin-bottom: 20px;
    }
    
    /* Download Button */
    .download-button {
        display: inline-block;
        background: linear-gradient(135deg, #4a00e0 0%, #8e2de2 100%);
        color: white;
        font-weight: bold;
        padding: 8px 16px;
        border-radius: 4px;
        text-decoration: none;
        margin-bottom: 10px;
        transition: all 0.3s ease;
    }
    .download-button:hover {
        background: linear-gradient(135deg, #5b10f1 0%, #9f3ef3 100%);
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    
    /* Download Container */
    #download-container {
        display: flex;
        justify-content: center;
        margin: 20px 0;
        padding: 15px;
        background-color: #f5f5f5;
        border-radius: 8px;
    }
    
    /* PRISMA Flow Chart Container */
    .prisma-section {
        background-color: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        margin-bottom: 20px;
    }
    
    .prisma-form {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 15px;
    }
    
    /* Responsive adjustments */
    @media screen and (max-width: 768px) {
        .gradio-container {
            padding: 10px;
        }
        .prisma-form {
            grid-template-columns: 1fr;
        }
    }
</style>
"""

# Gradio UI Layout with improved styling
with gr.Blocks(css=custom_css) as demo:
    gr.Markdown("# Systematic Review Generator with PRISMA Flow Chart")
    
    with gr.Accordion("How to Use This App", open=False):
        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. Fill in the PRISMA flow chart information (numbers at each stage of your review)
        5. Check the "Include Tables" option if you want the review to include comparison tables
        6. Click "Generate Systematic Review" to start the process
        7. After generation, you can download the review as HTML
        
        ### PRISMA Flow Chart:
        - The PRISMA (Preferred Reporting Items for Systematic Reviews and Meta-Analyses) flow diagram shows the flow of information through the different phases of your systematic review
        - Fill in the numbers for each stage to generate an accurate diagram
        - The diagram will be embedded in your systematic review
        
        ### 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
        - The review will be formatted as a professional academic paper with proper sections and citations
        """)
    
    # API Key Input in a styled container
    with gr.Row(elem_classes="input-container"):
        with gr.Column(scale=3):
            api_key_input = gr.Textbox(label="Enter OpenAI API Key", type="password", placeholder="sk-...")
        with gr.Column(scale=1):
            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(elem_classes="input-container"):
        with gr.Column():
            gr.Markdown("### Upload Research Papers")
            pdf_files = gr.File(label="Upload PDF Research Papers", file_count="multiple", type="binary", elem_classes="file-upload")
            review_question = gr.Textbox(
                label="Review Question or Topic", 
                value="Please generate a systematic review of the following papers.",
                placeholder="e.g., What are the effects of mindfulness meditation on stress reduction?"
            )
            include_tables = gr.Checkbox(label="Include Comparison Tables", value=True)
    
    # PRISMA Flow Chart inputs
    with gr.Row(elem_classes="prisma-section"):
        with gr.Column():
            gr.Markdown("### PRISMA Flow Chart Information")
            gr.Markdown("Enter the numbers for each stage of your systematic review process:")
            
            with gr.Row(elem_classes="prisma-form"):
                prisma_records_db = gr.Textbox(label="Records from database searching", value="100", placeholder="e.g., 100")
                prisma_records_other = gr.Textbox(label="Records from other sources", value="20", placeholder="e.g., 20")
                prisma_duplicates = gr.Textbox(label="Duplicates removed", value="15", placeholder="e.g., 15")
                prisma_excluded_screening = gr.Textbox(label="Records excluded at screening", value="60", placeholder="e.g., 60")
                prisma_excluded_fulltext = gr.Textbox(label="Full-text articles excluded", value="30", placeholder="e.g., 30")
                prisma_included_studies = gr.Textbox(label="Studies included in synthesis", value="15", placeholder="e.g., 15")
                prisma_included_meta = gr.Textbox(label="Studies in meta-analysis (optional)", value="10", placeholder="e.g., 10")
                
            generate_button = gr.Button("Generate Systematic Review", elem_id="generate_button", size="large")
    
    # Download link container
    download_html_output = gr.HTML(label="Download Options")
    
    # Output with improved styling
    with gr.Row(elem_classes="output-container"):
        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, 
                                           records_db, records_other, duplicates, 
                                           excluded_screening, excluded_fulltext, 
                                           included_studies, included_meta):
        if not files:
            return ("""
            <div style="padding: 20px; border: 1px solid #e0e0e0; border-radius: 5px; background-color: #f9f9f9;">
                <h3 style="color: #666;">Please upload at least one PDF file.</h3>
                <p>To generate a systematic review, upload one or more research papers in PDF format.</p>
            </div>
            """, "")
        
        # Save uploaded files
        saved_paths = save_uploaded_files(files)
        
        # Show loading message
        loading_message = """
        <div style="padding: 20px; text-align: center;">
            <h3>Generating Systematic Review with PRISMA Flow Chart...</h3>
            <p>This may take a few minutes depending on the number and size of papers.</p>
            <div style="width: 100%; height: 4px; background-color: #f0f0f0; margin: 20px 0; border-radius: 2px; overflow: hidden;">
                <div style="width: 30%; height: 100%; background: linear-gradient(90deg, #4a00e0, #8e2de2); animation: progress 2s infinite linear;"></div>
            </div>
            <style>
                @keyframes progress {
                    0% { margin-left: -30%; }
                    100% { margin-left: 100%; }
                }
            </style>
        </div>
        """
        
        yield loading_message, ""
        
        # Collect PRISMA flow chart data
        prisma_numbers = {
            'records_db': records_db,
            'records_other': records_other,
            'duplicates': duplicates,
            'excluded_screening': excluded_screening,
            'excluded_fulltext': excluded_fulltext,
            'included_studies': included_studies,
            'included_meta': included_meta
        }
        
        # Generate review with PRISMA flow chart
        review = generate_systematic_review(saved_paths, question, prisma_numbers, include_tables)
        
        # Create HTML download link
        html_link = create_html_download_link(review)
        
        # Create download link HTML
        download_link = f"""
        <div id="download-container">
            <div>
                <h3>Download Option:</h3>
                {html_link or ""}
            </div>
        </div>
        """
        
        # Clean up temporary files
        for path in saved_paths:
            try:
                os.remove(path)
            except:
                pass
        
        yield review, download_link
    
    generate_button.click(
        process_files_and_generate_review, 
        inputs=[pdf_files, review_question, include_tables, 
                prisma_records_db, prisma_records_other, prisma_duplicates, 
                prisma_excluded_screening, prisma_excluded_fulltext, 
                prisma_included_studies, prisma_included_meta], 
        outputs=[review_output, download_html_output]
    )

# Launch the app
if __name__ == "__main__":
    demo.launch(share=True)