GIRI45 commited on
Commit
d54ded6
Β·
verified Β·
1 Parent(s): f31679e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -93
app.py CHANGED
@@ -2,103 +2,94 @@ 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 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)}")
 
2
  import streamlit as st
3
  from langchain.prompts import PromptTemplate
4
  from langchain.chains import LLMChain
5
+ from langchain_community.llms import HuggingFaceHub
6
+ import matplotlib.pyplot as plt
7
+ from io import BytesIO
8
+ from reportlab.pdfgen import canvas
9
+ from reportlab.lib.pagesizes import letter
10
+
11
+ # Load Hugging Face token
12
+ os.environ["HUGGINGFACEHUB_API_TOKEN"] = st.secrets["HF_TOKEN"]
13
+
14
+ # Initialize LLM
15
+ llm = HuggingFaceHub(
16
+ repo_id="google/flan-t5-xl",
17
+ model_kwargs={"temperature": 0.5, "max_length": 1024}
18
+ )
19
 
20
+ # Prompt Template
21
+ template = """
22
+ Compare the following two products or services:
23
  Product 1: {product1}
 
24
  Product 2: {product2}
25
 
26
+ 1. Feature-by-feature comparison.
27
+ 2. SWOT analysis for each.
28
+ 3. A comparative summary highlighting key differentiators.
29
+
30
+ Respond in structured format with headings.
31
  """
32
+
33
+ prompt = PromptTemplate(
34
+ input_variables=["product1", "product2"],
35
+ template=template,
36
  )
37
 
38
+ comparison_chain = LLMChain(llm=llm, prompt=prompt)
39
+
40
+ # Streamlit UI
41
+ st.title("πŸ” Competitive Analysis Tool (Hugging Face Version)")
42
+
43
+ product1 = st.text_area("Enter details for Product/Service 1")
44
+ product2 = st.text_area("Enter details for Product/Service 2")
45
+
46
+ if st.button("Compare"):
47
+ with st.spinner("Generating analysis..."):
48
+ try:
49
+ result = comparison_chain.run(product1=product1, product2=product2)
50
+ st.subheader("πŸ“Š Analysis Result")
51
+ st.markdown(result)
52
+
53
+ # Optional: Simple chart visualization (Dummy feature scores)
54
+ features = ["Usability", "Performance", "Support", "Integration"]
55
+ p1_scores = [8, 7, 6, 9]
56
+ p2_scores = [7, 8, 8, 7]
57
+
58
+ fig, ax = plt.subplots()
59
+ bar_width = 0.35
60
+ index = range(len(features))
61
+
62
+ ax.bar(index, p1_scores, bar_width, label="Product 1")
63
+ ax.bar([i + bar_width for i in index], p2_scores, bar_width, label="Product 2")
64
+
65
+ ax.set_xlabel('Features')
66
+ ax.set_ylabel('Scores')
67
+ ax.set_title('Feature Comparison')
68
+ ax.set_xticks([i + bar_width / 2 for i in index])
69
+ ax.set_xticklabels(features)
70
+ ax.legend()
71
+
72
+ st.pyplot(fig)
73
+
74
+ # PDF Download
75
+ def create_pdf(text):
76
+ buffer = BytesIO()
77
+ c = canvas.Canvas(buffer, pagesize=letter)
78
+ width, height = letter
79
+ y = height - 40
80
+
81
+ for line in text.split('\n'):
82
+ c.drawString(30, y, line)
83
+ y -= 15
84
+ if y < 50:
85
+ c.showPage()
86
+ y = height - 40
87
+ c.save()
88
+ buffer.seek(0)
89
+ return buffer
90
+
91
+ pdf_data = create_pdf(result)
92
+ st.download_button("πŸ“„ Download PDF Report", data=pdf_data, file_name="analysis_report.pdf")
93
+
94
+ except Exception as e:
95
+ st.error(f"Something went wrong: {e}")