Spaces:
Sleeping
Sleeping
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) |