GIRI45 commited on
Commit
fe198df
Β·
verified Β·
1 Parent(s): fcc671d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -35
app.py CHANGED
@@ -1,55 +1,98 @@
 
1
  import streamlit as st
2
  from langchain.chat_models import ChatOpenAI
3
  from langchain.prompts import PromptTemplate
4
  from langchain.chains import LLMChain
5
- import os
 
 
 
6
 
7
- # Set your OpenAI key
8
- openai_api_key = os.getenv("OPENAI_API_KEY")
9
- os.environ["OPENAI_API_KEY"] = openai_api_key
10
 
11
- # Prompt template for comparison
12
- prompt_template = PromptTemplate(
13
- input_variables=["product1", "product2"],
14
- template="""
15
- Compare the following two products/services:
16
 
17
- Product 1: {product1}
18
- Product 2: {product2}
 
 
 
 
19
 
20
- Please provide the following:
 
 
 
21
  1. A feature-by-feature comparison.
22
- 2. A SWOT (Strengths, Weaknesses, Opportunities, Threats) analysis for each.
23
  3. A comparative summary highlighting key differentiators.
24
  """
 
 
 
 
25
  )
26
 
27
- # Initialize LLM and chain
28
- llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
29
- comparison_chain = LLMChain(llm=llm, prompt=prompt_template)
30
 
31
- # Streamlit UI
32
- st.set_page_config(page_title="Competitive Analysis Tool", layout="wide")
33
- st.title("πŸ” Competitive Analysis Tool")
 
 
34
 
35
- st.markdown("Compare two products or services and get a full SWOT analysis and feature comparison.")
 
 
 
 
36
 
37
- # Input fields
38
- product1 = st.text_area("πŸ“ Enter details of Product/Service 1", height=200)
39
- product2 = st.text_area("πŸ“ Enter details of Product/Service 2", height=200)
 
 
 
40
 
41
- # Button
42
- if st.button("Compare"):
43
- if product1.strip() and product2.strip():
44
- with st.spinner("Generating analysis..."):
45
- result = comparison_chain.run(product1=product1, product2=product2)
46
 
47
- # Display result in separate sections
48
- st.subheader("πŸ“Š Feature Comparison & SWOT Analysis")
49
- st.markdown(result)
 
50
  else:
51
- st.warning("Please enter details for both products/services.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
- # Footer
54
- st.markdown("---")
55
- st.caption("Powered by OpenAI + Langchain + Streamlit")
 
1
+ import os
2
  import streamlit as st
3
  from langchain.chat_models import ChatOpenAI
4
  from langchain.prompts import PromptTemplate
5
  from langchain.chains import LLMChain
6
+ import openai
7
+ import plotly.graph_objects as go
8
+ from xhtml2pdf import pisa
9
+ import tempfile
10
 
11
+ # --- Configuration ---
12
+ st.set_page_config(page_title="πŸ” Competitive Analysis Tool")
13
+ st.title("πŸ” Competitive Analysis Tool")
14
 
15
+ # --- OpenAI Key ---
16
+ openai_api_key = os.getenv("OPENAI_API_KEY")
17
+ if not openai_api_key:
18
+ st.error("❌ OPENAI_API_KEY not found in environment variables.")
19
+ st.stop()
20
 
21
+ # --- Initialize LLM ---
22
+ try:
23
+ llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0, openai_api_key=openai_api_key)
24
+ except openai.error.OpenAIError as e:
25
+ st.error(f"Failed to initialize OpenAI: {str(e)}")
26
+ st.stop()
27
 
28
+ # --- Prompt Template ---
29
+ template = """
30
+ Compare the following two products/services: {product1} and {product2}.
31
+ Provide the following:
32
  1. A feature-by-feature comparison.
33
+ 2. SWOT analysis for each product/service.
34
  3. A comparative summary highlighting key differentiators.
35
  """
36
+
37
+ prompt = PromptTemplate(
38
+ input_variables=["product1", "product2"],
39
+ template=template,
40
  )
41
 
42
+ comparison_chain = LLMChain(llm=llm, prompt=prompt)
 
 
43
 
44
+ # --- PDF Conversion ---
45
+ def convert_to_pdf(text: str):
46
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
47
+ pisa.CreatePDF(text, dest=tmp_file)
48
+ return tmp_file.name
49
 
50
+ # --- Chart Drawing (Static Example) ---
51
+ def draw_feature_chart():
52
+ features = ["Storage", "Collaboration", "Sync Speed", "Security"]
53
+ scores1 = [8, 9, 7, 8]
54
+ scores2 = [7, 6, 9, 7]
55
 
56
+ fig = go.Figure(data=[
57
+ go.Bar(name='Product 1', x=features, y=scores1),
58
+ go.Bar(name='Product 2', x=features, y=scores2)
59
+ ])
60
+ fig.update_layout(barmode='group', title="πŸ“Š Feature Comparison")
61
+ st.plotly_chart(fig, use_container_width=True)
62
 
63
+ # --- UI Input ---
64
+ with st.form("product_form"):
65
+ product1 = st.text_area("Enter details for Product/Service 1", height=150, placeholder="e.g., Google Drive: Cloud storage with real-time collaboration.")
66
+ product2 = st.text_area("Enter details for Product/Service 2", height=150, placeholder="e.g., Dropbox: File sharing and sync service with smart folders.")
67
+ submitted = st.form_submit_button("Compare")
68
 
69
+ # --- On Submit ---
70
+ if submitted:
71
+ if not product1.strip() or not product2.strip():
72
+ st.warning("Please enter descriptions for both products.")
73
  else:
74
+ with st.spinner("πŸ” Generating analysis..."):
75
+ try:
76
+ result = comparison_chain.run(product1=product1, product2=product2)
77
+
78
+ # --- Show Results ---
79
+ st.subheader("πŸ“‹ Full Analysis")
80
+ st.markdown(result)
81
+
82
+ # --- Show Chart ---
83
+ st.subheader("πŸ“Š Feature Comparison (Chart)")
84
+ draw_feature_chart()
85
+
86
+ # --- Download PDF ---
87
+ pdf_path = convert_to_pdf(f"<h1>Competitive Analysis</h1><pre>{result}</pre>")
88
+ with open(pdf_path, "rb") as f:
89
+ st.download_button("πŸ“„ Download PDF Report", f, file_name="analysis_report.pdf")
90
+
91
+ except openai.error.RateLimitError:
92
+ st.error("🚫 You exceeded your OpenAI quota. Check https://platform.openai.com/account/usage")
93
+
94
+ except openai.error.InvalidRequestError as e:
95
+ st.error(f"❌ Invalid request: {str(e)}")
96
 
97
+ except openai.error.OpenAIError as e:
98
+ st.error(f"πŸ’₯ OpenAI Error: {str(e)}")