SoDa12321's picture
Update app.py
7565af9 verified
import streamlit as st
from docx import Document
import re
import io
import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from email.mime.text import MIMEText
from fpdf import FPDF
from dotenv import load_dotenv
from retrying import retry
from functions import *
from sumerize import count_tokens, summarize_content,create_extraction_prompt,generate_data_from_docx
import streamlit_ext as ste
from exa_py import Exa
from groq import Groq
import httpx
import tiktoken
# Load environment variables
load_dotenv()
# Initialize APIs
exa = Exa(api_key=os.getenv("EXA_API_KEY"))
#client = Groq(api_key=os.getenv("GROQ_API_KEY"))
utilized_model = "llama3-70b-8192"
token_limit = 6000
model_name = "gpt-3.5-turbo"
# Initialize the tokenizer for the GPT model
#tokenizer = tiktoken.encoding_for_model("meta-llama/Meta-Llama-3-8B")
try:
# Use a custom HTTP client
http_client = httpx.Client()
client = Groq(api_key=os.getenv("GROQ_API_KEY"), http_client=http_client)
print("Groq client initialized successfully!")
except TypeError as e:
print("Error initializing Groq client:", str(e))
except Exception as ex:
print("Unexpected error:", str(ex))
highlights_options = {
"num_sentences": 7,
"highlights_per_url": 1,
}
@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000, stop_max_attempt_number=5)
def call_llm(prompt):
"""Send the prompt to the LLM and return the response."""
search_response = exa.search_and_contents(query=prompt, highlights=highlights_options, num_results=3, use_autoprompt=True)
info = [sr.highlights[0] for sr in search_response.results]
system_prompt = "You are a business proposal assistant. Generate detailed and precise responses to the user's query."
user_prompt = f"Sources: {info}\nQuestion: {prompt}"
completion = client.chat.completions.create(
model=utilized_model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
]
)
return completion.choices[0].message.content
def strip_md(text):
text = text.replace("**", "").replace("*", "").replace("#", "")
return re.sub(r'([!*_=~-])', r'\\\1', text)
def create_document():
doc = Document()
doc.add_heading("Business Proposal", 0)
return doc
def add_section_to_doc(doc, section_name, section_content):
section_content = strip_md(section_content)
section_content = section_content.replace("\\", "") # Remove backslashes
doc.add_heading(section_name, level=1)
doc.add_paragraph(section_content)
return doc
def get_docx_bytes(doc):
doc_io = io.BytesIO()
doc.save(doc_io)
doc_io.seek(0)
return doc_io
def send_email_with_attachment(to_email, subject, body, filename, section_content):
from_email = os.getenv("EMAIL_USER")
email_password = os.getenv("EMAIL_PASSWORD")
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = subject
# Attach the body of the email
msg.attach(MIMEText(body + f"\n\nContent of the section:\n\n{section_content}", 'plain'))
# Attach the DOCX file
try:
with open(filename, 'rb') as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename={filename}')
msg.attach(part)
# Send the email
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login(from_email, email_password)
server.send_message(msg)
# Return success message
return f"Email sent successfully to {to_email} for section '{subject}'."
except Exception as e:
# Return error message
return f"Failed to send email to {to_email}: {str(e)}"
# Send the email
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login(from_email, email_password)
server.send_message(msg)
def sanitize_filename(filename, max_length=100):
"""
Remove or replace invalid characters from the filename to make it valid for file systems,
and limit the filename length to avoid file system errors.
"""
# Remove invalid characters
sanitized = re.sub(r'[<>:"/\\|?*]', '', filename)
# Ensure the filename is within the max_length
return sanitized[:max_length]
def get_docx_bytes(doc):
"""Convert a DOCX Document to bytes for download."""
doc_io = io.BytesIO()
doc.save(doc_io)
doc_io.seek(0)
return doc_io
def process_uploaded_docx(file):
"""Extract text content from an uploaded DOCX file."""
doc = Document(file)
content = "\n".join([p.text for p in doc.paragraphs if p.text.strip()])
return content
import re
from docx import Document
def generate_17_quest_responses(content, data):
"""Generate a new document with responses to 17 questions based on the given text content and data."""
# Create a new DOCX document
# Initialize responses dictionary
responses = {}
doc_bytes = io.BytesIO() # Initialize document bytes
doc = Document()
doc.add_heading("Responses to Business Plan Questions", 0)
# Define questions in a list
questions_0 = [
("Question 1", f"Describe the business idea for {data['company_name']} operating in the {data['industry']} industry. Include its purpose, unique features, and goals."),
("Question 2", f"What customer need does {data['company_name']} address? Explain the target market and specific client needs being met."),
("Question 3", f"Provide a detailed description of the solution {data['company_name']} offers. How does it address customer needs and fulfill the company's vision?"),
("Question 4", f"Describe the business model and pricing strategy for {data['company_name']}. Include details about paying customers, end users, and monetization methods."),
("Question 5", f"Generate a go-to-market plan for {data['company_name']}. Include the target market areas, customer segments, and strategies for distribution and promotion."),
("Question 6", f"Explain the benefits that {data['company_name']} provides to its clients. Quantify these benefits and describe how they address pain points."),
("Question 7", f"What are the alternative approaches available for the problem that {data['company_name']} solves? Highlight gaps in those approaches."),
("Question 8", f"Who are the main competitors of {data['company_name']} in the {data['industry']} industry? Provide a brief analysis of their market presence."),
("Question 9", f"Describe the competitive advantages of {data['company_name']} over its competitors. Focus on innovation, scalability, and differentiation."),
("Question 10", f"Outline the team plan for {data['company_name']}. Include key roles, responsibilities, and ownership structure."),
("Question 11", f"Summarize what you have done so far for {data['company_name']}. Mention prototypes, demos, IPs, and customer contacts established so far: {data['current_status']}."),
("Question 12", f"Has {data['company_name']} already been established? Provide details including the name, location, and legal structure: {data['existing_company_details']}."),
("Question 13", f"Has {data['company_name']} participated in any accelerator or incubator programs? Provide details about the programs: {data['accelerator_participation']}."),
("Question 14", f"Do you have any contacts in Finland for {data['company_name']}, if any: {data['finland_contacts']}. If there are no contacts, explain why Finland is attractive: {data['reason_for_finland']}."),
("Question 15", f"What is your plan for the first 12 months of operation for {data['company_name']}? Include tasks, milestones, and expected outcomes: {data['first_year_plan']}."),
("Question 16", f"What is your plan to fund the initial phase of your company? Provide an estimated need for funding and how you plan to secure it: {data['funding_plan']}."),
("Question 17", f"Provide any additional information relevant to {data['company_name']} or its business plan: {data['additional_information']}.")
]
questions = [
("Question 1: Describe your business idea shortly.",
f"Describe the business idea for {data['company_name']} operating in the {data['industry']} industry. Include its purpose, unique features, and goals."),
("Question 2: What is a customer need you plan to satisfy?",
f"What customer need does {data['company_name']} address? Explain the target market and specific client needs being met."),
("Question 3: What is your compelling solution to the specific customer need?",
f"Provide a detailed description of the solution {data['company_name']} offers. How does it address customer needs and fulfill the company's vision?"),
("Question 4: What is your business model and an initial idea of pricing?",
f"Describe the business model and pricing strategy for {data['company_name']}. Include details about paying customers, end users, and monetization methods."),
("Question 5: What is your go-to-market plan?",
f"Generate a go-to-market plan for {data['company_name']}. Include the target market areas, customer segments, and strategies for distribution and promotion."),
("Question 6: What are the benefits that your approach provides to your clients?",
f"Explain the benefits that {data['company_name']} provides to its clients. Quantify these benefits and describe how they address pain points."),
("Question 7: What are the alternative approaches available for the problem that you solve?",
f"What are the alternative approaches available for the problem that {data['company_name']} solves? Highlight gaps in those approaches."),
("Question 8: Who are the main competitors?",
f"Who are the main competitors of {data['company_name']} in the {data['industry']} industry? Provide a brief analysis of their market presence."),
("Question 9: What are your solution’s competitive advantages?",
f"Describe the competitive advantages of {data['company_name']} over its competitors. Focus on innovation, scalability, and differentiation."),
("Question 10: Describe your team plan.",
f"Outline the team plan for {data['company_name']}. Include key roles, responsibilities, and ownership structure."),
("Question 11: Describe what you have done so far.",
f"Summarize what you have done so far for {data['company_name']}. Mention prototypes, demos, IPs, and customer contacts established so far: {data['current_status']}."),
("Question 12: Have you already established a company working on this business idea?",
f"Has {data['company_name']} already been established? Provide details including the name, location, and legal structure: {data['existing_company_details']}."),
("Question 13: Have you participated in any accelerator/incubator programs?",
f"Has {data['company_name']} participated in any accelerator or incubator programs? Provide details about the programs: {data['accelerator_participation']}."),
("Question 14: Do you have contacts in Finland?",
f"Do you have any contacts in Finland for {data['company_name']}, if any: {data['finland_contacts']}. If there are no contacts, explain why Finland is attractive: {data['reason_for_finland']}."),
("Question 15: What is your plan for the first 12 months of operation?",
f"What is your plan for the first 12 months of operation for {data['company_name']}? Include tasks, milestones, and expected outcomes: {data['first_year_plan']}."),
("Question 16: What is your plan to fund the initial phase of your company?",
f"What is your plan to fund the initial phase of your company? Provide an estimated need for funding and how you plan to secure it: {data['funding_plan']}."),
("Question 17: Additional information for the application.",
f"Provide any additional information relevant to {data['company_name']} or its business plan: {data['additional_information']}.")
]
# Process each question separately
for question_title, prompt in questions:
# Tokenize
#content_tokens = count_tokens(content,model_name) #tiktoken.get_encoding(content)
#if content_tokens > token_limit :
# content = summarize_content(content, token_limit-150)
content = summarize_content(content, token_limit-150)
# Call LLM with current question prompt
response = call_llm(f"{prompt}\n\nFor the following content:\n\n{content}\n\n")
# Add each question and its response to the document
doc.add_heading(question_title, level=1)
doc.add_paragraph(response)
# Display results in Streamlit
st.subheader(question_title)
st.write(response)
responses[question_title] = response
#st.write(f"changed this line\n responses variable is :( {responses}")
doc_bytes = get_docx_bytes(doc)
#st.write(f"doc_bytes value is :{doc_bytes.getvalue()}")
return responses,doc,doc_bytes
def generate_new_business_plan(data):
"""Generate a new business plan using the input data."""
doc = Document()
doc.add_heading("Business Proposal", 0)
sections_to_process_0 = {
"Executive Summary": generate_executive_summary(data),
"Mission Statement": generate_mission(data),
"Vision Statement": generate_vision(data),
"Objectives": generate_objectives(data),
"Core Values": generate_core_values(data),
"Business Description": generate_business_description(data),
"Market Overview": analyze_demand(data),
"Marketing Strategy": generate_marketing_mix(data),
"Promotional Strategy": generate_promotional_strategy(data),
"Financial Overview": generate_funding_request(data),
}
# Process and update document with each section
sections_to_process = [
("Executive Summary", generate_executive_summary),
("Mission Statement", generate_mission),
("Vision Statement", generate_vision),
("Objectives", generate_objectives),
("Core Values", generate_core_values),
("Business Description Analysis", generate_business_description),
("Company Location", generate_company_location),
("Products", generate_products),
("Ownership", generate_ownership),
("Company Structure", generate_company_structure),
("Management Profiles", generate_management_profiles),
("Operational Strategy", generate_operational_strategy),
("Marketing Mix Strategy", generate_marketing_mix),
("Promotional Strategy", generate_promotional_strategy),
("Market Demand Analysis", analyze_demand),
("Market Segment Analysis", segment_market),
("Competitor Analysis", analyze_competitors),
("Porter's Five Forces Analysis", perform_porters_five_forces),
("Industry Analysis", analyze_industry_accommodation),
("Major Player Analysis", list_major_players),
("Business Sub Sector Analysis", analyze_business_sub_sector),
("SWOT Analysis", generate_swot_analysis),
("Funding Request", generate_funding_request),
("Financing & Bank Loan Amortization", create_financing_plan),
("Income Statement Analysis", generate_pro_forma_income_statement),
("Revenue Expense Analysis", predict_revenue_expenses),
("Montly Cash Flow Analysis", generate_monthly_cash_flow),
("Pro Forma Annual Cash Flow Analysis", generate_pro_forma_annual_cash_flow),
("Pro Forma Balance Sheet Analysis", generate_pro_forma_balance_sheet),
("Break-Even Analysis", perform_break_even_analysis),
("Payback Period Analysis", calculate_payback_period),
("Financial Graphs Analysis", generate_financial_graphs),
("Risk Mitigations Analysis", identify_risks_mitigations)
]
# Sanitize the company name to be used in file names
if True:
sanitized_company_name = sanitize_filename(company_name,max_length=50)
#sanitized_section_name = sanitize_filename(section_name, max_length=50)
# Generate final file name and ensure it is not too long
filename = f"Bussiness_Plan_for _{sanitized_company_name}.docx"
# Create a new document
doc = create_document() #f"{sanitized_company_name}_{sanitized_section_name}")
for section_name, generate_prompt_func in sections_to_process:
prompt = generate_prompt_func(data)
section_content = call_llm(prompt)
st.subheader(section_name)
st.write(section_content)
# Update document and create download link
doc = add_section_to_doc(doc, section_name, section_content)
doc_bytes = get_docx_bytes(doc)
st.download_button(
label=f"Download {section_name} as DOCX",
data=doc_bytes,
file_name=f"{section_name.replace(' ', '_').lower()}.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
# Save section content in a file
#filename = f"{company_name}_{section_name}.docx"
# Sanitize section name and limit file name length
sanitized_section_name = sanitize_filename(section_name, max_length=50)
# Generate final file name and ensure it is not too long
filename = f"{sanitized_company_name}_{sanitized_section_name}.docx"
with open(filename, 'wb') as f:
f.write(doc_bytes.getbuffer())
# Send email with section content and attachment
#send_email_with_attachment(email, f"{section_name} of Your Business Proposal", "Please find attached the section of your business proposal.", filename, section_content)
return doc_bytes,filename
def File_to_17_question_Answer_1_1_(uploaded_file, data):
content = process_uploaded_docx(uploaded_file)
st.write(f"File content loaded successfully.")
responses = {}
doc_bytes = io.BytesIO() # Initialize document bytes
# Display extracted data
for key, value in data.items():
if value:
st.write(f"{key}: {value}")
else:
st.write(f"{key}: Not found in the document")
if st.button("Generate Responses for 17 Questions"):
responses, doc_bytes = generate_17_quest_responses(content, data)
# Create a new Document object from doc_bytes
response_doc = Document()
response_doc.add_heading("Responses to 17 Questions", 0)
st.header("File_to_17_question_Answer(uploaded_file results")
st.write(f"doc_bytes value is :{doc_bytes.getvalue()}") # Changed this line
# Add paragraphs to the new Document object
for question, answer in responses.items():
response_doc.add_heading(question, level=1)
response_doc.add_paragraph(answer)
doc_bytes = get_docx_bytes(response_doc) # Update doc_bytes with the new content
ste.download_button(
label="Download Responses as DOCX",
data=doc_bytes,
file_name="Responses_to_17_Questions.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
st.header("File_to_17_question_Answer(uploaded_file results")
st.write(f"Responses value is :{responses}\n and doc_bytes.getvalue() is :{doc_bytes.getvalue()} ")
return responses, doc_bytes.getvalue() # Return doc_bytes.getvalue() instead of doc_bytes
def File_to_17_question_Answer(uploaded_file, data):
content = process_uploaded_docx(uploaded_file)
st.write(f"File content loaded successfully.")
responses = {}
doc_res = Document()
#doc_bytes = io.BytesIO() # Initialize document bytes
# Display extracted data
for key, value in data.items():
if value:
st.write(f"{key}: {value}")
else:
st.write(f"{key}: Not found in the document")
if st.button("Generate Responses for 17 Questions"):
responses,doc_res,doc_bytes = generate_17_quest_responses(content, data)
# Create response document
response_doc = Document()
response_doc.add_heading("Responses to 17 Questions", 0)
st.header("File_to_17_question_Answer(uploaded_file results")
st.write(f"doc_res value is :{doc_res}\n and response_doc is :{response_doc} ")
#for question, answer in doc_res.items():
# response_doc.add_heading(question, level=1)
# response_doc.add_paragraph(answer)
#doc_bytes = get_docx_bytes(doc_res)
st.download_button(
label="Download Responses as DOCX",
data=doc_bytes,
file_name="Responses_to_17_Questions.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
#st.header("File_to_17_question_Answer(uploaded_file results")
#st.write(f"Responses value is :{responses}\n and doc_bytes.getvalue() is :{doc_bytes.getvalue()} ")
return responses,doc_res,doc_bytes
def File_to_17_question_Answer_0(filename, data):
"""Process the uploaded file and data and return responses and document bytes."""
content = process_uploaded_docx(uploaded_file)
st.write(f"File content loaded successfully.")
# Display extracted data
responses = {} # Initialize responses
doc_bytes = io.BytesIO() # Initialize document bytes
try:
# Your processing logic here
# Simulate processing logic...
processed_doc = Document()
processed_doc.add_heading("Responses to 17 Questions", 0)
for key, value in data.items():
processed_doc.add_paragraph(f"{key}: {value}")
# Save to bytes
processed_doc.save(doc_bytes)
# Return both responses and document bytes
return responses, doc_bytes.getvalue()
except Exception as e:
st.error(f"An error occurred while processing: {str(e)}")
return {}, None # Return empty responses and None for doc_bytes
def collect_basic_info():
st.title("Business Proposal Generator")
# Basic Company Information
company_name = st.text_input("Company Name")
industry = st.text_input("Industry")
location = st.text_input("Location")
mission = st.text_area("Mission Statement")
vision = st.text_area("Vision Statement")
products_services = st.text_area("Description of Products/Services")
target_market = st.text_area("Customer Segments")
value_proposition = st.text_area("Competitive Advantage")
promotional_strategy = st.text_area("Promotional Strategy")
current_revenue = st.number_input("Current Revenue (R)", min_value=0.0, format="%f")
current_expenses = st.number_input("Current Expenses (R)", min_value=0.0, format="%f")
funding_requirements = st.text_area("Funding Requirements")
management_team = st.text_area("Key Personnel")
company_structure = st.text_area("Company Structure")
goals_objectives = st.text_area("Short-term and Long-term Goals")
operational_strategy = st.text_area("Operational Strategy")
market_overview = st.text_area("Market Overview")
# Add your contact information
st.write("## Contact Information")
email = st.text_input("Email")
whatsapp_number = st.text_input("WhatsApp Number")
if st.button('Submit'):
# Collect data
data = {
"company_name": company_name,
"industry": industry,
"location": location,
"mission": mission,
"vision": vision,
"products_services": products_services,
"target_market": target_market,
"value_proposition": value_proposition,
"current_revenue": current_revenue,
"current_expenses": current_expenses,
"funding_requirements": funding_requirements,
"management_team": management_team,
"company_structure": company_structure,
"goals_objectives": goals_objectives,
"operational_strategy": operational_strategy,
"market_overview": market_overview,
"promotional_strategy": promotional_strategy,
"email": email,
"whatsapp_number": whatsapp_number
}
# Process and update document with each section
sections_to_process = [
("Executive Summary", generate_executive_summary),
("Mission Statement", generate_mission),
("Vision Statement", generate_vision),
("Objectives", generate_objectives),
("Core Values", generate_core_values),
("Business Description Analysis", generate_business_description),
("Company Location", generate_company_location),
("Products", generate_products),
("Ownership", generate_ownership),
("Company Structure", generate_company_structure),
("Management Profiles", generate_management_profiles),
("Operational Strategy", generate_operational_strategy),
("Marketing Mix Strategy", generate_marketing_mix),
("Promotional Strategy", generate_promotional_strategy),
("Market Demand Analysis", analyze_demand),
("Market Segment Analysis", segment_market),
("Competitor Analysis", analyze_competitors),
("Porter's Five Forces Analysis", perform_porters_five_forces),
("Industry Analysis", analyze_industry_accommodation),
("Major Player Analysis", list_major_players),
("Business Sub Sector Analysis", analyze_business_sub_sector),
("SWOT Analysis", generate_swot_analysis),
("Funding Request", generate_funding_request),
("Financing & Bank Loan Amortization", create_financing_plan),
("Income Statement Analysis", generate_pro_forma_income_statement),
("Revenue Expense Analysis", predict_revenue_expenses),
("Montly Cash Flow Analysis", generate_monthly_cash_flow),
("Pro Forma Annual Cash Flow Analysis", generate_pro_forma_annual_cash_flow),
("Pro Forma Balance Sheet Analysis", generate_pro_forma_balance_sheet),
("Break-Even Analysis", perform_break_even_analysis),
("Payback Period Analysis", calculate_payback_period),
("Financial Graphs Analysis", generate_financial_graphs),
("Risk Mitigations Analysis", identify_risks_mitigations)
]
sections_to_process_ = [
("Executive Summary", generate_executive_summary),
("Mission Statement", generate_mission),
]
# Sanitize the company name to be used in file names
sanitized_company_name = sanitize_filename(company_name,max_length=50)
#sanitized_section_name = sanitize_filename(section_name, max_length=50)
# Generate final file name and ensure it is not too long
filename = f"Bussiness_Plan_for _{sanitized_company_name}.docx"
# Create a new document
doc = create_document() #f"{sanitized_company_name}_{sanitized_section_name}")
for section_name, generate_prompt_func in sections_to_process:
prompt = generate_prompt_func(data)
section_content = call_llm(prompt)
st.subheader(section_name)
st.write(section_content)
# Update document and create download link
doc = add_section_to_doc(doc, section_name, section_content)
doc_bytes = get_docx_bytes(doc)
st.download_button(
label=f"Download {section_name} as DOCX",
data=doc_bytes,
file_name=f"{section_name.replace(' ', '_').lower()}.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
# Save section content in a file
#filename = f"{company_name}_{section_name}.docx"
# Sanitize section name and limit file name length
sanitized_section_name = sanitize_filename(section_name, max_length=50)
# Generate final file name and ensure it is not too long
filename = f"{sanitized_company_name}_{sanitized_section_name}.docx"
with open(filename, 'wb') as f:
f.write(doc_bytes.getbuffer())
# Send email with section content and attachment
#send_email_with_attachment(email, f"{section_name} of Your Business Proposal", "Please find attached the section of your business proposal.", filename, section_content)
return doc_bytes,filename
def app():
"""Streamlit app with dual options for creating or processing business plans."""
st.title("Business Plan Generator & Analyzer")
# Initialize session state variables if they don't exist
if 'downloaded' not in st.session_state:
st.session_state.downloaded = False
if 'data_processed' not in st.session_state:
st.session_state.data_processed = False
# Option 1: Upload existing business plan
st.header("Option 1: Upload an Existing Business Plan")
uploaded_file = st.file_uploader("Upload your DOCX file", type=["docx"])
if uploaded_file and not st.session_state.data_processed:
# Save the uploaded file locally
# Generate data from the uploaded DOCX file
data = generate_data_from_docx(uploaded_file)
# Process the uploaded file and data
responses,doc_res,doc_bytes = File_to_17_question_Answer(uploaded_file, data)
sanitized_uploaded_name = sanitize_filename(uploaded_file.name, max_length=50)
# Save the processed report locally
report_filename = f"17_quest_{sanitized_uploaded_name}"
with open(report_filename, 'wb') as f:
f.write(doc_bytes)
st.session_state.data_processed = True # Mark as processed
st.success("Data processed successfully!")
# Provide download button for the processed report using streamlit-ext
if not st.session_state.downloaded:
ste.download_button(
label="Download Processed Report",
data=doc_bytes,
file_name=f"17_quest_{sanitized_uploaded_name}",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
if not st.session_state.downloaded:
if False : #st.download_button(
label="Download 17 Question Answered for the Business Plan as DOCX",
data=doc_bytes,
file_name=f"17_quest_{sanitized_uploaded_name}", #f"Business_Plan_{company_name}.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
# ):
# Set flag to indicate that the document has been downloaded
st.session_state.downloaded_3 = True
ste.download_button(
label="Download Business Plan as DOCX",
data=doc_bytes,
file_name=f"17_quest_{sanitized_uploaded_name}",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
ste.download_button(
label="Download Business Plan as DOCX",
data=doc_bytes,
file_name=f"17_quest_{sanitized_uploaded_name}",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
#st.session_state.data_processed_3 = True # Mark as processed
st.success("Data processed successfully!")
#option 2
st.header("Option 2: Create a New Business Plan")
# Option 2: Create a new business plan
st.header("Option 2: Create a New Business Plan")
with st.form(key='business_plan_form'):
company_name = st.text_input("Company Name")
industry = st.text_input("Industry")
location = st.text_input("Location")
mission = st.text_area("Mission Statement")
vision = st.text_area("Vision Statement")
products_services = st.text_area("Description of Products/Services")
target_market = st.text_area("Customer Segments")
value_proposition = st.text_area("Competitive Advantage")
current_revenue = st.number_input("Current Revenue (USD)", min_value=0.0, format="%f")
current_expenses = st.number_input("Current Expenses (USD)", min_value=0.0, format="%f")
funding_requirements = st.text_area("Funding Requirements")
management_team = st.text_area("Key Personnel")
company_structure = st.text_area("Company Structure")
goals_objectives = st.text_area("Goals and Objectives")
market_overview = st.text_area("Market Overview")
current_status = st.text_area("Current Status")
existing_company_details = st.text_area("Existing Company Details")
accelerator_participation = st.text_area("Accelerator Participation Details")
finland_contacts = st.text_area("Contacts in Finland")
reason_for_finland = st.text_area("Why Finland is Attractive")
first_year_plan = st.text_area("First-Year Plan")
funding_plan = st.text_area("Funding Plan")
additional_information = st.text_area("Additional Information")
submitted = st.form_submit_button("Generate Business Plan")
if submitted:
data = {
"company_name": company_name,
"industry": industry,
"location": location,
"mission": mission,
"vision": vision,
"products_services": products_services,
"target_market": target_market,
"value_proposition": value_proposition,
"current_revenue": current_revenue,
"current_expenses": current_expenses,
"funding_requirements": funding_requirements,
"management_team": management_team,
"company_structure": company_structure,
"goals_objectives": goals_objectives,
"market_overview": market_overview,
"current_status": current_status,
"existing_company_details": existing_company_details,
"accelerator_participation": accelerator_participation,
"finland_contacts": finland_contacts,
"reason_for_finland": reason_for_finland,
"first_year_plan": first_year_plan,
"funding_plan": funding_plan,
"additional_information": additional_information
}
business_plan_doc,file_name_busibess_plan = generate_new_business_plan(data)
doc_bytes = get_docx_bytes(business_plan_doc)
# Sanitize filenames for saving locally
sanitized_company_name = sanitize_filename(company_name, max_length=50)
sanitized_section_name = sanitize_filename("Business_Plan", max_length=50) # You can customize this as needed
# Generate final filename and ensure it is not too long
filename = f"{sanitized_company_name}_{sanitized_section_name}.docx"
# Provide download button for the generated DOCX file only if not downloaded yet
if False : #not st.session_state.downloaded_1:
if st.download_button(
label="Download Business Plan as DOCX",
data=doc_bytes,
file_name=f"Business_Plan_{company_name}.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
):
# Set flag to indicate that the document has been downloaded
st.session_state.downloaded_1 = True
# Call additional processing function if needed
responses,doc_bytes = File_to_17_question_Answer(file_name_busibess_plan, data)
file_name_17_quest=f"17_quest_Business_Plan_{company_name}.docx"
# Save the document locally (optional)
if not st.session_state.downloaded_2:
if st.download_button(
label="Download 17 Question Answered for the Business Plan as DOCX",
data=doc_bytes,
file_name=file_name_17_quest, #f"Business_Plan_{company_name}.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
):
# Set flag to indicate that the document has been downloaded
st.session_state.downloaded_2 = True
st.session_state.data_processed = True # Mark as processed
st.success("Data processed successfully!")
if __name__ == "__main__":
app()