AsthanM commited on
Commit
05760ad
·
verified ·
1 Parent(s): 16f51c1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -66
app.py CHANGED
@@ -4,8 +4,9 @@ import os
4
  from fpdf import FPDF
5
  from io import BytesIO
6
  import textwrap
 
7
 
8
- # Set page layout and styling
9
  st.set_page_config(page_title="Pro Competitive Analysis", layout="centered")
10
  st.markdown("""
11
  <style>
@@ -37,33 +38,36 @@ button:hover {
37
 
38
  # App header
39
  st.title("💼 Competitive Analysis Pro")
40
- st.markdown("Generate expert-level comparisons of two products or services, including SWOT, business recommendations, and more.")
41
 
42
- # Set Hugging Face API key
43
  os.environ["HUGGINGFACEHUB_API_TOKEN"] = st.secrets["HF_TOKEN"]
44
 
45
- # Initialize the LLM
46
  llm = HuggingFaceHub(
47
  repo_id="tiiuae/falcon-7b-instruct",
48
  model_kwargs={"temperature": 0.7, "max_new_tokens": 1024}
49
  )
50
 
51
- # User inputs
52
  product1 = st.text_area("🧩 Product/Service 1", height=200, placeholder="e.g., iPhone 13")
53
  product2 = st.text_area("🧩 Product/Service 2", height=200, placeholder="e.g., iPhone 14")
54
 
55
- # On click
56
  if st.button("🔍 Run Competitive Analysis", use_container_width=True):
57
  if not product1 or not product2:
58
- st.warning("Please enter descriptions for both products.")
59
  else:
60
- # Prompt for the model
61
  system_instruction = """
62
  You are a professional market analyst trained to evaluate two competing products or services.
63
 
64
  Write an in-depth comparative analysis in **markdown format**, covering:
65
 
66
  1. Feature-by-Feature Comparison:
 
 
 
67
  - Hardware specifications
68
  - Design and display
69
  - Performance (CPU, GPU, etc.)
@@ -87,68 +91,50 @@ Write an in-depth comparative analysis in **markdown format**, covering:
87
 
88
  ⚠️ Do NOT include or reference these instructions in your output. Return only the clean markdown report.
89
  """
 
 
90
 
91
- user_input = f"""
92
- Product 1:
93
- {product1}
94
-
95
- Product 2:
96
- {product2}
97
- """
98
- final_input = system_instruction.strip() + "\n\n" + user_input.strip()
99
-
100
- # Run the LLM
101
  with st.spinner("🧠 Generating detailed analysis..."):
102
  result = llm(final_input)
103
 
104
- # Display markdown result
105
  st.markdown("### 📊 Expert Comparison")
106
  st.markdown(result)
107
 
108
- # Sanitize and wrap text for PDF
109
- from fpdf import FPDF
110
- from io import BytesIO
111
- import textwrap
112
- import re
113
-
114
- # Clean markdown
115
- clean_text = result.replace("**", "").replace("*", "").replace("`", "").replace("#", "").replace("•", "-")
116
-
117
- # Init PDF
118
- pdf = FPDF()
119
- pdf.add_page()
120
- pdf.set_font("Arial", size=12)
121
- pdf.set_auto_page_break(auto=True, margin=15)
122
-
123
- def safe_line_split(text, width=100):
124
- # Split long non-space strings if needed
125
- words = re.findall(r'.{1,%d}' % width, text) if len(text) > width else [text]
126
- return words
127
-
128
- for line in clean_text.split("\n"):
129
- line = line.strip()
130
- if not line:
131
- pdf.ln(5)
132
- continue
133
- try:
134
- wrapped_lines = textwrap.wrap(line, width=100)
135
- if not wrapped_lines:
136
- wrapped_lines = safe_line_split(line)
137
- for wl in wrapped_lines:
138
- pdf.multi_cell(0, 10, wl)
139
- except Exception as e:
140
- print(f"⚠️ Skipped line (too long or invalid): {line[:50]}...")
141
-
142
- # Output stream
143
- pdf_output = BytesIO()
144
- pdf.output(pdf_output)
145
- pdf_output.seek(0)
146
-
147
- # Download
148
- st.download_button(
149
- label="📥 Download Report as PDF",
150
- data=pdf_output,
151
- file_name="competitive_analysis_report.pdf",
152
- mime="application/pdf",
153
- use_container_width=True
154
- )
 
4
  from fpdf import FPDF
5
  from io import BytesIO
6
  import textwrap
7
+ import re
8
 
9
+ # Set page layout and dark theme styling
10
  st.set_page_config(page_title="Pro Competitive Analysis", layout="centered")
11
  st.markdown("""
12
  <style>
 
38
 
39
  # App header
40
  st.title("💼 Competitive Analysis Pro")
41
+ st.markdown("Generate expert-level comparisons between two products or services, with SWOT, insights, and business recommendations.")
42
 
43
+ # Set Hugging Face API key (securely via Secrets)
44
  os.environ["HUGGINGFACEHUB_API_TOKEN"] = st.secrets["HF_TOKEN"]
45
 
46
+ # LLM Setup
47
  llm = HuggingFaceHub(
48
  repo_id="tiiuae/falcon-7b-instruct",
49
  model_kwargs={"temperature": 0.7, "max_new_tokens": 1024}
50
  )
51
 
52
+ # Input Fields
53
  product1 = st.text_area("🧩 Product/Service 1", height=200, placeholder="e.g., iPhone 13")
54
  product2 = st.text_area("🧩 Product/Service 2", height=200, placeholder="e.g., iPhone 14")
55
 
56
+ # Button logic
57
  if st.button("🔍 Run Competitive Analysis", use_container_width=True):
58
  if not product1 or not product2:
59
+ st.warning("Please enter both product descriptions.")
60
  else:
61
+ # LLM prompt (not printed)
62
  system_instruction = """
63
  You are a professional market analyst trained to evaluate two competing products or services.
64
 
65
  Write an in-depth comparative analysis in **markdown format**, covering:
66
 
67
  1. Feature-by-Feature Comparison:
68
+
69
+ - For both Product 1 and Product 2 separately
70
+
71
  - Hardware specifications
72
  - Design and display
73
  - Performance (CPU, GPU, etc.)
 
91
 
92
  ⚠️ Do NOT include or reference these instructions in your output. Return only the clean markdown report.
93
  """
94
+ user_input = f"\n\nProduct 1:\n{product1}\n\nProduct 2:\n{product2}"
95
+ final_input = system_instruction.strip() + user_input
96
 
 
 
 
 
 
 
 
 
 
 
97
  with st.spinner("🧠 Generating detailed analysis..."):
98
  result = llm(final_input)
99
 
 
100
  st.markdown("### 📊 Expert Comparison")
101
  st.markdown(result)
102
 
103
+ # Clean markdown & sanitize output
104
+ clean_text = result.replace("**", "").replace("*", "").replace("`", "").replace("#", "").replace("•", "-")
105
+
106
+ # PDF Generation (safe against long unbreakable lines)
107
+ pdf = FPDF()
108
+ pdf.add_page()
109
+ pdf.set_font("Arial", size=12)
110
+ pdf.set_auto_page_break(auto=True, margin=15)
111
+
112
+ def safe_line_split(text, width=100):
113
+ return re.findall(r'.{1,%d}' % width, text) if len(text) > width else [text]
114
+
115
+ for line in clean_text.split("\n"):
116
+ line = line.strip()
117
+ if not line:
118
+ pdf.ln(5)
119
+ continue
120
+ try:
121
+ wrapped_lines = textwrap.wrap(line, width=100)
122
+ if not wrapped_lines:
123
+ wrapped_lines = safe_line_split(line)
124
+ for wl in wrapped_lines:
125
+ pdf.multi_cell(0, 10, wl)
126
+ except Exception as e:
127
+ print(f"⚠️ Skipped line due to error: {line[:50]}...")
128
+
129
+ pdf_output = BytesIO()
130
+ pdf.output(pdf_output)
131
+ pdf_output.seek(0)
132
+
133
+ # Streamlit download button
134
+ st.download_button(
135
+ label="📥 Download Report as PDF",
136
+ data=pdf_output,
137
+ file_name="competitive_analysis_report.pdf",
138
+ mime="application/pdf",
139
+ use_container_width=True
140
+ )