GIRI45 commited on
Commit
f8cf1b7
Β·
verified Β·
1 Parent(s): 409fb51

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -77
app.py CHANGED
@@ -1,37 +1,36 @@
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(
@@ -39,60 +38,72 @@ prompt = PromptTemplate(
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)}")
 
 
 
 
 
1
  import os
2
  import streamlit as st
 
3
  from langchain.prompts import PromptTemplate
4
  from langchain.chains import LLMChain
5
+ from langchain_community.chat_models import ChatOpenAI
6
+ from openai import OpenAIError, RateLimitError, InvalidRequestError
7
+ import matplotlib.pyplot as plt
8
+ from fpdf import FPDF
9
  import tempfile
10
 
11
+ # Set OpenAI API Key from Hugging Face secrets
12
+ os.environ["OPENAI_API_KEY"] = st.secrets["OPENAI_API_KEY"]
 
13
 
14
+ # Streamlit UI
15
+ st.set_page_config(page_title="πŸ†š Competitive Analysis Tool", layout="wide")
16
+ st.title("πŸ†š Competitive Analysis Tool")
17
+ st.markdown("Compare two products or services with **Feature Comparison**, **SWOT Analysis**, and a **Summary**.")
 
18
 
19
+ # --- Inputs ---
20
+ product1 = st.text_area("πŸ”Ή Enter details about Product/Service 1", height=150)
21
+ product2 = st.text_area("πŸ”Ή Enter details about Product/Service 2", height=150)
 
 
 
22
 
23
  # --- Prompt Template ---
24
  template = """
25
+ Compare the following two products or services:
26
+ [Product 1]: {product1}
27
+ [Product 2]: {product2}
28
+
29
+ 1. Feature-by-feature comparison in a table format.
30
+ 2. SWOT analysis for each product.
31
+ 3. Summary highlighting key differentiators.
32
+
33
+ Be concise, clear, and professional.
34
  """
35
 
36
  prompt = PromptTemplate(
 
38
  template=template,
39
  )
40
 
41
+ # --- Chain ---
42
+ llm = ChatOpenAI(temperature=0.2, model_name="gpt-3.5-turbo")
43
  comparison_chain = LLMChain(llm=llm, prompt=prompt)
44
 
45
+ # --- PDF Converter ---
46
+ def convert_to_pdf(html_text):
47
+ pdf = FPDF()
48
+ pdf.add_page()
49
+ pdf.set_auto_page_break(auto=True, margin=15)
50
+ pdf.set_font("Arial", size=12)
51
+ for line in html_text.split('\n'):
52
+ pdf.multi_cell(0, 10, line)
53
+ temp_path = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name
54
+ pdf.output(temp_path)
55
+ return temp_path
56
+
57
+ # --- Chart Drawer (dummy feature count for visual demo) ---
58
  def draw_feature_chart():
59
+ features = ["Ease of Use", "Pricing", "Customization", "Support", "Scalability"]
60
+ product1_scores = [7, 6, 8, 9, 7]
61
+ product2_scores = [8, 7, 6, 8, 9]
62
+
63
+ fig, ax = plt.subplots()
64
+ bar_width = 0.35
65
+ x = range(len(features))
66
+
67
+ ax.bar(x, product1_scores, width=bar_width, label='Product 1')
68
+ ax.bar([p + bar_width for p in x], product2_scores, width=bar_width, label='Product 2')
69
+
70
+ ax.set_xlabel('Features')
71
+ ax.set_ylabel('Score')
72
+ ax.set_title('Feature Comparison Chart')
73
+ ax.set_xticks([p + bar_width/2 for p in x])
74
+ ax.set_xticklabels(features)
75
+ ax.legend()
76
+
77
+ st.pyplot(fig)
78
+
79
+ # --- Generate Output ---
80
+ if st.button("βš–οΈ Compare Now") and product1 and product2:
81
+ with st.spinner("Analyzing with LLM..."):
82
+ try:
83
+ result = comparison_chain.run(product1=product1, product2=product2)
84
+
85
+ # --- Show Results ---
86
+ st.subheader("πŸ“‹ Full Analysis")
87
+ st.markdown(result)
88
+
89
+ # --- Show Chart ---
90
+ st.subheader("πŸ“Š Feature Comparison (Chart)")
91
+ draw_feature_chart()
92
+
93
+ # --- Download PDF ---
94
+ pdf_path = convert_to_pdf(f"Competitive Analysis\n\n{result}")
95
+ with open(pdf_path, "rb") as f:
96
+ st.download_button("πŸ“„ Download PDF Report", f, file_name="analysis_report.pdf")
97
+
98
+ except RateLimitError:
99
+ st.error("🚫 You exceeded your OpenAI quota. Check https://platform.openai.com/account/usage")
100
+
101
+ except InvalidRequestError as e:
102
+ st.error(f"❌ Invalid request: {str(e)}")
103
+
104
+ except OpenAIError as e:
105
+ st.error(f"πŸ’₯ OpenAI Error: {str(e)}")
106
+
107
+ # Optional Footer
108
+ st.markdown("---")
109
+ st.markdown("Built with πŸ’‘ using Langchain, Streamlit, and OpenAI.")