File size: 27,915 Bytes
8cf2a7f
 
 
 
4558e9e
8cf2a7f
67b74d5
 
 
 
17fffbd
67b74d5
17fffbd
4558e9e
67b74d5
17fffbd
4558e9e
 
 
 
7db25c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4558e9e
 
 
 
 
 
67b74d5
4558e9e
 
 
 
 
 
 
 
 
67b74d5
4558e9e
67b74d5
 
17fffbd
67b74d5
17fffbd
67b74d5
 
 
17fffbd
 
 
 
 
 
 
67b74d5
17fffbd
67b74d5
 
17fffbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67b74d5
17fffbd
 
 
 
 
67b74d5
17fffbd
 
67b74d5
17fffbd
67b74d5
17fffbd
 
 
 
67b74d5
17fffbd
 
 
 
67b74d5
17fffbd
 
 
 
67b74d5
17fffbd
 
 
 
67b74d5
17fffbd
 
 
 
67b74d5
17fffbd
 
 
 
67b74d5
17fffbd
 
 
 
67b74d5
17fffbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67b74d5
 
17fffbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67b74d5
17fffbd
67b74d5
 
4558e9e
 
 
67b74d5
 
17fffbd
 
8cf2a7f
4558e9e
 
 
67b74d5
 
4558e9e
 
 
 
 
67b74d5
4558e9e
 
 
 
 
 
17fffbd
67b74d5
8cf2a7f
4558e9e
 
 
8cf2a7f
4558e9e
 
 
8cf2a7f
67b74d5
 
17fffbd
67b74d5
 
 
952e968
17fffbd
 
 
 
 
952e968
17fffbd
952e968
 
 
 
17fffbd
67b74d5
 
 
 
 
 
 
 
 
 
952e968
 
67b74d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
952e968
67b74d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4558e9e
 
747aa89
 
 
 
 
67b74d5
747aa89
 
 
 
67b74d5
747aa89
 
17fffbd
747aa89
17fffbd
8cf2a7f
17fffbd
 
 
 
8cf2a7f
17fffbd
 
747aa89
17fffbd
 
 
 
 
 
 
 
 
 
 
 
 
 
67b74d5
17fffbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747aa89
 
67b74d5
17fffbd
747aa89
 
17fffbd
8cf2a7f
17fffbd
747aa89
17fffbd
747aa89
 
 
17fffbd
747aa89
17fffbd
 
 
 
 
 
 
 
 
 
 
 
 
747aa89
17fffbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747aa89
 
17fffbd
747aa89
 
8cf2a7f
747aa89
 
 
 
 
 
 
 
 
 
17fffbd
747aa89
 
 
 
 
8cf2a7f
17fffbd
 
747aa89
17fffbd
 
 
 
747aa89
17fffbd
 
 
747aa89
17fffbd
 
 
747aa89
17fffbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747aa89
17fffbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747aa89
17fffbd
 
 
 
 
747aa89
17fffbd
 
 
 
 
 
 
 
 
 
 
 
747aa89
17fffbd
 
 
747aa89
17fffbd
 
747aa89
17fffbd
 
 
 
 
 
 
 
 
 
 
 
 
8cf2a7f
4558e9e
8cf2a7f
17fffbd
 
 
8cf2a7f
 
4558e9e
8cf2a7f
 
4558e9e
8cf2a7f
 
67b74d5
 
 
 
17fffbd
67b74d5
 
17fffbd
8cf2a7f
4558e9e
 
 
67b74d5
 
 
4558e9e
67b74d5
4558e9e
 
 
67b74d5
 
17fffbd
 
67b74d5
 
 
 
8cf2a7f
 
 
67b74d5
 
8cf2a7f
4558e9e
 
8cf2a7f
4558e9e
8cf2a7f
 
 
 
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
import os
import sys
import time
import gradio as gr
from openai import OpenAI
from pptx import Presentation
from pptx.util import Pt, Inches
from pptx.enum.text import PP_ALIGN
from pptx.dml.color import RGBColor
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
from reportlab.lib import colors
from dotenv import load_dotenv
import re
import textwrap

# Load environment variables
load_dotenv()

# Get API key from environment variable
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
if not OPENROUTER_API_KEY:
    raise ValueError("OPENROUTER_API_KEY environment variable is not set")

# OpenRouter API configuration
MODEL_NAME = "meta-llama/llama-3.3-8b-instruct:free"  # You can also use more powerful models like "anthropic/claude-3-opus-20240229"
SITE_URL = "https://requirements-generator.io"  # Replace with your actual site URL
SITE_NAME = "Technical Requirements Generator"  # Replace with your actual site name

# Process the input and generate everything
def process_input(description, project_type):
    """Process the input and generate both proposal, PDF and slides"""
    try:
        # Check if input is too short
        if len(description.strip()) < 10:
            return "Please provide a more detailed project description (at least 10 characters).", None, None
        
        # Map project type to specific type value
        type_value = None
        if project_type == "SaaS Performance Platform":
            type_value = "saas_performance"
        
        # Generate the proposal
        proposal = generate_proposal(description, type_value)
        
        # Create the PDF
        try:
            pdf_path = create_pdf(proposal)
        except Exception as pdf_error:
            print(f"Error creating PDF: {pdf_error}")
            pdf_path = None
        
        # Create the slides
        try:
            ppt_path = create_slides(proposal)
        except Exception as ppt_error:
            print(f"Error creating slides: {ppt_error}")
            ppt_path = None
        
        return proposal, pdf_path, ppt_path
    except Exception as e:
        error_message = f"An error occurred: {str(e)}\nPlease try again with a different project description."
        print(f"Error in process_input: {e}")
        return error_message, None, None

# Load environment variables
load_dotenv()

# Get API key from environment variable
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
if not OPENROUTER_API_KEY:
    raise ValueError("OPENROUTER_API_KEY environment variable is not set")

# OpenRouter API configuration
MODEL_NAME = "meta-llama/llama-3.3-8b-instruct:free"  # You can also use more powerful models like "anthropic/claude-3-opus-20240229"
SITE_URL = "https://proposal-generator.io"  # Replace with your actual site URL
SITE_NAME = "Professional Proposal Generator"  # Replace with your actual site name

# Initialize OpenAI client for OpenRouter
client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=OPENROUTER_API_KEY,
)

def generate_proposal(description, project_type=None):
    """Generate a proposal from a description using OpenRouter API"""
    
    # Create a better prompt with example formatting and detailed instructions
    system_prompt = """You are a professional technical documentation writer with expertise in creating detailed, well-structured requirements and proposal documents.
    
Your documents are comprehensive, highly detailed, and follow a clear structure with proper formatting. Each section should include substantial content with specific details, bullet points, and professional technical language.

Make sure to:
1. Include proper formatting with section headings in bold
2. Use bullet points (● symbol) for listing features and requirements
3. Organize content into logical sections and subsections
4. Provide concrete, specific technical details rather than generic statements
5. Maintain a professional, technical tone throughout
6. DO NOT include timelines, budgets, or pricing information
7. Format the document to look like a formal technical requirements document
8. Focus on functional requirements, technical specifications, and feature details

The document must be highly detailed, professionally formatted, and ready for presentation to technical stakeholders.
"""

    # For SaaS Performance Platform, use a specific template based on the provided document
    if project_type == "saas_performance":
        example_format = """**[Title based on description]**

**Introduction:**
A comprehensive explanation of the project goals, purpose, and overview in 2-3 paragraphs. Describe the key benefits and intended outcomes without mentioning timelines or budgets.

**Functional Requirements:**

**User Authentication and Role Management:**
● [Feature point 1]
● [Feature point 2]
● [Feature point 3]

**Dashboard and Analytics:**
● [Feature point 1]
● [Feature point 2]
● [Feature point 3]

**Evaluation Framework Builder:**
● [Feature point 1]
● [Feature point 2]
● [Feature point 3]

**Data Input and Rating Engine:**
● [Feature point 1]
● [Feature point 2]
● [Feature point 3]

**Progress Tracking Module:**
● [Feature point 1]
● [Feature point 2]
● [Feature point 3]

**Reporting and Exporting:**
● [Feature point 1]
● [Feature point 2]
● [Feature point 3]

**Notifications:**
● [Feature point 1]

**Permission and Access Management:**
● [Feature point 1]
● [Feature point 2]

**Audit Log and Activity Tracking:**
● [Feature point 1]
● [Feature point 2]

**Modules:**
● [Module 1]
● [Module 2]
● [Module 3]
● [Module 4]
● [Module 5]
● [Module 6]
● [Module 7]
● [Module 8]

**User Roles and Permissions:**

**[Role Type 1]:**
● [Permission 1]
● [Permission 2]

**[Role Type 2]:**
● [Permission 1]
● [Permission 2]
● [Permission 3]

**[Role Type 3]:**
● [Permission 1]
● [Permission 2]

**[Role Type 4]:**
● [Permission 1]
● [Permission 2]
● [Permission 3]

**Technology Stack:**
● [Technology Category 1]: [Specific technologies]
● [Technology Category 2]: [Specific technologies]
● [Technology Category 3]: [Specific technologies]
● [Technology Category 4]: [Specific technologies]
● [Technology Category 5]: [Specific technologies]
● [Technology Category 6]: [Specific technologies]
● [Technology Category 7]: [Specific technologies]
● [Technology Category 8]: [Specific technologies]
● [Technology Category 9]: [Specific technologies]
● [Technology Category 10]: [Specific technologies]

**Conclusion:**
A final summary of the proposed system and its benefits in 1-2 paragraphs. Emphasize how the solution will meet the needs described without mentioning timelines or costs."""
    else:
        # General format for other project types
        example_format = """**[Title based on description]**

**Introduction:**
A comprehensive explanation of the project goals, purpose, and overview in 2-3 paragraphs. Describe the key benefits and intended outcomes without mentioning timelines or budgets.

**Functional Requirements:**

**[Key Feature Area 1]:**
● [Feature point 1]
● [Feature point 2]
● [Feature point 3]

**[Key Feature Area 2]:**
● [Feature point 1]
● [Feature point 2]
● [Feature point 3]

**[Key Feature Area 3]:**
● [Feature point 1]
● [Feature point 2]
● [Feature point 3]

**[Key Feature Area 4]:**
● [Feature point 1]
● [Feature point 2]
● [Feature point 3]

**System Architecture:**
● [Architecture Component 1]
● [Architecture Component 2]
● [Architecture Component 3]

**Technical Specifications:**
● [Technical Requirement 1]
● [Technical Requirement 2]
● [Technical Requirement 3]

**Security Requirements:**
● [Security Feature 1]
● [Security Feature 2]
● [Security Feature 3]

**Integration Requirements:**
● [Integration Point 1]
● [Integration Point 2]
● [Integration Point 3]

**User Types and Permissions:**

**[User Type 1]:**
● [Permission 1]
● [Permission 2]

**[User Type 2]:**
● [Permission 1]
● [Permission 2]

**[User Type 3]:**
● [Permission 1]
● [Permission 2]

**Technology Stack:**
● [Technology Area 1]: [Specific technologies]
● [Technology Area 2]: [Specific technologies]
● [Technology Area 3]: [Specific technologies]
● [Technology Area 4]: [Specific technologies]

**Conclusion:**
A final summary of the proposed system and its benefits in 1-2 paragraphs. Emphasize how the solution will meet the needs described without mentioning timelines or costs."""

    # Create a project type specific instruction
    project_specific_prompt = ""
    if project_type == "saas_performance":
        project_specific_prompt = """
Format the document to precisely match the example provided. For this SaaS Performance Evaluation Platform:

1. DO NOT include any sections about budget, timeline, team structure, or pricing
2. Structure the document exactly like the provided example with these specific sections:
   - Introduction
   - Functional Requirements (with all subsections as shown)
   - User Roles and Permissions (with all user types)
   - Technology Stack
   - Conclusion
3. Use bullet points with the ● symbol for all feature lists
4. Include specific technical details about:
   - Multi-tenant architecture with role-based access control
   - User authentication and authorization
   - Dashboard and analytics features with visualization options
   - Evaluation framework capabilities
   - Data input methods and rating systems
   - Reporting and exporting functions
   - Specific technology recommendations
5. Maintain a formal, technical tone throughout the document
6. Format all section headings in bold with a colon, like: "**Section Name:**"
"""
    
    prompt = f"""Create a detailed technical requirements document based on the following description. Format it exactly like the example format provided, with bold section headings and proper structure.

{example_format}

Project Description: {description}

{project_specific_prompt}

Create a complete, professionally formatted technical requirements document that resembles a formal functional specification. DO NOT include any sections about budget, timeline, team structure, or pricing. Focus entirely on functional and technical requirements.
"""

    try:
        completion = client.chat.completions.create(
            extra_headers={
                "HTTP-Referer": SITE_URL,
                "X-Title": SITE_NAME,
            },
            model=MODEL_NAME,
            messages=[
                {
                    "role": "system",
                    "content": system_prompt
                },
                {
                    "role": "user",
                    "content": prompt
                }
            ],
            temperature=0.4,  # Lower temperature for more consistent, formal results
            max_tokens=4500
        )
        
        proposal = completion.choices[0].message.content
        return proposal
    
    except Exception as e:
        print(f"Error generating proposal: {e}")
        return f"Error generating proposal: {e}"

def extract_title(proposal):
    """Extract the title from the proposal"""
    # Try to match the exact format first - standard format
    title_match = re.search(r"\*\*Project Proposal: (.*?)\*\*", proposal)
    if title_match:
        return title_match.group(1)
    
    # Try to match the requirements document format - just the title
    title_match = re.search(r"\*\*(.*?)\*\*", proposal)
    if title_match:
        return title_match.group(1)
    
    # Fallback pattern for more flexibility
    title_match = re.search(r"\*\*\s*(?:Project Proposal|Proposal|Title|Requirements Document):\s*(.*?)\s*\*\*", proposal, re.IGNORECASE)
    if title_match:
        return title_match.group(1)
    
    # If no title found, use a generic one
    return "Requirements Document"

def create_pdf(proposal, output_path="proposal.pdf"):
    """Create a PDF document from the proposal"""
    doc = SimpleDocTemplate(output_path, pagesize=letter,
                            rightMargin=72, leftMargin=72,
                            topMargin=72, bottomMargin=72)
    
    styles = getSampleStyleSheet()
    
    # Create custom styles
    # Use a different name to avoid collision with existing styles
    styles.add(ParagraphStyle(name='ProposalTitle',
                              parent=styles['Heading1'],
                              fontSize=16,
                              alignment=TA_CENTER,
                              spaceAfter=20))
    
    styles.add(ParagraphStyle(name='SectionHeading',
                              parent=styles['Heading2'],
                              fontSize=14,
                              spaceAfter=12,
                              spaceBefore=20))
    
    styles.add(ParagraphStyle(name='Normal',
                              parent=styles['Normal'],
                              fontSize=10,
                              alignment=TA_JUSTIFY,
                              spaceAfter=10))
    
    # Extract title
    title = extract_title(proposal)
    
    # Process the proposal content
    story = []
    
    # Add title
    story.append(Paragraph(f"<b>Project Proposal: {title}</b>", styles['ProposalTitle']))
    story.append(Spacer(1, 0.25*inch))
    
    # Process sections
    sections = re.split(r'\*\*\d+\.\s+(.*?)\*\*', proposal)
    headers = re.findall(r'\*\*\d+\.\s+(.*?)\*\*', proposal)
    
    # The first element in sections is the title area, skip it
    for i, content in enumerate(sections[1:], 0):
        if i < len(headers):
            # Add section header
            story.append(Paragraph(f"<b>{i+1}. {headers[i]}</b>", styles['SectionHeading']))
            
            # Process content paragraphs
            paragraphs = content.strip().split('\n\n')
            for para in paragraphs:
                para = para.strip()
                if not para:
                    continue
                
                # Check if it's a bullet point list
                if re.match(r'^[\*\-]', para):
                    # Process bullet points
                    bullet_items = re.split(r'\n[\*\-]\s+', para)
                    for item in bullet_items:
                        item = item.strip()
                        if item:
                            # Remove leading bullet if present
                            item = re.sub(r'^[\*\-]\s+', '', item)
                            story.append(Paragraph(f"• {item}", styles['Normal']))
                else:
                    # Regular paragraph
                    story.append(Paragraph(para, styles['Normal']))
    
    # Build the PDF
    doc.build(story)
    return output_path

def create_slides(proposal):
    """Create PowerPoint slides from the proposal"""
    try:
        prs = Presentation()
        
        # Extract title
        title = extract_title(proposal)
        
        # Set up slide layouts
        title_slide_layout = prs.slide_layouts[0]
        section_title_layout = prs.slide_layouts[2]
        content_layout = prs.slide_layouts[1]
        
        # Add title slide
        title_slide = prs.slides.add_slide(title_slide_layout)
        title_slide.shapes.title.text = title
        subtitle = title_slide.placeholders[1]
        subtitle.text = "Requirements Document"
        
        # Parse the document into sections
        sections = []
        current_section = None
        current_content = []
        
        # Split into paragraphs
        paragraphs = proposal.split('\n\n')
        
        for para in paragraphs:
            para = para.strip()
            if not para:
                continue
                
            # Check if it's a main section header
            if para.startswith('**') and para.endswith('**'):
                # Save previous section if exists
                if current_section and current_content:
                    sections.append((current_section, current_content))
                
                # Start new section
                current_section = para.replace('**', '')
                current_content = []
            
            # Check if it's a subsection header
            elif para.startswith('**') and '**:' in para:
                parts = para.split('**:', 1)
                if len(parts) == 2:
                    # Add as subsection with special formatting
                    header = parts[0].replace('**', '') + ':'
                    content = parts[1].strip()
                    current_content.append(("subsection", header, content if content else []))
            
            # Regular content or bullet points
            else:
                current_content.append(("content", para))
        
        # Add the last section
        if current_section and current_content:
            sections.append((current_section, current_content))
        
        # Create slides for each section
        for section_title, contents in sections:
            # Skip the first section if it's the title
            if section_title.lower() == title.lower():
                continue
                
            # Section title slide
            section_slide = prs.slides.add_slide(section_title_layout)
            section_slide.shapes.title.text = section_title
            
            # Content slides
            current_slide = None
            text_frame = None
            items_on_slide = 0
            
            for content_type, *content_data in contents:
                # Start a new slide if needed
                if current_slide is None or items_on_slide >= 6:
                    current_slide = prs.slides.add_slide(content_layout)
                    current_slide.shapes.title.text = section_title
                    text_frame = current_slide.placeholders[1].text_frame
                    items_on_slide = 0
                
                if content_type == "subsection":
                    # Add subsection header
                    subsection_header, subsection_content = content_data
                    p = text_frame.add_paragraph()
                    p.text = subsection_header
                    p.font.bold = True
                    items_on_slide += 1
                    
                    # Add subsection content if any
                    if subsection_content and isinstance(subsection_content, str):
                        p = text_frame.add_paragraph()
                        p.text = subsection_content
                        items_on_slide += 1
                
                elif content_type == "content":
                    para_text = content_data[0]
                    
                    # Check if it's a bullet list
                    if para_text.startswith('●'):
                        lines = para_text.split('\n')
                        for line in lines:
                            if line.strip():
                                p = text_frame.add_paragraph()
                                p.text = line.strip().replace('●', '').strip()
                                p.level = 1
                                items_on_slide += 1
                    else:
                        p = text_frame.add_paragraph()
                        p.text = para_text
                        items_on_slide += 1
        
        # Save the presentation
        output_path = "requirements_slides.pptx"
        prs.save(output_path)
        return output_path
    
    except Exception as e:
        print(f"Error creating PowerPoint: {e}")
        # Create a simple error presentation
        try:
            prs = Presentation()
            slide = prs.slides.add_slide(prs.slide_layouts[0])
            slide.shapes.title.text = "Error Creating Presentation"
            subtitle = slide.placeholders[1]
            subtitle.text = f"An error occurred: {str(e)}\nPlease try again with a different project description."
            
            output_path = "requirements_slides.pptx"
            prs.save(output_path)
        except:
            # If even the error presentation fails, return a default path
            pass
        return output_path

def create_pdf(proposal, output_path="requirements_document.pdf"):
    """Create a PDF document from the proposal"""
    try:
        from reportlab.lib.pagesizes import letter
        from reportlab.pdfgen import canvas
        from reportlab.lib.units import inch
        from reportlab.lib import colors
        
        # Basic PDF generation using canvas directly
        c = canvas.Canvas(output_path, pagesize=letter)
        width, height = letter
        
        # Add a header with company info (similar to the example)
        c.setFont("Helvetica", 10)
        c.drawString(1*inch, height-0.5*inch, "Generated Requirements Document")
        
        # Title
        title = extract_title(proposal)
        c.setFont("Helvetica-Bold", 14)
        c.drawCentredString(width/2, height-1.2*inch, title)
        
        # Simple text rendering
        c.setFont("Helvetica", 10)
        y = height - 1.5*inch
        line_height = 14
        
        # Process by paragraphs to handle sections better
        paragraphs = proposal.split('\n\n')
        
        for paragraph in paragraphs:
            paragraph = paragraph.strip()
            if not paragraph:
                continue
                
            # Check for page break
            if y < 1*inch:
                c.showPage()
                # Add header to new page
                c.setFont("Helvetica", 10)
                c.drawString(1*inch, height-0.5*inch, "Generated Requirements Document")
                y = height - 1*inch
            
            # Check if it's a section header (starts with **)
            if paragraph.startswith('**') and paragraph.endswith('**'):
                c.setFont("Helvetica-Bold", 12)
                # Remove ** markers
                paragraph = paragraph.replace('**', '')
                c.drawString(1*inch, y, paragraph)
                y -= line_height * 1.5
            # Check if it's a subsection header (starts with ** but has more text)
            elif paragraph.startswith('**') and '**:' in paragraph:
                parts = paragraph.split('**:', 1)
                if len(parts) == 2:
                    header = parts[0].replace('**', '') + ':'
                    c.setFont("Helvetica-Bold", 11)
                    c.drawString(1*inch, y, header)
                    y -= line_height * 1.2
                    
                    # If there's content after the header
                    content = parts[1].strip()
                    if content:
                        c.setFont("Helvetica", 10)
                        # Need to wrap this text
                        text_object = c.beginText(1.2*inch, y)
                        for line in textwrap.wrap(content, width=70):
                            text_object.textLine(line)
                            y -= line_height
                        c.drawText(text_object)
                        y -= line_height * 0.5
            # Check if it's a bullet point
            elif paragraph.startswith('●'):
                c.setFont("Helvetica", 10)
                # Draw the bullet
                c.drawString(1.2*inch, y, '●')
                
                # Draw the text after the bullet with indentation
                text = paragraph[1:].strip()
                text_object = c.beginText(1.5*inch, y)
                for line in textwrap.wrap(text, width=60):
                    text_object.textLine(line)
                    y -= line_height
                c.drawText(text_object)
                y -= line_height * 0.3
            else:
                # Regular paragraph
                c.setFont("Helvetica", 10)
                # Need to wrap this text
                text_object = c.beginText(1*inch, y)
                for line in textwrap.wrap(paragraph, width=70):
                    text_object.textLine(line)
                    y -= line_height
                c.drawText(text_object)
                y -= line_height * 0.5
        
        # Add a footer with page number
        c.setFont("Helvetica", 8)
        c.drawCentredString(width/2, 0.5*inch, "Page 1")
        
        c.save()
        return output_path
    except Exception as e:
        print(f"Error creating PDF: {e}")
        # Create an even simpler emergency PDF
        try:
            c = canvas.Canvas(output_path, pagesize=letter)
            width, height = letter
            c.setFont("Helvetica-Bold", 14)
            c.drawString(1*inch, height-1*inch, "Requirements Document")
            c.setFont("Helvetica", 10)
            c.drawString(1*inch, height-1.5*inch, "Error formatting document. Please see text version.")
            c.save()
        except Exception as inner_e:
            print(f"Error creating emergency PDF: {inner_e}")
        return output_path

# Create Gradio interface
def create_interface():
    with gr.Blocks(title="Requirements Document Generator") as app:
        gr.Markdown("# Technical Requirements Document Generator")
        gr.Markdown("Generate comprehensive, professionally formatted technical requirements documents with PDF and PowerPoint exports.")
        
        with gr.Row():
            with gr.Column(scale=1):
                description_input = gr.Textbox(
                    label="Project Description",
                    placeholder="Describe your project in detail...",
                    lines=10
                )
                
                project_type = gr.Dropdown(
                    label="Project Type",
                    choices=["General Project", "SaaS Performance Platform"],
                    value="SaaS Performance Platform"
                )
                
                generate_button = gr.Button("Generate Requirements Document", variant="primary")
                
                # Examples
                examples = gr.Examples(
                    examples=[
                        ["Develop a cloud-based SaaS platform for performance evaluation in educational institutions and corporate environments. The platform will enable users to track, evaluate, and report on individual performance metrics with customizable evaluation models.", "SaaS Performance Platform"],
                        ["Create a mobile application for sustainable waste management and recycling in urban communities. The app will connect residents with local recycling centers and provide educational resources on waste reduction.", "General Project"],
                        ["Design and implement a smart agriculture system using IoT sensors for small-scale farms. The system will monitor soil conditions, weather patterns, and crop health to optimize irrigation and fertilization.", "General Project"]
                    ],
                    inputs=[description_input, project_type]
                )
            
            with gr.Column(scale=2):
                output_tabs = gr.Tabs()
                with output_tabs:
                    with gr.TabItem("Document Text"):
                        proposal_output = gr.Textbox(label="Generated Document", lines=25)
                    with gr.TabItem("Documents"):
                        with gr.Row():
                            pdf_output = gr.File(label="PDF Document")
                            slides_output = gr.File(label="PowerPoint Slides")
        
        generate_button.click(
            process_input,
            inputs=[description_input, project_type],
            outputs=[proposal_output, pdf_output, slides_output]
        )
        
        return app

# Main script code
if __name__ == "__main__":
    print("Starting Gradio interface...")
    app = create_interface()
    app.launch(share=True)