sosa123454321's picture
Update app.py
1d80294 verified
import streamlit as st
from docx import Document
import re
import io
import os
import requests
from retrying import retry
from functions import *
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from email.mime.text import MIMEText
global data
# Declare the Exa search API
exa = Exa(api_key=os.getenv("EXA_API_KEY"))
# Initialize available Groq APIs from Hugging Face secrets
#groq_api_keys = st.secrets["GROQ_API_KEYS"].split(",") # Split the comma-separated string into a list
groq_api_keys = os.getenv("GROQ_API_KEYS").split(",") # Split the comma-separated string into a list
available_groq_apis = [Groq(api_key=key.strip()) for key in groq_api_keys if key.strip()] # Create Groq instances
current_api_index = 0
utilized_model = "llama3-70b-8192"
# Functions for the Exa Search content & Parameters for Highlights search
highlights_options = {
"num_sentences": 7, # Length of highlights
"highlights_per_url": 1, # Get the best highlight for each URL
}
# Display the image using st.image
st.image("https://i.sstatic.net/jUkkO0Fd.jpg", caption="پوستر نمایشگاه", use_column_width=True)
st.title("نویسم طرح کسب و کار خود")
st.markdown("""
**وب‌سایت:** [Iran Investex](https://iraninvestex.ir/)
""")
st.write("برای همکاری بیشتر، لطفاً با نویسنده تماس بگیرید 👇🌹")
st.write("ایمیل: chatgpt4compas@gmail.com")
st.markdown("[تماس با واتساپ 📞](https://web.whatsapp.com/send?phone=12085033653)")
# Exhibition information
st.markdown("""
## اطلاعات نمایشگاه
**عنوان:** نمایشگاه سرمایه‌گذاری ایران
**شماره تماس:** [مدیر فروش: 09031239281](tel:09031239281)
**راه‌های ارتباطی:**
- **ایمیل:** [ایمیل را اینجا وارد کنید](mailto:ایمیل) # Replace with actual email
- **اینستاگرام:** [Instagram](https://www.instagram.com/your_instagram_handle) # Replace with actual Instagram link
""")
@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000, stop_max_attempt_number=5)
def call_llm_0(prompt):
global current_api_index
while current_api_index < len(available_groq_apis):
try:
client = available_groq_apis[current_api_index]
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 = f"You are a Business proposal generator in language of {data['language']} .Read the provided contexts and, if relevant, use them to answer the user's question."
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
except Exception as e:
st.warning(f"API {current_api_index + 1} expired or failed: {str(e)}")
current_api_index += 1
raise Exception("All available APIs have expired.")
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 sanitize_filename(filename, max_length=100):
sanitized = re.sub(r'[<>:"/\\|?*]', '', filename)
return sanitized[:max_length]
def send_email_with_attachment(email, file_path):
sender_email = "your_sender_email@example.com" # Replace with your sender email
sender_password = "your_sender_password" # Replace with sender email password
subject = "Business Proposal Document"
# Create the email
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = email
msg['Subject'] = subject
# Attach the document
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(file_path, "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f"attachment; filename= {os.path.basename(file_path)}")
msg.attach(part)
# Send the email
try:
with smtplib.SMTP('smtp.example.com', 587) as server: # Use your SMTP server
server.starttls()
server.login(sender_email, sender_password)
server.send_message(msg)
st.success(f"Proposal sent to {email} successfully.")
except Exception as e:
st.error(f"Error sending email: {str(e)}")
def collect_basic_info():
global data
st.title("Business Proposal Generator")
# Initialize session state variables if they do not exist
if 'data' not in st.session_state:
st.session_state.data = {
"company_name": "",
"industry": "",
"location": "",
"mission": "",
"vision": "",
"products_services": "",
"target_market": "",
"value_proposition": "",
"promotional_strategy": "",
"current_revenue": 0.0,
"current_expenses": 0.0,
"funding_requirements": "",
"management_team": "",
"company_structure": "",
"goals_objectives": "",
"operational_strategy": "",
"market_overview": "",
"email": "",
"whatsapp_number": "",
"language_index": 0 # Default to English
}
if 'section_contents' not in st.session_state:
st.session_state.section_contents = {}
data = st.session_state.data
# Add language selection using selectbox
languages = ["English", "Persian", "Arabic", "Russian", "Chinese", "Japanese", "Finnish", "German"]
# Custom styling using Streamlit's built-in options
with open("./custom.css", "r") as f:
st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)
data["language"] = st.selectbox(
"Select Language",
options=languages,
key="language_selector"
)
# Collect data inputs
data["company_name"] = st.text_input("Company Name", value=data["company_name"])
data["industry"] = st.text_input("Industry", value=data["industry"])
data["location"] = st.text_input("Location", value=data["location"])
data["mission"] = st.text_area("Mission Statement", value=data["mission"])
data["vision"] = st.text_area("Vision Statement", value=data["vision"])
data["products_services"] = st.text_area("Products/Services", value=data["products_services"])
data["target_market"] = st.text_area("Target Market", value=data["target_market"])
data["value_proposition"] = st.text_area("Value Proposition", value=data["value_proposition"])
data["promotional_strategy"] = st.text_area("Promotional Strategy", value=data["promotional_strategy"])
data["current_revenue"] = st.number_input("Current Revenue", value=data["current_revenue"], format="%.2f")
data["current_expenses"] = st.number_input("Current Expenses", value=data["current_expenses"], format="%.2f")
data["funding_requirements"] = st.text_area("Funding Requirements", value=data["funding_requirements"])
data["management_team"] = st.text_area("Management Team", value=data["management_team"])
data["company_structure"] = st.text_area("Company Structure", value=data["company_structure"])
data["goals_objectives"] = st.text_area("Goals/Objectives", value=data["goals_objectives"])
data["operational_strategy"] = st.text_area("Operational Strategy", value=data["operational_strategy"])
data["market_overview"] = st.text_area("Market Overview", value=data["market_overview"])
data["email"] = st.text_input("Email", value=data["email"])
data["whatsapp_number"] = st.text_input("WhatsApp Number", value=data["whatsapp_number"])
if st.button('Submit'):
for key in data:
st.session_state.data[key] = data[key]
# Generate and save content for 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),
("Monthly 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)
]
doc = create_document()
sanitized_company_name = sanitize_filename(data['company_name'], max_length=50)
filename_prefix = f"Business_Plan_for_{sanitized_company_name}"
for section_name, generate_prompt_func in sections_to_process:
if section_name not in st.session_state.section_contents:
prompt = generate_prompt_func(data)
section_content = call_llm(prompt)
st.session_state.section_contents[section_name] = section_content
section_content = st.session_state.section_contents[section_name]
st.subheader(section_name)
st.write(section_content)
doc = add_section_to_doc(doc, section_name, section_content)
# Generate document bytes for download
doc_bytes = get_docx_bytes(doc)
st.download_button(
label="Download Full Proposal",
data=doc_bytes,
file_name=f"{filename_prefix}.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
# Send email after generating the document
if data['email']:
email_file_path = f"/mnt/data/{filename_prefix}.docx" # Path for the email attachment
send_email_with_attachment(data['email'], email_file_path)
collect_basic_info()