GIRI45 commited on
Commit
e347e09
Β·
verified Β·
1 Parent(s): 7fb62bf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -76
app.py CHANGED
@@ -3,107 +3,102 @@ 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.error 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(
37
- input_variables=["product1", "product2"],
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(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 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.")
 
3
  from langchain.prompts import PromptTemplate
4
  from langchain.chains import LLMChain
5
  from langchain_community.chat_models import ChatOpenAI
6
+ from matplotlib import pyplot as plt
 
 
7
  import tempfile
8
+ from fpdf import FPDF
9
+ import openai
10
 
11
+ # πŸ” Set your OpenAI API key from Hugging Face secret
12
  os.environ["OPENAI_API_KEY"] = st.secrets["OPENAI_API_KEY"]
13
 
14
+ # 🎯 Prompt template
15
+ prompt_template = PromptTemplate(
16
+ input_variables=["product1", "product2"],
17
+ template="""
18
+ Compare the following two products/services:
 
 
 
19
 
20
+ Product 1: {product1}
 
 
 
 
21
 
22
+ Product 2: {product2}
 
 
23
 
24
+ 1. Provide a detailed feature-by-feature comparison.
25
+ 2. Perform a SWOT analysis for each.
26
+ 3. Conclude with a comparative summary highlighting key differentiators.
27
  """
 
 
 
 
28
  )
29
 
30
+ # πŸ€– LLM Model Setup
31
+ llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.3)
32
+ comparison_chain = LLMChain(llm=llm, prompt=prompt_template)
33
 
34
+ # πŸ“Š Helper: Draw dummy chart for features
35
+ def draw_feature_chart():
36
+ labels = ['Price', 'Ease of Use', 'Performance', 'Support', 'Customization']
37
+ product1_scores = [7, 8, 6, 9, 7]
38
+ product2_scores = [6, 7, 9, 8, 6]
39
+
40
+ x = range(len(labels))
41
+ plt.figure(figsize=(8, 4))
42
+ plt.bar(x, product1_scores, width=0.4, label="Product 1", align='center')
43
+ plt.bar([i + 0.4 for i in x], product2_scores, width=0.4, label="Product 2", align='center')
44
+ plt.xticks([i + 0.2 for i in x], labels)
45
+ plt.ylabel("Rating (out of 10)")
46
+ plt.title("Feature Comparison")
47
+ plt.legend()
48
+ st.pyplot(plt)
49
+
50
+ # πŸ“ Helper: Convert text to PDF
51
  def convert_to_pdf(text):
52
  pdf = FPDF()
 
53
  pdf.set_auto_page_break(auto=True, margin=15)
54
+ pdf.add_page()
55
  pdf.set_font("Arial", size=12)
56
+
57
  for line in text.split('\n'):
58
  pdf.multi_cell(0, 10, line)
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
+ temp_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
61
+ pdf.output(temp_pdf.name)
62
+ return temp_pdf.name
63
 
64
+ # πŸš€ Streamlit UI
65
+ st.set_page_config(page_title="πŸ” Competitive Analysis Tool", layout="wide")
66
+ st.title("πŸ€– Competitive Analysis Tool using LLMs")
67
+ st.write("Compare two products or services with a detailed feature comparison, SWOT analysis, and summary.")
 
 
68
 
69
+ # ✍️ User Inputs
70
+ product1 = st.text_area("πŸ…°οΈ Enter details about Product/Service 1", height=200)
71
+ product2 = st.text_area("πŸ…±οΈ Enter details about Product/Service 2", height=200)
72
 
73
+ if st.button("πŸ” Compare Now"):
74
+ if not product1 or not product2:
75
+ st.warning("⚠️ Please enter details for both products/services.")
76
+ else:
77
+ with st.spinner("Analyzing... Please wait."):
78
+ try:
79
+ result = comparison_chain.run(product1=product1, product2=product2)
80
 
81
+ # Display results
82
+ st.subheader("πŸ“‹ Full Analysis")
83
+ st.markdown(result)
84
 
85
+ # Show Chart
86
+ st.subheader("πŸ“Š Feature Comparison (Chart)")
87
+ draw_feature_chart()
88
 
89
+ # PDF Download
90
+ pdf_path = convert_to_pdf(f"Competitive Analysis\n\n{result}")
91
+ with open(pdf_path, "rb") as f:
92
+ st.download_button("πŸ“„ Download PDF Report", f, file_name="analysis_report.pdf")
93
 
94
+ except openai.RateLimitError:
95
+ st.error("🚫 You exceeded your OpenAI quota. Check https://platform.openai.com/account/usage")
96
 
97
+ except openai.InvalidRequestError as e:
98
+ st.error(f"❌ Invalid request: {str(e)}")
99
 
100
+ except openai.OpenAIError as e:
101
+ st.error(f"πŸ’₯ OpenAI Error: {str(e)}")
102
 
103
+ except Exception as e:
104
+ st.error(f"⚠️ Unexpected Error: {str(e)}")