Srish117 commited on
Commit
c0ea862
·
verified ·
1 Parent(s): 125505a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +907 -907
app.py CHANGED
@@ -1,907 +1,907 @@
1
- import ast
2
- import requests
3
- import json
4
- from duckduckgo_search import DDGS
5
- import google.generativeai as genai
6
- from groq import Groq
7
- import time
8
- import smtplib
9
- from email.mime.text import MIMEText
10
- from email.mime.multipart import MIMEMultipart
11
- import markdown
12
- import streamlit as st
13
-
14
- genai.configure(api_key='AIzaSyCootL_jwKI3YDb6cKRJV-Ad0N4oKlLXXE')
15
- client = Groq(api_key='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')
16
-
17
- # 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
18
-
19
- def jina(url):
20
- base_url= "https://r.jina.ai//"
21
- url=base_url+url
22
- response=requests.get(url)
23
- return response.text
24
-
25
- def groq_inference(query):
26
-
27
- # client = Groq()
28
- completion = client.chat.completions.create(
29
- model="llama3-groq-70b-8192-tool-use-preview",
30
- messages=[
31
- {
32
- "role": "user",
33
- "content": query
34
- }
35
- ],
36
- temperature=0,
37
- max_tokens=2040,
38
- top_p=0.65,
39
- # stream=True,
40
- stop=None,
41
- )
42
-
43
- # for chunk in completion:
44
- # print(chunk.choices[0].delta.content or "", end="")
45
- # return completion.choices[0].delta.content
46
- return completion.choices[0].message.content
47
-
48
- #Know about product
49
- def serper_prod(company):
50
- url = "https://google.serper.dev/news"
51
-
52
- payload = json.dumps({
53
- "q": f"{company} info",
54
- })
55
- headers = {
56
- 'X-API-KEY': '7d6a39f71072f99cd421dbdd6cfebc73e2a66a07',
57
- 'Content-Type': 'application/json'
58
- }
59
-
60
- response = requests.request("POST", url, headers=headers, data=payload)
61
-
62
- return json.loads(response.text)
63
-
64
-
65
- #Know about the competiton\competitiors
66
- def serper_compi(company):
67
- url = "https://google.serper.dev/search"
68
-
69
- payload = json.dumps({
70
- "q": f"{company} competitors.",
71
- })
72
- headers = {
73
- 'X-API-KEY': '7d6a39f71072f99cd421dbdd6cfebc73e2a66a07',
74
- 'Content-Type': 'application/json'
75
- }
76
-
77
- response = requests.request("POST", url, headers=headers, data=payload)
78
-
79
- return json.loads(response.text)
80
-
81
- def AI_Search_compi(text):
82
- ans = DDGS().chat("Summarize the text and dont remove the important terms about products or applications which should be helped for planning market for a company " + text, model='claude-3-haiku')
83
- return ans
84
-
85
- def AI_Search_compi(text,titles,name):
86
- ans = groq_inference(f"""Summarize the text of the articles titles are {titles} and dont remove the important terms about products or applications which should be helped for knowing about the compititors for a company {name} and the data is: {text}""")
87
- return ans
88
-
89
- def AI_Product_Analysis(text):
90
- ans = DDGS().chat("Analyze the products mentioned in the following news article in 400 words or fewer. Focus on their features, market relevance, and potential impact for a company's market planning: " + text, model='claude-3-haiku')
91
- return ans
92
-
93
- def AI_Product_Summary(news_summaries,product):
94
- # combined_summaries = " ".join(news_summaries)
95
- ans = groq_inference(f"""Create a comprehensive summary of the product {product} based on the following summaries of 10 or fewer news articles. Ensure no important product details are lost and remember that these are form the news articles so you may have add text also : """ + news_summaries)
96
- # ans = DDGS().chat("Create a comprehensive summary of the product based on the following summaries of 10 or fewer news articles. Ensure no important product details are lost: " + news_summaries, model='gpt-4o-mini')
97
- return ans
98
-
99
- def AI_Product_Summary_prod(news_summaries):
100
- # combined_summaries = " ".join(news_summaries)
101
- ans = groq_inference(f"""Create a comprehensive summary of the product based on the following summaries of 10 or fewer news articles. Ensure no important product details are lost and remember that these are form the news articles so you may have add text also : """ + news_summaries)
102
- # ans = DDGS().chat("Create a comprehensive summary of the product based on the following summaries of 10 or fewer news articles. Ensure no important product details are lost: " + news_summaries, model='gpt-4o-mini')
103
- return ans
104
- # AI_Product_Summary_prod
105
-
106
- def AI_Search_extract_cmpy(text):
107
- # prompt = """You will be given a dynamic text that summarizes key products, applications, and comparisons from articles about VR headsets. Your task is to extract relevant product names from the text and generate a list of search queries suitable for a search API.Don't give more than five names in the list.
108
-
109
- # Output Format:
110
-
111
- # The output should be a list in the following format:
112
- # ['company - product name', 'company - product name', 'product name', ...]
113
- # If the company name is unknown, only include the product name without the company name.
114
- # Do not include any introductory or explanatory text in the output; provide only the list in brackets.
115
- # Input Format:
116
-
117
- # The input will be a summary text containing product names, features, and key points."""
118
- #$#$#$#$#
119
- prompt = """You will be given a dynamic text that summarizes key products, applications, and comparisons from articles about VR headsets. Your task is to extract relevant product names from the text and generate a list of search queries suitable for a search API. Don't give more than five names in the list.
120
- Output Format:
121
-
122
- Provide only the list in the following format, without any explanatory or introductory text:
123
- ['company - product name', 'company - product name', 'product name', ...]
124
- and remember dont give like this ['McDonald's - Big Mac'] becauses this will be given to pyhton this return error.
125
- If the company name is unknown, only include the product name without the company name."""
126
- # prompt = """You will be given a dynamic text that summarizes key products, applications, and comparisons from articles about VR headsets. Your task is to extract relevant product names from the text and generate a list of search queries suitable for a search API. Don't give more than five names in the list.Dont repeat the company names and please dont add single quotes or any other special characters that will be given error for pyhton to read.
127
- # Output Format:
128
-
129
- # Provide only the list in the following format, without any explanatory or introductory text:
130
- # ['company - product name', 'company - product name', 'product name', ...]
131
- # and remember dont give like this ['McDonald's - Big Mac'] becauses this will be given to pyhton this return error.
132
- # If the company name is unknown, only include the product name without the company name."""
133
-
134
- # ans = groq_inference(prompt + f"the text is: {text}")
135
- ans = DDGS().chat(prompt+"the text is \n" + text, model='claude-3-haiku')
136
- return ast.literal_eval(ans)
137
-
138
-
139
- def AI_Company_Summary(news_summaries):
140
- ans = DDGS().chat("Analyze the following combined summaries about multiple products. Provide a detailed summary of each product individually, clearly outlining their features, market relevance, and competitive advantages, so this information can be used to analyze competitor products: " + news_summaries, model='claude-3-haiku')
141
- return ans
142
-
143
- def AI_Analysis(Product_analysis,Compitetiors_analysis):
144
- prompt = Compitetiors_analysis + "Product Information: \n " + Product_analysis
145
- system_prompt = "Analyze the following competitor and product details. Provide a thorough technical analysis of each product, focusing on its market standing, technical strengths, and areas for improvement. Offer actionable insights on how the product can be enhanced to increase sales and profitability. Compare the product with competitors, identifying gaps and opportunities for differentiation and market leadership and remember that give the analyis of the compitiors only if they are related else dont give it: " + "Competitors: \n "+ prompt,
146
-
147
- # ans = DDGS().chat(prompt, model='claude-3-haiku')
148
- # if len(prompt) > 22000:
149
- # prompt = prompt[:22000]
150
- # ans = DDGS().chat(
151
- # "Analyze the following competitor and product details. Provide a thorough technical analysis of each product, focusing on its market standing, technical strengths, and areas for improvement. Offer actionable insights on how the product can be enhanced to increase sales and profitability. Compare the product with competitors, identifying gaps and opportunities for differentiation and market leadership: " + "Competitors: \n "
152
- # + prompt,
153
- # model='claude-3-haiku')
154
- model = genai.GenerativeModel(model_name="gemini-1.5-flash")
155
- response = model.generate_content(system_prompt)
156
-
157
- return response.text
158
-
159
- def AI_Analysis(Product_analysis,Compitetiors_analysis):
160
- prompt = Compitetiors_analysis + "Product Information: \n " + Product_analysis
161
- system_prompt = "Analyze the following competitor and product details. Provide a thorough technical analysis of each product, focusing on its market standing, technical strengths, and areas for improvement. Offer actionable insights on how the product can be enhanced to increase sales and profitability. Compare the product with competitors, identifying gaps and opportunities for differentiation and market leadership and remember that give the analyis of the compitiors only if they are related else dont give it: " + "Competitors: \n "+ prompt,
162
-
163
- # ans = DDGS().chat(prompt, model='claude-3-haiku')
164
- # if len(prompt) > 22000:
165
- # prompt = prompt[:22000]
166
- # ans = DDGS().chat(
167
- # "Analyze the following competitor and product details. Provide a thorough technical analysis of each product, focusing on its market standing, technical strengths, and areas for improvement. Offer actionable insights on how the product can be enhanced to increase sales and profitability. Compare the product with competitors, identifying gaps and opportunities for differentiation and market leadership: " + "Competitors: \n "
168
- # + prompt,
169
- # model='claude-3-haiku')
170
- model = genai.GenerativeModel(model_name="gemini-1.5-flash")
171
- response = model.generate_content(system_prompt)
172
-
173
- return response.text
174
-
175
- # """ This takes input of company and return summary of the company"""
176
- def analysis_name(text):
177
- compi_urls = [i['link'] for i in text['news']][0:4]
178
- print(compi_urls)
179
- text = [jina(url) for url in compi_urls]
180
- ans = ' '.join(AI_Product_Analysis(i[:8000]) for i in text if len(i)>1500)
181
- # time.sleep(25)
182
- summ = AI_Product_Summary_prod(ans[:21000])
183
- return summ
184
-
185
-
186
- # """" This is for knowing about the Product"""
187
- # 11
188
- # groq
189
- def know_prod(name):
190
- ser = serper_prod(name)
191
- compi_urls = [i['link'] for i in ser['news']]
192
- text = [jina(url) for url in compi_urls]
193
- ans = ' '.join(AI_Product_Analysis(i[:8000]) for i in text if len(i)>1500)
194
- summ = AI_Product_Summary(ans[:20000],name)
195
- return summ
196
-
197
- # """ This takes input of company and return list of the compi"""
198
- # 11
199
- def compi_main(name):
200
- ret = serper_compi(name)
201
- compi_urls = [i['link'] for i in ret['organic']]
202
- title_list= [i['title'] for i in ret['organic']]
203
- text = [jina(url) for url in compi_urls]
204
- ans = ' '.join(AI_Search_compi(i[:8000],title_list,name) for i in text if len(i)>1500)
205
- lst = AI_Search_extract_cmpy(ans)
206
- return lst
207
-
208
- # """ This takes input of company list and return summary of the company"""
209
- #21
210
- def summary_name(otp):
211
- names=[]
212
- title=otp
213
- for idx, i in enumerate(otp):
214
- results = serper_prod(i) # Call your function with the company name
215
- globals()[f'compi_{chr(65 + idx)}'] = results
216
- # print(i)
217
- # print(f'compi_{chr(65 + idx)}')
218
- names.append(f'compi_{chr(65 + idx)}')
219
- text_data = [globals()[name] for name in names]
220
- summ_data = [analysis_name(i) for i in text_data]
221
- cmpy_summ = AI_Company_Summary(" ".join(summ_data))
222
- return cmpy_summ
223
-
224
- # """ This takes inputs of compi summary and product summary and return summary of the company"""
225
- #1
226
- def analysis_prod(prod_summ,cmpy_summ):
227
- return AI_Analysis(prod_summ,cmpy_summ)
228
-
229
-
230
- # def main(name,email_id):
231
- # start_time = time.time()
232
- # prod_info = know_prod(name)
233
- # end_prd_anal = time.time()
234
- # print(prod_info)
235
- # print(f"Time taken to analyze the product: {end_prd_anal - start_time} seconds")
236
- # print('*****************************************************************')
237
- # # print(prod_info)
238
- # print(len(prod_info))
239
- # otp = compi_main(name)
240
- # end_compi = time.time()
241
- # print(len(otp))
242
- # print(f"Time taken to analyze the competitors: {end_compi - end_prd_anal} seconds")
243
- # print('*****************************************************************')
244
- # # print(otp)
245
- # summpop = summary_name(otp)
246
- # print(len(summpop))
247
- # end_time_summary = time.time()
248
- # print(f"Time taken to analyze the summary: {end_time_summary - end_compi} seconds")
249
- # print('*****************************************************************')
250
- # # print(summpop)
251
- # print('*****************************************************************')
252
- # analysis_total = analysis_prod(prod_info,summpop)
253
- # end_time = time.time()
254
- # print(f"Analysis time taken: {end_time - end_time_summary} seconds")
255
- # print('*****************************************************************')
256
- # print(f"Total time taken: {end_time - start_time} seconds")
257
- # print('*****************************************************************')
258
- # # print(analysis(prod_info,summpop))
259
- # #Send emails
260
- # send_email_gmail(email_id,analysis_total)
261
-
262
-
263
- # return start_time, end_prd_anal, end_compi, end_time_summary , end_time, analysis_total
264
-
265
- def time_calculator(start_time, end_time):
266
- time_in_seconds = end_time - start_time
267
- minutes = int(time_in_seconds // 60) # Get minutes
268
- seconds = int(time_in_seconds % 60)
269
- time_taken = f"{minutes} minutes and {seconds} seconds"
270
- return time_taken
271
-
272
- def send_email_gmail(receiver_email,markdown_content):
273
- sender_email = "srishnotebooks@gmail.com"
274
- sender_password = "zoge jatp yaib qtsz"# replace with the app password generated
275
- # receiver_email = "recipient_email@example.com"
276
- subject = "Product Analysis Report"
277
-
278
- # Create the email message container
279
- msg = MIMEMultipart('alternative')
280
- msg['From'] = sender_email
281
- msg['To'] = receiver_email
282
- msg['Subject'] = subject
283
-
284
- # Convert markdown to HTML
285
- html_content = markdown.markdown(markdown_content)
286
-
287
- # Attach the HTML content
288
- msg.attach(MIMEText(html_content, 'html'))
289
-
290
- try:
291
- # Set up the server using Gmail's SMTP
292
- server = smtplib.SMTP('smtp.gmail.com', 587)
293
- server.starttls() # Encrypt the connection
294
- server.login(sender_email, sender_password) # Use App Password instead of Gmail password
295
-
296
- # Send the email
297
- server.sendmail(sender_email, receiver_email, msg.as_string())
298
- server.quit()
299
-
300
- print("Email sent successfully!")
301
- return True
302
- except Exception as e:
303
- print(f"Error sending email: {str(e)}")
304
- return False
305
-
306
- # def main(name, email_id):
307
- # start_time = time.time()
308
-
309
- # # Display the process in Streamlit
310
- # st.write("Analyzing product information...")
311
- # prod_info = know_prod(name)
312
- # end_prd_anal = time.time()
313
-
314
- # # Show product info and analysis time
315
- # st.write("Product Information:")
316
- # st.write(prod_info)
317
- # st.write(f"Time taken to analyze the product: {end_prd_anal - start_time} seconds")
318
-
319
- # st.write('*****************************************************************')
320
- # st.write(f"Number of websites analyzed: {len(prod_info)}")
321
-
322
- # # Competitor analysis
323
- # st.write("Analyzing competitors...")
324
- # otp = compi_main(name)
325
- # end_compi = time.time()
326
-
327
- # st.write(f"Number of competitors found: {len(otp)}")
328
- # st.write(f"Time taken to analyze the competitors: {end_compi - end_prd_anal} seconds")
329
-
330
- # st.write('*****************************************************************')
331
-
332
- # # Summary analysis
333
- # st.write("Generating summary...")
334
- # summpop = summary_name(otp)
335
- # end_time_summary = time.time()
336
-
337
- # # st.write('## Compititors Summary')
338
- # # st.write(f"len(summpop)")
339
- # st.write(f"Time taken to generate summary: {end_time_summary - end_compi} seconds")
340
-
341
- # st.write('*****************************************************************')
342
-
343
- # # Total analysis
344
- # analysis_total = analysis_prod(prod_info, summpop)
345
- # end_time = time.time()
346
-
347
- # st.write("## Total Analysis")
348
- # st.write(analysis_total)
349
- # # st.write(f"Analysis time taken: {end_time - end_time_summary} seconds")
350
- # # st.write(f"Total time taken: {end_time - start_time} seconds")
351
-
352
- # st.write('*****************************************************************')
353
-
354
- # # Send email
355
- # send_email_gmail(email_id, analysis_total)
356
-
357
- # return start_time, end_prd_anal, end_compi, end_time_summary, end_time, analysis_total
358
- # def main(name, email_id):
359
- # start_time = time.time()
360
-
361
- # # Use container to group elements in a card-like style
362
- # with st.container():
363
- # st.markdown('---') # Horizontal line before the section
364
-
365
- # with st.spinner("Analyzing product information..."):
366
- # prod_info = know_prod(name)
367
- # end_prd_anal = time.time()
368
-
369
- # # Show product info and analysis time
370
- # st.write("### Product Information:")
371
- # st.write(prod_info)
372
- # st.write(f"Time taken to analyze the product: {end_prd_anal - start_time:.2f} seconds")
373
- # st.write(f"Number of websites analyzed: {len(prod_info)}")
374
-
375
- # st.markdown('---') # Horizontal line after the section
376
-
377
- # with st.container():
378
- # st.markdown('---') # Horizontal line before the section
379
-
380
- # with st.spinner("Analyzing competitors..."):
381
- # otp = compi_main(name)
382
- # end_compi = time.time()
383
-
384
- # st.write("### Competitor Analysis:")
385
- # st.write(f"Number of competitors found: {len(otp)}")
386
- # st.write(f"Time taken to analyze the competitors: {end_compi - end_prd_anal:.2f} seconds")
387
-
388
- # st.markdown('---') # Horizontal line after the section
389
-
390
- # with st.container():
391
- # st.markdown('---') # Horizontal line before the section
392
-
393
- # with st.spinner("Generating summary..."):
394
- # summpop = summary_name(otp)
395
- # end_time_summary = time.time()
396
-
397
- # st.write("### Summary Analysis:")
398
- # st.write(f"Time taken to generate summary: {end_time_summary - end_compi:.2f} seconds")
399
-
400
- # st.markdown('---') # Horizontal line after the section
401
-
402
- # with st.container():
403
- # st.markdown('---') # Horizontal line before the section
404
-
405
- # st.write("### Total Analysis:")
406
- # analysis_total = analysis_prod(prod_info, summpop)
407
- # st.write(analysis_total)
408
-
409
- # end_time = time.time()
410
-
411
- # st.write(f"Analysis time taken: {end_time - end_time_summary:.2f} seconds")
412
- # st.write(f"Total time taken: {end_time - start_time:.2f} seconds")
413
-
414
- # st.markdown('---') # Horizontal line after the section
415
-
416
- # # Email handling
417
- # if not email_id:
418
- # st.error("Email is not sent because it was not provided.", icon="🚫")
419
- # else:
420
- # # Call send_email_gmail and check if email is sent
421
- # if send_email_gmail(email_id, analysis_total):
422
- # st.success("Email sent successfully!", icon="✅")
423
- # else:
424
- # st.error("Failed to send email.", icon="❌")
425
-
426
- # return start_time, end_prd_anal, end_compi, end_time_summary, end_time, analysis_total
427
-
428
-
429
- # # Streamlit UI
430
- # st.title("Product and Competitor Analysis")
431
-
432
- # # Inputs from user
433
- # name = st.text_input("Enter the Product Name", "Cafe Coffee Day")
434
- # email_id = st.text_input("Enter your Email", "kapishrachamalla32@gmail.com")
435
-
436
- # if st.button("Start Analysis"):
437
- # t1, t2, t3, t4, t5, analysis = main(name, email_id)
438
-
439
- # # Time breakdown in minutes
440
- # st.write("Time taken to know about the product:", (t2 - t1) / 60, "minutes")
441
- # st.write("Time taken to know about the competitors:", (t3 - t2) / 60, "minutes")
442
- # st.write("Time taken to give analysis:", (t4 - t3) / 60, "minutes")
443
- # st.write("Time taken to generate summary:", (t5 - t4) / 60, "minutes")
444
- # st.write("Total time taken:", (t5 - t1) / 60, "minutes")
445
- #$%$%$
446
-
447
- def colored_container(color, content):
448
- st.markdown(
449
- f"""
450
- <div style="background-color: {color}; padding: 10px; border-radius: 5px;">
451
- {content}
452
- </div>
453
- """, unsafe_allow_html=True
454
- )
455
-
456
- def main(name, email_id):
457
-
458
- start_time = time.time()
459
- # colored_container("#A9DFBF", f"""
460
- # <h4 style="color: black;">Total Analysis:</h4>
461
- # <p style="color: black;">## Technical Analysis of McDonald's Chicken Big Mac</p>
462
- # <p style="color: black;"><strong>Market Standing:</strong><br>The Chicken Big Mac represents a strategic move by McDonald's to tap into the growing demand for chicken-based menu items in the fast-food industry. This trend is driven by consumer interest in healthier options, a wider variety of protein sources, and the growing popularity of chicken sandwiches in general.</p>
463
- # <p style="color: black;"><strong>Technical Strengths:</strong></p>
464
- # <ul style="color: black;">
465
- # <li>Leveraging Existing Brand Equity: The Chicken Big Mac benefits from the strong brand equity of the iconic Big Mac, ensuring immediate recognition and consumer interest.</li>
466
- # <li>Innovation: The use of tempura-battered chicken patties represents an innovative approach to chicken preparation, adding a unique flavor profile and appealing to a broader customer base.</li>
467
- # <li>Meeting Consumer Preferences: The sandwich addresses the growing demand for chicken-based options, demonstrating McDonald's ability to adapt to changing consumer preferences.</li>
468
- # </ul>
469
- # <p style="color: black;"><strong>Areas for Improvement:</strong></p>
470
- # <ul style="color: black;">
471
- # <li>Product Differentiation: While the Chicken Big Mac leverages the Big Mac's brand equity, it might benefit from more distinct features to differentiate itself further from other chicken sandwiches in the market.</li>
472
- # <li>Nutritional Profile: The tempura batter might raise concerns about the nutritional profile of the sandwich, potentially impacting its appeal to health-conscious consumers.</li>
473
- # <li>Marketing and Promotion: McDonald's needs to develop a comprehensive marketing strategy to effectively promote the Chicken Big Mac and highlight its unique selling points.</li>
474
- # </ul>
475
- # <p style="color: black;"><strong>Actionable Insights:</strong></p>
476
- # <ul style="color: black;">
477
- # <li>Enhance Differentiation: Consider adding unique ingredients or flavor profiles to further distinguish the Chicken Big Mac from other offerings.</li>
478
- # <li>Promote Healthier Options: Explore lighter batter options or create a "healthier" version of the Chicken Big Mac with grilled chicken and lighter sauces.</li>
479
- # <li>Targeted Marketing: Focus marketing efforts on highlighting the innovation and appeal of the Chicken Big Mac, reaching target demographics interested in chicken-based options.</li>
480
- # </ul>
481
- # <p style="color: black;"><strong>Comparison to Competitors:</strong></p>
482
- # <p style="color: black;">McDonald's needs to analyze the competitive landscape of chicken sandwiches. This includes identifying key competitors like Chick-fil-A, Wendy's, and Popeyes, and comparing their offerings in terms of flavor profiles, ingredients, and marketing strategies. This analysis will help McDonald's identify potential gaps and opportunities for differentiation.</p>
483
- # <p style="color: black;"><strong>Opportunities for Market Leadership:</strong></p>
484
- # <ul style="color: black;">
485
- # <li>Focus on Premium Quality: McDonald's can leverage its brand reputation to introduce a premium chicken sandwich with higher-quality ingredients and a unique flavor profile.</li>
486
- # <li>Create a Signature Chicken Experience: Develop a distinctive chicken sandwich experience that sets it apart from competitors, emphasizing its unique taste and texture.</li>
487
- # <li>Promote Chicken Innovation: Leverage the Chicken Big Mac's launch to position McDonald's as a leader in chicken innovation, showcasing a commitment to meeting evolving consumer demands.</li>
488
- # </ul>
489
- # <p style="color: black;"><strong>Conclusion:</strong></p>
490
- # <p style="color: black;">The Chicken Big Mac holds significant potential for McDonald's to expand its market share in the growing chicken sandwich segment. By addressing its weaknesses, leveraging its strengths, and actively monitoring competitive offerings, McDonald's can create a successful product that drives sales and profitability.</p>
491
- # <p style="color: black;">Analysis time taken: 4.51 seconds</p>
492
- # <p style="color: black;">Total time taken: 368.86 seconds</p>
493
- # """)
494
-
495
- # Product information section
496
- with st.container():
497
- st.markdown('---') # Horizontal line before the section
498
-
499
- with st.spinner("Analyzing product information..."):
500
- prod_info = know_prod(name)
501
- end_prd_anal = time.time()
502
-
503
- # Display product info in a colored container
504
- # colored_container("#D6EAF8", f"""
505
- # <h4>Product Information:</h4>
506
- # <p>{prod_info}</p>
507
- # <p>Time taken to analyze the product: {end_prd_anal - start_time:.2f} seconds</p>
508
- # <p>Number of websites analyzed: {len(prod_info)}</p>
509
- # """)
510
-
511
- st.write("### Product Information:")
512
- st.write(prod_info)
513
- # st.write(f"Time taken to analyze the product: {end_prd_anal - start_time:.2f} seconds")
514
- st.write(f"Number of Articles analyzed: {len(prod_info)}")
515
- st.markdown('---') # Horizontal line after the section
516
-
517
- # Competitor analysis section
518
- with st.container():
519
- st.markdown('---') # Horizontal line before the section
520
-
521
- with st.spinner("Analyzing competitors..."):
522
- otp = compi_main(name)
523
- end_compi = time.time()
524
-
525
- # Display competitor info in a different colored container
526
- # colored_container("#F9E79F", f"""
527
- # <h4>Competitor Analysis:</h4>
528
- # <p>Number of competitors found: {len(otp)}</p>
529
- # <p>Time taken to analyze the competitors: {end_compi - end_prd_anal:.2f} seconds</p>
530
- # """)
531
-
532
- st.write("### Competitor Analysis:")
533
- st.write(f"Number of potential competitors found: {len(otp)}")
534
- # st.write(f"The Competitors are: \n {otp}")
535
- # st.write(f"Time taken to analyze the competitors: {end_compi - end_prd_anal:.2f} seconds")
536
-
537
- # st.markdown('---') # Horizontal line after the section
538
-
539
- # Summary analysis section
540
- # with st.container():
541
- # st.markdown('---') # Horizontal line before the section
542
-
543
- with st.spinner("Generating summary..."):
544
- summpop = summary_name(otp)
545
- end_time_summary = time.time()
546
-
547
- # Display summary in a different color container
548
- # colored_container("#A9DFBF", f"""
549
- # <h4>Summary Analysis:</h4>
550
- # <p>Time taken to generate summary: {end_time_summary - end_compi:.2f} seconds</p>
551
- # """)
552
-
553
- st.write("### Summary Analysis:")
554
- st.write(summpop)
555
- # st.write(f"Time taken to generate summary: {end_time_summary - end_compi:.2f} seconds")
556
-
557
- st.markdown('---') # Horizontal line after the section
558
-
559
- # Total analysis section
560
- with st.container():
561
- st.markdown('---') # Horizontal line before the section
562
-
563
- # Display total analysis in another color container
564
- analysis_total = analysis_prod(prod_info, summpop)
565
- end_time = time.time()
566
- # colored_container("#F5B7B1", f"""
567
- # <h4>Total Analysis:</h4>
568
- # <p>{analysis_total}</p>
569
- # <p>Analysis time taken: {end_time - end_time_summary:.2f} seconds</p>
570
- # <p>Total time taken: {end_time - start_time:.2f} seconds</p>
571
- # """)
572
-
573
- # st.write("### Total Analysis:")
574
- st.write(analysis_total)
575
-
576
- st.markdown('---') # Horizontal line after the section
577
-
578
- # Email handling
579
- if not email_id:
580
- st.error("Email is not sent because it was not provided.", icon="🚫")
581
- else:
582
- # Call send_email_gmail and check if email is sent
583
- if send_email_gmail(email_id, analysis_total):
584
- st.success("Email sent successfully!", icon="✅")
585
- else:
586
- st.error("Failed to send email.", icon="❌")
587
-
588
- return start_time, end_prd_anal, end_compi, end_time_summary, end_time, analysis_total
589
-
590
-
591
- # Streamlit UI
592
- st.title("Market Mind 🧠")
593
- # st.subheader("Empowering You with ")
594
- st.markdown("<h7>Real-Time Market Intelligence</h1>", unsafe_allow_html=True)
595
- # Sidebar for developer profiles and hackathon info
596
- st.sidebar.markdown(
597
- """
598
- <h1 style='color: #ff0000;'>🚀 Hackathon Project</h1>
599
- """,
600
- unsafe_allow_html=True
601
- )
602
- st.sidebar.markdown("Welcome to the MarketMind project, developed for the hackathon to showcase AI power in the product and competitor analysis. 🚀")
603
-
604
- # Add some icons/emojis to make it look more engaging
605
- st.sidebar.markdown("### 🔧 Project Features")
606
- # st.sidebar.markdown("- Analyze product details using OpenFoodFacts API.")
607
- st.sidebar.markdown("- Real-Time Market Intelligence: Offers real-time data updates for informed decision-making")
608
- st.sidebar.markdown("- AI and Machine Learning: Helps analyze competitors and suggests improvement strategies based on data.")
609
-
610
- # Developer details with LinkedIn links
611
- st.sidebar.markdown("### 👨‍💻 Developers")
612
- st.sidebar.markdown("[Srish](https://www.linkedin.com/in/srishrachamalla/) - AI/ML Developer")
613
- st.sidebar.markdown("[Sai Teja](https://www.linkedin.com/in/saiteja-pallerla-668734225/) - Data Analyst")
614
-
615
- # Add expander sections for additional content
616
- with st.sidebar.expander("ℹ About MarketMind"):
617
- st.write("MarketMind is a platform focused on providing advanced data analytics, market intelligence, and AI-driven insights for businesses, investors, and market professionals. Its solutions are aimed at helping organizations make informed decisions by analyzing vast amounts of market data, consumer behavior, and industry trends in real-time")
618
-
619
- with st.sidebar.expander("📚 Useful Resources"):
620
- st.write("[Google Gemini AI Documentation](https://ai.google.dev/gemini-api/docs)")
621
- st.write("[Streamlit Documentation](https://docs.streamlit.io/)")
622
- st.write("[Groq Documentation](https://console.groq.com/docs/quickstart)")
623
-
624
- # Add progress indicator for hackathon phases or development stages
625
- st.sidebar.markdown("### ⏳ Hackathon Progress")
626
- st.sidebar.progress(0.99) # Set progress level (0 to 1)
627
-
628
- # Sidebar footer with final notes
629
- st.sidebar.markdown("---")
630
- st.sidebar.markdown(
631
- """
632
- <div style="text-align: center; font-size: 0.85em;">
633
- Developed by Srish & Sai Teja • Powered by Google Gemini AI
634
- </div>
635
- """, unsafe_allow_html=True
636
- )
637
- # Inputs from user
638
- name = st.text_input("Enter the Product Name", "Cafe Coffee Day")
639
- email_id = st.text_input("Enter your Email", "")
640
-
641
- if st.button("Start Analysis"):
642
- t1, t2, t3, t4, t5, analysis = main(name, email_id)
643
-
644
- # # Time breakdown in minutes
645
- # st.write("### Time Breakdown (in minutes)")
646
- # st.write(f"Time taken to analyze the product: {(t2 - t1) / 60:.2f} minutes")
647
- # st.write(f"Time taken to analyze competitors: {(t3 - t2) / 60:.2f} minutes")
648
- # st.write(f"Time taken to generate summary: {(t4 - t3) / 60:.2f} minutes")
649
- # st.write(f"Time taken for total analysis: {(t5 - t1) / 60:.2f} minutes")
650
- # Time breakdown in minutes
651
- st.write("### Time Breakdown (in minutes)")
652
-
653
- # Define colors for each breakdown
654
- total_color = "#FF5733" # Red
655
- competitors_color = "#33C1FF" # Blue
656
- summary_color = "#75FF33" # Green
657
- product_color = "#FF33B5" # Pink
658
-
659
- # Display each time taken in different colors
660
- # Get seconds
661
- st.markdown(f"<p style='color: {product_color};'>Time taken to analyze the product: {time_calculator(t2 - t1)}</p>", unsafe_allow_html=True)
662
- st.markdown(f"<p style='color: {competitors_color};'>Time taken to analyze competitors: {time_calculator(t3 - t2)} minutes</p>", unsafe_allow_html=True)
663
- st.markdown(f"<p style='color: {summary_color};'>Time taken to generate summary: {time_calculator(t4 - t3)} minutes</p>", unsafe_allow_html=True)
664
- st.markdown(f"<p style='color: {total_color};'>Time taken for total analysis: {time_calculator(t5 - t1)} minutes</p>", unsafe_allow_html=True)
665
- st.markdown("---")
666
- st.markdown("""
667
- <div style="text-align: center; font-size: 0.9em;">
668
- <p><i>MarketMind</i> was developed for a hackathon using <b>Streamlit</b> to showcase AI power in product and competitor analysis.</p>
669
- <p>Developed by Srish & Sai Teja </p>
670
- </div>
671
- """, unsafe_allow_html=True)
672
- # if __name__ == "__main__":
673
- # t1,t2,t3,t4,t5,analysis = main('Cafe Coffee Day',"kapishrachamalla32@gmail.com")
674
- # print("time taken to Know about the product: ", (t2-t1)/60)
675
- # print("time taken to Know about the competitors: ", (t3-t2)/60)
676
- # print("time taken to Know about the give analysis: ", (t4-t3)/60)
677
- # print("time taken to Know about the summary: ", (t5-t4)/60)
678
- # print("total time taken: ", (t5-t1)/60)
679
-
680
-
681
- # import ast
682
- # import requests
683
- # import json
684
- # import time
685
- # import streamlit as st
686
- # from duckduckgo_search import DDGS
687
- # import google.generativeai as genai
688
- # from groq import Groq
689
- # import smtplib
690
- # from email.mime.text import MIMEText
691
- # from email.mime.multipart import MIMEMultipart
692
- # import markdown
693
-
694
- # # Configure generative AI API key
695
- # genai.configure(api_key='AIzaSyCootL_jwKI3YDb6cKRJV-Ad0N4oKlLXXE')
696
- # client = Groq(api_key='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')
697
-
698
- # # Function definitions as in your original code
699
-
700
- # def jina(url):
701
- # base_url= "https://r.jina.ai//"
702
- # url=base_url+url
703
- # response=requests.get(url)
704
- # return response.text
705
-
706
- # def groq_inference(query):
707
- # completion = client.chat.completions.create(
708
- # model="llama3-groq-70b-8192-tool-use-preview",
709
- # messages=[{"role": "user", "content": query}],
710
- # temperature=0,
711
- # max_tokens=2040,
712
- # top_p=0.65,
713
- # stop=None,
714
- # )
715
- # return completion.choices[0].message.content
716
-
717
- # def serper_prod(company):
718
- # url = "https://google.serper.dev/news"
719
- # payload = json.dumps({"q": f"{company} info"})
720
- # headers = {
721
- # 'X-API-KEY': '7d6a39f71072f99cd421dbdd6cfebc73e2a66a07',
722
- # 'Content-Type': 'application/json'
723
- # }
724
- # response = requests.request("POST", url, headers=headers, data=payload)
725
- # return json.loads(response.text)
726
-
727
- # def serper_compi(company):
728
- # url = "https://google.serper.dev/search"
729
- # payload = json.dumps({"q": f"{company} competitors."})
730
- # headers = {
731
- # 'X-API-KEY': '7d6a39f71072f99cd421dbdd6cfebc73e2a66a07',
732
- # 'Content-Type': 'application/json'
733
- # }
734
- # response = requests.request("POST", url, headers=headers, data=payload)
735
- # return json.loads(response.text)
736
-
737
- # def AI_Search_compi(text, titles, name):
738
- # ans = groq_inference(f"""Summarize the text of the articles titles are {titles} and don't remove the important terms about products or applications which should help in knowing about the competitors for a company {name}. The data is: {text}""")
739
- # return ans
740
-
741
- # def AI_Product_Analysis(text):
742
- # ans = DDGS().chat("Analyze the products mentioned in the following news article in 400 words or fewer. Focus on their features, market relevance, and potential impact for a company's market planning: " + text, model='claude-3-haiku')
743
- # return ans
744
-
745
- # def AI_Product_Summary(news_summaries, product):
746
- # ans = groq_inference(f"""Create a comprehensive summary of the product {product} based on the following summaries of 10 or fewer news articles. Ensure no important product details are lost, and you may add text from the articles as well: {news_summaries}""")
747
- # return ans
748
-
749
- # def AI_Search_extract_cmpy(text):
750
- # prompt = """You will be given a dynamic text that summarizes key products, applications, and comparisons from articles. Your task is to extract relevant product names from the text and generate a list of search queries suitable for a search API. Don't give more than five names in the list. Output Format: ['company - product name', 'company - product name', 'product name', ...]."""
751
- # ans = DDGS().chat(prompt + "The text is \n" + text, model='claude-3-haiku')
752
- # print(ans)
753
- # return ast.literal_eval(ans)
754
-
755
- # def AI_Company_Summary(news_summaries):
756
- # ans = DDGS().chat("Analyze the following combined summaries about multiple products. Provide a detailed summary of each product individually, clearly outlining their features, market relevance, and competitive advantages: " + news_summaries, model='claude-3-haiku')
757
- # return ans
758
-
759
- # def AI_Product_Summary_prod(news_summaries):
760
- # # combined_summaries = " ".join(news_summaries)
761
- # ans = groq_inference(f"""Create a comprehensive summary of the product based on the following summaries of 10 or fewer news articles. Ensure no important product details are lost and remember that these are form the news articles so you may have add text also : """ + news_summaries)
762
- # # ans = DDGS().chat("Create a comprehensive summary of the product based on the following summaries of 10 or fewer news articles. Ensure no important product details are lost: " + news_summaries, model='gpt-4o-mini')
763
-
764
- # def AI_Analysis(Product_analysis, Compitetiors_analysis):
765
- # prompt = Compitetiors_analysis + "Product Information: \n " + Product_analysis
766
- # system_prompt = f"""Analyze the following competitor and product details. Provide a technical analysis of each product, focusing on its market standing, technical strengths, and areas for improvement. Compare the product with competitors, identifying gaps and opportunities for differentiation: Competitors: {prompt}"""
767
-
768
- # model = genai.GenerativeModel(model_name="gemini-1.5-flash")
769
- # response = model.generate_content(system_prompt)
770
- # return response.text
771
-
772
- # def send_email_gmail(receiver_email,markdown_content):
773
- # sender_email = "srishnotebooks@gmail.com"
774
- # sender_password = "zoge jatp yaib qtsz"# replace with the app password generated
775
- # # receiver_email = "recipient_email@example.com"
776
- # subject = "Product Analysis Report"
777
-
778
- # # Create the email message container
779
- # msg = MIMEMultipart('alternative')
780
- # msg['From'] = sender_email
781
- # msg['To'] = receiver_email
782
- # msg['Subject'] = subject
783
-
784
- # # Convert markdown to HTML
785
- # html_content = markdown.markdown(markdown_content)
786
-
787
- # # Attach the HTML content
788
- # msg.attach(MIMEText(html_content, 'html'))
789
-
790
- # try:
791
- # # Set up the server using Gmail's SMTP
792
- # server = smtplib.SMTP('smtp.gmail.com', 587)
793
- # server.starttls() # Encrypt the connection
794
- # server.login(sender_email, sender_password) # Use App Password instead of Gmail password
795
-
796
- # # Send the email
797
- # server.sendmail(sender_email, receiver_email, msg.as_string())
798
- # server.quit()
799
-
800
- # print("Email sent successfully!")
801
- # except Exception as e:
802
- # print(f"Error sending email: {str(e)}")
803
-
804
- # # """ This takes input of company and return summary of the company"""
805
- # def analysis_name(text):
806
- # compi_urls = [i['link'] for i in text['news']][0:4]
807
- # print(compi_urls)
808
- # text = [jina(url) for url in compi_urls]
809
- # ans = ' '.join(AI_Product_Analysis(i[:8000]) for i in text if len(i)>1500)
810
- # # time.sleep(25)
811
- # summ = AI_Product_Summary_prod(ans[:21000])
812
- # return summ
813
-
814
- # # """" This is for knowing about the Product"""
815
- # # 11
816
- # # groq
817
- # def know_prod(name):
818
- # ser = serper_prod(name)
819
- # compi_urls = [i['link'] for i in ser['news']]
820
- # text = [jina(url) for url in compi_urls]
821
- # ans = ' '.join(AI_Product_Analysis(i[:8000]) for i in text if len(i)>1500)
822
- # summ = AI_Product_Summary(ans[:20000],name)
823
- # return summ
824
-
825
- # # """ This takes input of company and return list of the compi"""
826
- # # 11
827
- # def compi_main(name):
828
- # ret = serper_compi(name)
829
- # compi_urls = [i['link'] for i in ret['organic']]
830
- # title_list= [i['title'] for i in ret['organic']]
831
- # text = [jina(url) for url in compi_urls]
832
- # ans = ' '.join(AI_Search_compi(i[:8000],title_list,name) for i in text if len(i)>1500)
833
- # lst = AI_Search_extract_cmpy(ans)
834
- # return lst
835
-
836
- # # """ This takes input of company list and return summary of the company"""
837
- # #21
838
- # def summary_name(otp):
839
- # names=[]
840
- # title=otp
841
- # for idx, i in enumerate(otp):
842
- # results = serper_prod(i) # Call your function with the company name
843
- # globals()[f'compi_{chr(65 + idx)}'] = results
844
- # # print(i)
845
- # # print(f'compi_{chr(65 + idx)}')
846
- # names.append(f'compi_{chr(65 + idx)}')
847
- # text_data = [globals()[name] for name in names]
848
- # summ_data = [analysis_name(i) for i in text_data]
849
- # cmpy_summ = AI_Company_Summary(" ".join(summ_data))
850
- # return cmpy_summ
851
-
852
- # # """ This takes inputs of compi summary and product summary and return summary of the company"""
853
- # #1
854
- # def analysis_prod(prod_summ,cmpy_summ):
855
- # return AI_Analysis(prod_summ,cmpy_summ)
856
-
857
- # # Streamlit Interface
858
-
859
- # def main():
860
- # st.title("Product and Competitor Analysis Tool")
861
-
862
- # # Input company name
863
- # company_name = st.text_input("Enter Company Name", value="Sample Company")
864
- # email = st.text_input("Enter your email (Optional)")
865
-
866
- # # Perform Analysis
867
- # if st.button("Analyze"):
868
- # start_time = time.time()
869
-
870
- # st.write(f"Analyzing {company_name}...")
871
-
872
- # # Analyze product
873
- # prod_info = know_prod(company_name)
874
- # st.write("### Product Information:")
875
- # st.write(prod_info)
876
-
877
- # end_prd_anal = time.time()
878
- # st.write(f"Time taken to analyze the product: {(end_prd_anal - start_time)/60} Mins")
879
-
880
- # # Analyze competitors
881
- # st.write("### Competitor Information:")
882
- # otp = compi_main(company_name)
883
- # print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$')
884
- # print(otp)
885
- # st.write(otp)
886
- # end_compi = time.time()
887
- # st.write(f"Time taken to analyze the competitors: {end_compi - end_prd_anal} seconds")
888
-
889
- # # Summary
890
- # st.write("### Summary:")
891
- # cmpy_summ = summary_name(otp)
892
- # st.write(cmpy_summ)
893
-
894
- # end_time_summary = time.time()
895
- # st.write(f"Time taken to generate summary: {end_time_summary - end_compi} seconds")
896
-
897
- # analysis_total = analysis_prod(prod_info,cmpy_summ)
898
- # st.write("### Analysis:" + analysis_total)
899
- # # Send via email (Optional)
900
- # if email:
901
- # send_email_gmail(email, analysis_total)
902
- # st.write(f"Sending analysis to {email}...")
903
- # # (Implement email sending logic here)
904
- # # ...
905
-
906
- # if __name__ == "__main__":
907
- # main()
 
1
+ import ast
2
+ import requests
3
+ import json
4
+ from duckduckgo_search import DDGS
5
+ import google.generativeai as genai
6
+ from groq import Groq
7
+ import time
8
+ import smtplib
9
+ from email.mime.text import MIMEText
10
+ from email.mime.multipart import MIMEMultipart
11
+ import markdown
12
+ import streamlit as st
13
+
14
+ genai.configure(api_key='AIzaSyCootL_jwKI3YDb6cKRJV-Ad0N4oKlLXXE')
15
+ client = Groq(api_key='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')
16
+
17
+ # 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
18
+
19
+ def jina(url):
20
+ base_url= "https://r.jina.ai//"
21
+ url=base_url+url
22
+ response=requests.get(url)
23
+ return response.text
24
+
25
+ def groq_inference(query):
26
+
27
+ # client = Groq()
28
+ completion = client.chat.completions.create(
29
+ model="llama3-groq-70b-8192-tool-use-preview",
30
+ messages=[
31
+ {
32
+ "role": "user",
33
+ "content": query
34
+ }
35
+ ],
36
+ temperature=0,
37
+ max_tokens=2040,
38
+ top_p=0.65,
39
+ # stream=True,
40
+ stop=None,
41
+ )
42
+
43
+ # for chunk in completion:
44
+ # print(chunk.choices[0].delta.content or "", end="")
45
+ # return completion.choices[0].delta.content
46
+ return completion.choices[0].message.content
47
+
48
+ #Know about product
49
+ def serper_prod(company):
50
+ url = "https://google.serper.dev/news"
51
+
52
+ payload = json.dumps({
53
+ "q": f"{company} info",
54
+ })
55
+ headers = {
56
+ 'X-API-KEY': '7d6a39f71072f99cd421dbdd6cfebc73e2a66a07',
57
+ 'Content-Type': 'application/json'
58
+ }
59
+
60
+ response = requests.request("POST", url, headers=headers, data=payload)
61
+
62
+ return json.loads(response.text)
63
+
64
+
65
+ #Know about the competiton\competitiors
66
+ def serper_compi(company):
67
+ url = "https://google.serper.dev/search"
68
+
69
+ payload = json.dumps({
70
+ "q": f"{company} competitors.",
71
+ })
72
+ headers = {
73
+ 'X-API-KEY': '7d6a39f71072f99cd421dbdd6cfebc73e2a66a07',
74
+ 'Content-Type': 'application/json'
75
+ }
76
+
77
+ response = requests.request("POST", url, headers=headers, data=payload)
78
+
79
+ return json.loads(response.text)
80
+
81
+ def AI_Search_compi(text):
82
+ ans = DDGS().chat("Summarize the text and dont remove the important terms about products or applications which should be helped for planning market for a company " + text, model='claude-3-haiku')
83
+ return ans
84
+
85
+ def AI_Search_compi(text,titles,name):
86
+ ans = groq_inference(f"""Summarize the text of the articles titles are {titles} and dont remove the important terms about products or applications which should be helped for knowing about the compititors for a company {name} and the data is: {text}""")
87
+ return ans
88
+
89
+ def AI_Product_Analysis(text):
90
+ ans = DDGS().chat("Analyze the products mentioned in the following news article in 400 words or fewer. Focus on their features, market relevance, and potential impact for a company's market planning: " + text, model='claude-3-haiku')
91
+ return ans
92
+
93
+ def AI_Product_Summary(news_summaries,product):
94
+ # combined_summaries = " ".join(news_summaries)
95
+ ans = groq_inference(f"""Create a comprehensive summary of the product {product} based on the following summaries of 10 or fewer news articles. Ensure no important product details are lost and remember that these are form the news articles so you may have add text also : """ + news_summaries)
96
+ # ans = DDGS().chat("Create a comprehensive summary of the product based on the following summaries of 10 or fewer news articles. Ensure no important product details are lost: " + news_summaries, model='gpt-4o-mini')
97
+ return ans
98
+
99
+ def AI_Product_Summary_prod(news_summaries):
100
+ # combined_summaries = " ".join(news_summaries)
101
+ ans = groq_inference(f"""Create a comprehensive summary of the product based on the following summaries of 10 or fewer news articles. Ensure no important product details are lost and remember that these are form the news articles so you may have add text also : """ + news_summaries)
102
+ # ans = DDGS().chat("Create a comprehensive summary of the product based on the following summaries of 10 or fewer news articles. Ensure no important product details are lost: " + news_summaries, model='gpt-4o-mini')
103
+ return ans
104
+ # AI_Product_Summary_prod
105
+
106
+ def AI_Search_extract_cmpy(text):
107
+ # prompt = """You will be given a dynamic text that summarizes key products, applications, and comparisons from articles about VR headsets. Your task is to extract relevant product names from the text and generate a list of search queries suitable for a search API.Don't give more than five names in the list.
108
+
109
+ # Output Format:
110
+
111
+ # The output should be a list in the following format:
112
+ # ['company - product name', 'company - product name', 'product name', ...]
113
+ # If the company name is unknown, only include the product name without the company name.
114
+ # Do not include any introductory or explanatory text in the output; provide only the list in brackets.
115
+ # Input Format:
116
+
117
+ # The input will be a summary text containing product names, features, and key points."""
118
+ #$#$#$#$#
119
+ prompt = """You will be given a dynamic text that summarizes key products, applications, and comparisons from articles about VR headsets. Your task is to extract relevant product names from the text and generate a list of search queries suitable for a search API. Don't give more than five names in the list.
120
+ Output Format:
121
+
122
+ Provide only the list in the following format, without any explanatory or introductory text:
123
+ ['company - product name', 'company - product name', 'product name', ...]
124
+ and remember dont give like this ['McDonald's - Big Mac'] becauses this will be given to pyhton this return error.
125
+ If the company name is unknown, only include the product name without the company name."""
126
+ # prompt = """You will be given a dynamic text that summarizes key products, applications, and comparisons from articles about VR headsets. Your task is to extract relevant product names from the text and generate a list of search queries suitable for a search API. Don't give more than five names in the list.Dont repeat the company names and please dont add single quotes or any other special characters that will be given error for pyhton to read.
127
+ # Output Format:
128
+
129
+ # Provide only the list in the following format, without any explanatory or introductory text:
130
+ # ['company - product name', 'company - product name', 'product name', ...]
131
+ # and remember dont give like this ['McDonald's - Big Mac'] becauses this will be given to pyhton this return error.
132
+ # If the company name is unknown, only include the product name without the company name."""
133
+
134
+ # ans = groq_inference(prompt + f"the text is: {text}")
135
+ ans = DDGS().chat(prompt+"the text is \n" + text, model='claude-3-haiku')
136
+ return ast.literal_eval(ans)
137
+
138
+
139
+ def AI_Company_Summary(news_summaries):
140
+ ans = DDGS().chat("Analyze the following combined summaries about multiple products. Provide a detailed summary of each product individually, clearly outlining their features, market relevance, and competitive advantages, so this information can be used to analyze competitor products: " + news_summaries, model='claude-3-haiku')
141
+ return ans
142
+
143
+ def AI_Analysis(Product_analysis,Compitetiors_analysis):
144
+ prompt = Compitetiors_analysis + "Product Information: \n " + Product_analysis
145
+ system_prompt = "Analyze the following competitor and product details. Provide a thorough technical analysis of each product, focusing on its market standing, technical strengths, and areas for improvement. Offer actionable insights on how the product can be enhanced to increase sales and profitability. Compare the product with competitors, identifying gaps and opportunities for differentiation and market leadership and remember that give the analyis of the compitiors only if they are related else dont give it: " + "Competitors: \n "+ prompt,
146
+
147
+ # ans = DDGS().chat(prompt, model='claude-3-haiku')
148
+ # if len(prompt) > 22000:
149
+ # prompt = prompt[:22000]
150
+ # ans = DDGS().chat(
151
+ # "Analyze the following competitor and product details. Provide a thorough technical analysis of each product, focusing on its market standing, technical strengths, and areas for improvement. Offer actionable insights on how the product can be enhanced to increase sales and profitability. Compare the product with competitors, identifying gaps and opportunities for differentiation and market leadership: " + "Competitors: \n "
152
+ # + prompt,
153
+ # model='claude-3-haiku')
154
+ model = genai.GenerativeModel(model_name="gemini-1.5-flash")
155
+ response = model.generate_content(system_prompt)
156
+
157
+ return response.text
158
+
159
+ def AI_Analysis(Product_analysis,Compitetiors_analysis):
160
+ prompt = Compitetiors_analysis + "Product Information: \n " + Product_analysis
161
+ system_prompt = "Analyze the following competitor and product details. Provide a thorough technical analysis of each product, focusing on its market standing, technical strengths, and areas for improvement. Offer actionable insights on how the product can be enhanced to increase sales and profitability. Compare the product with competitors, identifying gaps and opportunities for differentiation and market leadership and remember that give the analyis of the compitiors only if they are related else dont give it: " + "Competitors: \n "+ prompt,
162
+
163
+ # ans = DDGS().chat(prompt, model='claude-3-haiku')
164
+ # if len(prompt) > 22000:
165
+ # prompt = prompt[:22000]
166
+ # ans = DDGS().chat(
167
+ # "Analyze the following competitor and product details. Provide a thorough technical analysis of each product, focusing on its market standing, technical strengths, and areas for improvement. Offer actionable insights on how the product can be enhanced to increase sales and profitability. Compare the product with competitors, identifying gaps and opportunities for differentiation and market leadership: " + "Competitors: \n "
168
+ # + prompt,
169
+ # model='claude-3-haiku')
170
+ model = genai.GenerativeModel(model_name="gemini-1.5-flash")
171
+ response = model.generate_content(system_prompt)
172
+
173
+ return response.text
174
+
175
+ # """ This takes input of company and return summary of the company"""
176
+ def analysis_name(text):
177
+ compi_urls = [i['link'] for i in text['news']][0:4]
178
+ print(compi_urls)
179
+ text = [jina(url) for url in compi_urls]
180
+ ans = ' '.join(AI_Product_Analysis(i[:8000]) for i in text if len(i)>1500)
181
+ # time.sleep(25)
182
+ summ = AI_Product_Summary_prod(ans[:21000])
183
+ return summ
184
+
185
+
186
+ # """" This is for knowing about the Product"""
187
+ # 11
188
+ # groq
189
+ def know_prod(name):
190
+ ser = serper_prod(name)
191
+ compi_urls = [i['link'] for i in ser['news']]
192
+ text = [jina(url) for url in compi_urls]
193
+ ans = ' '.join(AI_Product_Analysis(i[:8000]) for i in text if len(i)>1500)
194
+ summ = AI_Product_Summary(ans[:20000],name)
195
+ return summ
196
+
197
+ # """ This takes input of company and return list of the compi"""
198
+ # 11
199
+ def compi_main(name):
200
+ ret = serper_compi(name)
201
+ compi_urls = [i['link'] for i in ret['organic']]
202
+ title_list= [i['title'] for i in ret['organic']]
203
+ text = [jina(url) for url in compi_urls]
204
+ ans = ' '.join(AI_Search_compi(i[:8000],title_list,name) for i in text if len(i)>1500)
205
+ lst = AI_Search_extract_cmpy(ans)
206
+ return lst
207
+
208
+ # """ This takes input of company list and return summary of the company"""
209
+ #21
210
+ def summary_name(otp):
211
+ names=[]
212
+ title=otp
213
+ for idx, i in enumerate(otp):
214
+ results = serper_prod(i) # Call your function with the company name
215
+ globals()[f'compi_{chr(65 + idx)}'] = results
216
+ # print(i)
217
+ # print(f'compi_{chr(65 + idx)}')
218
+ names.append(f'compi_{chr(65 + idx)}')
219
+ text_data = [globals()[name] for name in names]
220
+ summ_data = [analysis_name(i) for i in text_data]
221
+ cmpy_summ = AI_Company_Summary(" ".join(summ_data))
222
+ return cmpy_summ
223
+
224
+ # """ This takes inputs of compi summary and product summary and return summary of the company"""
225
+ #1
226
+ def analysis_prod(prod_summ,cmpy_summ):
227
+ return AI_Analysis(prod_summ,cmpy_summ)
228
+
229
+
230
+ # def main(name,email_id):
231
+ # start_time = time.time()
232
+ # prod_info = know_prod(name)
233
+ # end_prd_anal = time.time()
234
+ # print(prod_info)
235
+ # print(f"Time taken to analyze the product: {end_prd_anal - start_time} seconds")
236
+ # print('*****************************************************************')
237
+ # # print(prod_info)
238
+ # print(len(prod_info))
239
+ # otp = compi_main(name)
240
+ # end_compi = time.time()
241
+ # print(len(otp))
242
+ # print(f"Time taken to analyze the competitors: {end_compi - end_prd_anal} seconds")
243
+ # print('*****************************************************************')
244
+ # # print(otp)
245
+ # summpop = summary_name(otp)
246
+ # print(len(summpop))
247
+ # end_time_summary = time.time()
248
+ # print(f"Time taken to analyze the summary: {end_time_summary - end_compi} seconds")
249
+ # print('*****************************************************************')
250
+ # # print(summpop)
251
+ # print('*****************************************************************')
252
+ # analysis_total = analysis_prod(prod_info,summpop)
253
+ # end_time = time.time()
254
+ # print(f"Analysis time taken: {end_time - end_time_summary} seconds")
255
+ # print('*****************************************************************')
256
+ # print(f"Total time taken: {end_time - start_time} seconds")
257
+ # print('*****************************************************************')
258
+ # # print(analysis(prod_info,summpop))
259
+ # #Send emails
260
+ # send_email_gmail(email_id,analysis_total)
261
+
262
+
263
+ # return start_time, end_prd_anal, end_compi, end_time_summary , end_time, analysis_total
264
+
265
+ def time_calculator(start_time, end_time):
266
+ time_in_seconds = end_time - start_time
267
+ minutes = int(time_in_seconds // 60) # Get minutes
268
+ seconds = int(time_in_seconds % 60)
269
+ time_taken = f"{minutes} minutes and {seconds} seconds"
270
+ return time_taken
271
+
272
+ def send_email_gmail(receiver_email,markdown_content):
273
+ sender_email = "srishnotebooks@gmail.com"
274
+ sender_password = "zoge jatp yaib qtsz"# replace with the app password generated
275
+ # receiver_email = "recipient_email@example.com"
276
+ subject = "Product Analysis Report"
277
+
278
+ # Create the email message container
279
+ msg = MIMEMultipart('alternative')
280
+ msg['From'] = sender_email
281
+ msg['To'] = receiver_email
282
+ msg['Subject'] = subject
283
+
284
+ # Convert markdown to HTML
285
+ html_content = markdown.markdown(markdown_content)
286
+
287
+ # Attach the HTML content
288
+ msg.attach(MIMEText(html_content, 'html'))
289
+
290
+ try:
291
+ # Set up the server using Gmail's SMTP
292
+ server = smtplib.SMTP('smtp.gmail.com', 587)
293
+ server.starttls() # Encrypt the connection
294
+ server.login(sender_email, sender_password) # Use App Password instead of Gmail password
295
+
296
+ # Send the email
297
+ server.sendmail(sender_email, receiver_email, msg.as_string())
298
+ server.quit()
299
+
300
+ print("Email sent successfully!")
301
+ # return True
302
+ except Exception as e:
303
+ print(f"Error sending email: {str(e)}")
304
+ # return False
305
+
306
+ # def main(name, email_id):
307
+ # start_time = time.time()
308
+
309
+ # # Display the process in Streamlit
310
+ # st.write("Analyzing product information...")
311
+ # prod_info = know_prod(name)
312
+ # end_prd_anal = time.time()
313
+
314
+ # # Show product info and analysis time
315
+ # st.write("Product Information:")
316
+ # st.write(prod_info)
317
+ # st.write(f"Time taken to analyze the product: {end_prd_anal - start_time} seconds")
318
+
319
+ # st.write('*****************************************************************')
320
+ # st.write(f"Number of websites analyzed: {len(prod_info)}")
321
+
322
+ # # Competitor analysis
323
+ # st.write("Analyzing competitors...")
324
+ # otp = compi_main(name)
325
+ # end_compi = time.time()
326
+
327
+ # st.write(f"Number of competitors found: {len(otp)}")
328
+ # st.write(f"Time taken to analyze the competitors: {end_compi - end_prd_anal} seconds")
329
+
330
+ # st.write('*****************************************************************')
331
+
332
+ # # Summary analysis
333
+ # st.write("Generating summary...")
334
+ # summpop = summary_name(otp)
335
+ # end_time_summary = time.time()
336
+
337
+ # # st.write('## Compititors Summary')
338
+ # # st.write(f"len(summpop)")
339
+ # st.write(f"Time taken to generate summary: {end_time_summary - end_compi} seconds")
340
+
341
+ # st.write('*****************************************************************')
342
+
343
+ # # Total analysis
344
+ # analysis_total = analysis_prod(prod_info, summpop)
345
+ # end_time = time.time()
346
+
347
+ # st.write("## Total Analysis")
348
+ # st.write(analysis_total)
349
+ # # st.write(f"Analysis time taken: {end_time - end_time_summary} seconds")
350
+ # # st.write(f"Total time taken: {end_time - start_time} seconds")
351
+
352
+ # st.write('*****************************************************************')
353
+
354
+ # # Send email
355
+ # send_email_gmail(email_id, analysis_total)
356
+
357
+ # return start_time, end_prd_anal, end_compi, end_time_summary, end_time, analysis_total
358
+ # def main(name, email_id):
359
+ # start_time = time.time()
360
+
361
+ # # Use container to group elements in a card-like style
362
+ # with st.container():
363
+ # st.markdown('---') # Horizontal line before the section
364
+
365
+ # with st.spinner("Analyzing product information..."):
366
+ # prod_info = know_prod(name)
367
+ # end_prd_anal = time.time()
368
+
369
+ # # Show product info and analysis time
370
+ # st.write("### Product Information:")
371
+ # st.write(prod_info)
372
+ # st.write(f"Time taken to analyze the product: {end_prd_anal - start_time:.2f} seconds")
373
+ # st.write(f"Number of websites analyzed: {len(prod_info)}")
374
+
375
+ # st.markdown('---') # Horizontal line after the section
376
+
377
+ # with st.container():
378
+ # st.markdown('---') # Horizontal line before the section
379
+
380
+ # with st.spinner("Analyzing competitors..."):
381
+ # otp = compi_main(name)
382
+ # end_compi = time.time()
383
+
384
+ # st.write("### Competitor Analysis:")
385
+ # st.write(f"Number of competitors found: {len(otp)}")
386
+ # st.write(f"Time taken to analyze the competitors: {end_compi - end_prd_anal:.2f} seconds")
387
+
388
+ # st.markdown('---') # Horizontal line after the section
389
+
390
+ # with st.container():
391
+ # st.markdown('---') # Horizontal line before the section
392
+
393
+ # with st.spinner("Generating summary..."):
394
+ # summpop = summary_name(otp)
395
+ # end_time_summary = time.time()
396
+
397
+ # st.write("### Summary Analysis:")
398
+ # st.write(f"Time taken to generate summary: {end_time_summary - end_compi:.2f} seconds")
399
+
400
+ # st.markdown('---') # Horizontal line after the section
401
+
402
+ # with st.container():
403
+ # st.markdown('---') # Horizontal line before the section
404
+
405
+ # st.write("### Total Analysis:")
406
+ # analysis_total = analysis_prod(prod_info, summpop)
407
+ # st.write(analysis_total)
408
+
409
+ # end_time = time.time()
410
+
411
+ # st.write(f"Analysis time taken: {end_time - end_time_summary:.2f} seconds")
412
+ # st.write(f"Total time taken: {end_time - start_time:.2f} seconds")
413
+
414
+ # st.markdown('---') # Horizontal line after the section
415
+
416
+ # # Email handling
417
+ # if not email_id:
418
+ # st.error("Email is not sent because it was not provided.", icon="🚫")
419
+ # else:
420
+ # # Call send_email_gmail and check if email is sent
421
+ # if send_email_gmail(email_id, analysis_total):
422
+ # st.success("Email sent successfully!", icon="✅")
423
+ # else:
424
+ # st.error("Failed to send email.", icon="❌")
425
+
426
+ # return start_time, end_prd_anal, end_compi, end_time_summary, end_time, analysis_total
427
+
428
+
429
+ # # Streamlit UI
430
+ # st.title("Product and Competitor Analysis")
431
+
432
+ # # Inputs from user
433
+ # name = st.text_input("Enter the Product Name", "Cafe Coffee Day")
434
+ # email_id = st.text_input("Enter your Email", "kapishrachamalla32@gmail.com")
435
+
436
+ # if st.button("Start Analysis"):
437
+ # t1, t2, t3, t4, t5, analysis = main(name, email_id)
438
+
439
+ # # Time breakdown in minutes
440
+ # st.write("Time taken to know about the product:", (t2 - t1) / 60, "minutes")
441
+ # st.write("Time taken to know about the competitors:", (t3 - t2) / 60, "minutes")
442
+ # st.write("Time taken to give analysis:", (t4 - t3) / 60, "minutes")
443
+ # st.write("Time taken to generate summary:", (t5 - t4) / 60, "minutes")
444
+ # st.write("Total time taken:", (t5 - t1) / 60, "minutes")
445
+ #$%$%$
446
+
447
+ def colored_container(color, content):
448
+ st.markdown(
449
+ f"""
450
+ <div style="background-color: {color}; padding: 10px; border-radius: 5px;">
451
+ {content}
452
+ </div>
453
+ """, unsafe_allow_html=True
454
+ )
455
+
456
+ def main(name, email_id):
457
+
458
+ start_time = time.time()
459
+ # colored_container("#A9DFBF", f"""
460
+ # <h4 style="color: black;">Total Analysis:</h4>
461
+ # <p style="color: black;">## Technical Analysis of McDonald's Chicken Big Mac</p>
462
+ # <p style="color: black;"><strong>Market Standing:</strong><br>The Chicken Big Mac represents a strategic move by McDonald's to tap into the growing demand for chicken-based menu items in the fast-food industry. This trend is driven by consumer interest in healthier options, a wider variety of protein sources, and the growing popularity of chicken sandwiches in general.</p>
463
+ # <p style="color: black;"><strong>Technical Strengths:</strong></p>
464
+ # <ul style="color: black;">
465
+ # <li>Leveraging Existing Brand Equity: The Chicken Big Mac benefits from the strong brand equity of the iconic Big Mac, ensuring immediate recognition and consumer interest.</li>
466
+ # <li>Innovation: The use of tempura-battered chicken patties represents an innovative approach to chicken preparation, adding a unique flavor profile and appealing to a broader customer base.</li>
467
+ # <li>Meeting Consumer Preferences: The sandwich addresses the growing demand for chicken-based options, demonstrating McDonald's ability to adapt to changing consumer preferences.</li>
468
+ # </ul>
469
+ # <p style="color: black;"><strong>Areas for Improvement:</strong></p>
470
+ # <ul style="color: black;">
471
+ # <li>Product Differentiation: While the Chicken Big Mac leverages the Big Mac's brand equity, it might benefit from more distinct features to differentiate itself further from other chicken sandwiches in the market.</li>
472
+ # <li>Nutritional Profile: The tempura batter might raise concerns about the nutritional profile of the sandwich, potentially impacting its appeal to health-conscious consumers.</li>
473
+ # <li>Marketing and Promotion: McDonald's needs to develop a comprehensive marketing strategy to effectively promote the Chicken Big Mac and highlight its unique selling points.</li>
474
+ # </ul>
475
+ # <p style="color: black;"><strong>Actionable Insights:</strong></p>
476
+ # <ul style="color: black;">
477
+ # <li>Enhance Differentiation: Consider adding unique ingredients or flavor profiles to further distinguish the Chicken Big Mac from other offerings.</li>
478
+ # <li>Promote Healthier Options: Explore lighter batter options or create a "healthier" version of the Chicken Big Mac with grilled chicken and lighter sauces.</li>
479
+ # <li>Targeted Marketing: Focus marketing efforts on highlighting the innovation and appeal of the Chicken Big Mac, reaching target demographics interested in chicken-based options.</li>
480
+ # </ul>
481
+ # <p style="color: black;"><strong>Comparison to Competitors:</strong></p>
482
+ # <p style="color: black;">McDonald's needs to analyze the competitive landscape of chicken sandwiches. This includes identifying key competitors like Chick-fil-A, Wendy's, and Popeyes, and comparing their offerings in terms of flavor profiles, ingredients, and marketing strategies. This analysis will help McDonald's identify potential gaps and opportunities for differentiation.</p>
483
+ # <p style="color: black;"><strong>Opportunities for Market Leadership:</strong></p>
484
+ # <ul style="color: black;">
485
+ # <li>Focus on Premium Quality: McDonald's can leverage its brand reputation to introduce a premium chicken sandwich with higher-quality ingredients and a unique flavor profile.</li>
486
+ # <li>Create a Signature Chicken Experience: Develop a distinctive chicken sandwich experience that sets it apart from competitors, emphasizing its unique taste and texture.</li>
487
+ # <li>Promote Chicken Innovation: Leverage the Chicken Big Mac's launch to position McDonald's as a leader in chicken innovation, showcasing a commitment to meeting evolving consumer demands.</li>
488
+ # </ul>
489
+ # <p style="color: black;"><strong>Conclusion:</strong></p>
490
+ # <p style="color: black;">The Chicken Big Mac holds significant potential for McDonald's to expand its market share in the growing chicken sandwich segment. By addressing its weaknesses, leveraging its strengths, and actively monitoring competitive offerings, McDonald's can create a successful product that drives sales and profitability.</p>
491
+ # <p style="color: black;">Analysis time taken: 4.51 seconds</p>
492
+ # <p style="color: black;">Total time taken: 368.86 seconds</p>
493
+ # """)
494
+
495
+ # Product information section
496
+ with st.container():
497
+ st.markdown('---') # Horizontal line before the section
498
+
499
+ with st.spinner("Analyzing product information..."):
500
+ prod_info = know_prod(name)
501
+ end_prd_anal = time.time()
502
+
503
+ # Display product info in a colored container
504
+ # colored_container("#D6EAF8", f"""
505
+ # <h4>Product Information:</h4>
506
+ # <p>{prod_info}</p>
507
+ # <p>Time taken to analyze the product: {end_prd_anal - start_time:.2f} seconds</p>
508
+ # <p>Number of websites analyzed: {len(prod_info)}</p>
509
+ # """)
510
+
511
+ st.write("### Product Information:")
512
+ st.write(prod_info)
513
+ # st.write(f"Time taken to analyze the product: {end_prd_anal - start_time:.2f} seconds")
514
+ st.write(f"Number of Articles analyzed: {len(prod_info)}")
515
+ st.markdown('---') # Horizontal line after the section
516
+
517
+ # Competitor analysis section
518
+ with st.container():
519
+ st.markdown('---') # Horizontal line before the section
520
+
521
+ with st.spinner("Analyzing competitors..."):
522
+ otp = compi_main(name)
523
+ end_compi = time.time()
524
+
525
+ # Display competitor info in a different colored container
526
+ # colored_container("#F9E79F", f"""
527
+ # <h4>Competitor Analysis:</h4>
528
+ # <p>Number of competitors found: {len(otp)}</p>
529
+ # <p>Time taken to analyze the competitors: {end_compi - end_prd_anal:.2f} seconds</p>
530
+ # """)
531
+
532
+ st.write("### Competitor Analysis:")
533
+ st.write(f"Number of potential competitors found: {len(otp)}")
534
+ # st.write(f"The Competitors are: \n {otp}")
535
+ # st.write(f"Time taken to analyze the competitors: {end_compi - end_prd_anal:.2f} seconds")
536
+
537
+ # st.markdown('---') # Horizontal line after the section
538
+
539
+ # Summary analysis section
540
+ # with st.container():
541
+ # st.markdown('---') # Horizontal line before the section
542
+
543
+ with st.spinner("Generating summary..."):
544
+ summpop = summary_name(otp)
545
+ end_time_summary = time.time()
546
+
547
+ # Display summary in a different color container
548
+ # colored_container("#A9DFBF", f"""
549
+ # <h4>Summary Analysis:</h4>
550
+ # <p>Time taken to generate summary: {end_time_summary - end_compi:.2f} seconds</p>
551
+ # """)
552
+
553
+ st.write("### Summary Analysis:")
554
+ st.write(summpop)
555
+ # st.write(f"Time taken to generate summary: {end_time_summary - end_compi:.2f} seconds")
556
+
557
+ st.markdown('---') # Horizontal line after the section
558
+
559
+ # Total analysis section
560
+ with st.container():
561
+ st.markdown('---') # Horizontal line before the section
562
+
563
+ # Display total analysis in another color container
564
+ analysis_total = analysis_prod(prod_info, summpop)
565
+ end_time = time.time()
566
+ # colored_container("#F5B7B1", f"""
567
+ # <h4>Total Analysis:</h4>
568
+ # <p>{analysis_total}</p>
569
+ # <p>Analysis time taken: {end_time - end_time_summary:.2f} seconds</p>
570
+ # <p>Total time taken: {end_time - start_time:.2f} seconds</p>
571
+ # """)
572
+
573
+ # st.write("### Total Analysis:")
574
+ st.write(analysis_total)
575
+
576
+ st.markdown('---') # Horizontal line after the section
577
+
578
+ # Email handling
579
+ if not email_id:
580
+ st.error("Email is not sent because it was not provided.", icon="🚫")
581
+ else:
582
+ # Call send_email_gmail and check if email is sent
583
+ send_email_gmail(email_id, analysis_total)
584
+ st.success("Email sent successfully!", icon="✅")
585
+ # else:
586
+ # st.error("Failed to send email.", icon="❌")
587
+
588
+ return start_time, end_prd_anal, end_compi, end_time_summary, end_time, analysis_total
589
+
590
+
591
+ # Streamlit UI
592
+ st.title("Market Mind 🧠")
593
+ # st.subheader("Empowering You with ")
594
+ st.markdown("<h7>Real-Time Market Intelligence</h1>", unsafe_allow_html=True)
595
+ # Sidebar for developer profiles and hackathon info
596
+ st.sidebar.markdown(
597
+ """
598
+ <h1 style='color: #ff0000;'>🚀 Hackathon Project</h1>
599
+ """,
600
+ unsafe_allow_html=True
601
+ )
602
+ st.sidebar.markdown("Welcome to the MarketMind project, developed for the hackathon to showcase AI power in the product and competitor analysis. 🚀")
603
+
604
+ # Add some icons/emojis to make it look more engaging
605
+ st.sidebar.markdown("### 🔧 Project Features")
606
+ # st.sidebar.markdown("- Analyze product details using OpenFoodFacts API.")
607
+ st.sidebar.markdown("- Real-Time Market Intelligence: Offers real-time data updates for informed decision-making")
608
+ st.sidebar.markdown("- AI and Machine Learning: Helps analyze competitors and suggests improvement strategies based on data.")
609
+
610
+ # Developer details with LinkedIn links
611
+ st.sidebar.markdown("### 👨‍💻 Developers")
612
+ st.sidebar.markdown("[Srish](https://www.linkedin.com/in/srishrachamalla/) - AI/ML Developer")
613
+ st.sidebar.markdown("[Sai Teja](https://www.linkedin.com/in/saiteja-pallerla-668734225/) - Data Analyst")
614
+
615
+ # Add expander sections for additional content
616
+ with st.sidebar.expander("ℹ About MarketMind"):
617
+ st.write("MarketMind is a platform focused on providing advanced data analytics, market intelligence, and AI-driven insights for businesses, investors, and market professionals. Its solutions are aimed at helping organizations make informed decisions by analyzing vast amounts of market data, consumer behavior, and industry trends in real-time")
618
+
619
+ with st.sidebar.expander("📚 Useful Resources"):
620
+ st.write("[Google Gemini AI Documentation](https://ai.google.dev/gemini-api/docs)")
621
+ st.write("[Streamlit Documentation](https://docs.streamlit.io/)")
622
+ st.write("[Groq Documentation](https://console.groq.com/docs/quickstart)")
623
+
624
+ # Add progress indicator for hackathon phases or development stages
625
+ st.sidebar.markdown("### ⏳ Hackathon Progress")
626
+ st.sidebar.progress(0.99) # Set progress level (0 to 1)
627
+
628
+ # Sidebar footer with final notes
629
+ st.sidebar.markdown("---")
630
+ st.sidebar.markdown(
631
+ """
632
+ <div style="text-align: center; font-size: 0.85em;">
633
+ Developed by Srish & Sai Teja • Powered by Google Gemini AI
634
+ </div>
635
+ """, unsafe_allow_html=True
636
+ )
637
+ # Inputs from user
638
+ name = st.text_input("Enter the Product Name", "Cafe Coffee Day")
639
+ email_id = st.text_input("Enter your Email", "")
640
+
641
+ if st.button("Start Analysis"):
642
+ t1, t2, t3, t4, t5, analysis = main(name, email_id)
643
+
644
+ # # Time breakdown in minutes
645
+ # st.write("### Time Breakdown (in minutes)")
646
+ # st.write(f"Time taken to analyze the product: {(t2 - t1) / 60:.2f} minutes")
647
+ # st.write(f"Time taken to analyze competitors: {(t3 - t2) / 60:.2f} minutes")
648
+ # st.write(f"Time taken to generate summary: {(t4 - t3) / 60:.2f} minutes")
649
+ # st.write(f"Time taken for total analysis: {(t5 - t1) / 60:.2f} minutes")
650
+ # Time breakdown in minutes
651
+ st.write("### Time Breakdown (in minutes)")
652
+
653
+ # Define colors for each breakdown
654
+ total_color = "#FF5733" # Red
655
+ competitors_color = "#33C1FF" # Blue
656
+ summary_color = "#75FF33" # Green
657
+ product_color = "#FF33B5" # Pink
658
+
659
+ # Display each time taken in different colors
660
+ # Get seconds
661
+ st.markdown(f"<p style='color: {product_color};'>Time taken to analyze the product: {time_calculator(t2 , t1)}</p>", unsafe_allow_html=True)
662
+ st.markdown(f"<p style='color: {competitors_color};'>Time taken to analyze competitors: {time_calculator(t3 , t2)} minutes</p>", unsafe_allow_html=True)
663
+ st.markdown(f"<p style='color: {summary_color};'>Time taken to generate summary: {time_calculator(t4 , t3)} minutes</p>", unsafe_allow_html=True)
664
+ st.markdown(f"<p style='color: {total_color};'>Time taken for total analysis: {time_calculator(t5 , t1)} minutes</p>", unsafe_allow_html=True)
665
+ st.markdown("---")
666
+ st.markdown("""
667
+ <div style="text-align: center; font-size: 0.9em;">
668
+ <p><i>MarketMind</i> was developed for a hackathon using <b>Streamlit</b> to showcase AI power in product and competitor analysis.</p>
669
+ <p>Developed by Srish & Sai Teja </p>
670
+ </div>
671
+ """, unsafe_allow_html=True)
672
+ # if __name__ == "__main__":
673
+ # t1,t2,t3,t4,t5,analysis = main('Cafe Coffee Day',"kapishrachamalla32@gmail.com")
674
+ # print("time taken to Know about the product: ", (t2-t1)/60)
675
+ # print("time taken to Know about the competitors: ", (t3-t2)/60)
676
+ # print("time taken to Know about the give analysis: ", (t4-t3)/60)
677
+ # print("time taken to Know about the summary: ", (t5-t4)/60)
678
+ # print("total time taken: ", (t5-t1)/60)
679
+
680
+
681
+ # import ast
682
+ # import requests
683
+ # import json
684
+ # import time
685
+ # import streamlit as st
686
+ # from duckduckgo_search import DDGS
687
+ # import google.generativeai as genai
688
+ # from groq import Groq
689
+ # import smtplib
690
+ # from email.mime.text import MIMEText
691
+ # from email.mime.multipart import MIMEMultipart
692
+ # import markdown
693
+
694
+ # # Configure generative AI API key
695
+ # genai.configure(api_key='AIzaSyCootL_jwKI3YDb6cKRJV-Ad0N4oKlLXXE')
696
+ # client = Groq(api_key='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')
697
+
698
+ # # Function definitions as in your original code
699
+
700
+ # def jina(url):
701
+ # base_url= "https://r.jina.ai//"
702
+ # url=base_url+url
703
+ # response=requests.get(url)
704
+ # return response.text
705
+
706
+ # def groq_inference(query):
707
+ # completion = client.chat.completions.create(
708
+ # model="llama3-groq-70b-8192-tool-use-preview",
709
+ # messages=[{"role": "user", "content": query}],
710
+ # temperature=0,
711
+ # max_tokens=2040,
712
+ # top_p=0.65,
713
+ # stop=None,
714
+ # )
715
+ # return completion.choices[0].message.content
716
+
717
+ # def serper_prod(company):
718
+ # url = "https://google.serper.dev/news"
719
+ # payload = json.dumps({"q": f"{company} info"})
720
+ # headers = {
721
+ # 'X-API-KEY': '7d6a39f71072f99cd421dbdd6cfebc73e2a66a07',
722
+ # 'Content-Type': 'application/json'
723
+ # }
724
+ # response = requests.request("POST", url, headers=headers, data=payload)
725
+ # return json.loads(response.text)
726
+
727
+ # def serper_compi(company):
728
+ # url = "https://google.serper.dev/search"
729
+ # payload = json.dumps({"q": f"{company} competitors."})
730
+ # headers = {
731
+ # 'X-API-KEY': '7d6a39f71072f99cd421dbdd6cfebc73e2a66a07',
732
+ # 'Content-Type': 'application/json'
733
+ # }
734
+ # response = requests.request("POST", url, headers=headers, data=payload)
735
+ # return json.loads(response.text)
736
+
737
+ # def AI_Search_compi(text, titles, name):
738
+ # ans = groq_inference(f"""Summarize the text of the articles titles are {titles} and don't remove the important terms about products or applications which should help in knowing about the competitors for a company {name}. The data is: {text}""")
739
+ # return ans
740
+
741
+ # def AI_Product_Analysis(text):
742
+ # ans = DDGS().chat("Analyze the products mentioned in the following news article in 400 words or fewer. Focus on their features, market relevance, and potential impact for a company's market planning: " + text, model='claude-3-haiku')
743
+ # return ans
744
+
745
+ # def AI_Product_Summary(news_summaries, product):
746
+ # ans = groq_inference(f"""Create a comprehensive summary of the product {product} based on the following summaries of 10 or fewer news articles. Ensure no important product details are lost, and you may add text from the articles as well: {news_summaries}""")
747
+ # return ans
748
+
749
+ # def AI_Search_extract_cmpy(text):
750
+ # prompt = """You will be given a dynamic text that summarizes key products, applications, and comparisons from articles. Your task is to extract relevant product names from the text and generate a list of search queries suitable for a search API. Don't give more than five names in the list. Output Format: ['company - product name', 'company - product name', 'product name', ...]."""
751
+ # ans = DDGS().chat(prompt + "The text is \n" + text, model='claude-3-haiku')
752
+ # print(ans)
753
+ # return ast.literal_eval(ans)
754
+
755
+ # def AI_Company_Summary(news_summaries):
756
+ # ans = DDGS().chat("Analyze the following combined summaries about multiple products. Provide a detailed summary of each product individually, clearly outlining their features, market relevance, and competitive advantages: " + news_summaries, model='claude-3-haiku')
757
+ # return ans
758
+
759
+ # def AI_Product_Summary_prod(news_summaries):
760
+ # # combined_summaries = " ".join(news_summaries)
761
+ # ans = groq_inference(f"""Create a comprehensive summary of the product based on the following summaries of 10 or fewer news articles. Ensure no important product details are lost and remember that these are form the news articles so you may have add text also : """ + news_summaries)
762
+ # # ans = DDGS().chat("Create a comprehensive summary of the product based on the following summaries of 10 or fewer news articles. Ensure no important product details are lost: " + news_summaries, model='gpt-4o-mini')
763
+
764
+ # def AI_Analysis(Product_analysis, Compitetiors_analysis):
765
+ # prompt = Compitetiors_analysis + "Product Information: \n " + Product_analysis
766
+ # system_prompt = f"""Analyze the following competitor and product details. Provide a technical analysis of each product, focusing on its market standing, technical strengths, and areas for improvement. Compare the product with competitors, identifying gaps and opportunities for differentiation: Competitors: {prompt}"""
767
+
768
+ # model = genai.GenerativeModel(model_name="gemini-1.5-flash")
769
+ # response = model.generate_content(system_prompt)
770
+ # return response.text
771
+
772
+ # def send_email_gmail(receiver_email,markdown_content):
773
+ # sender_email = "srishnotebooks@gmail.com"
774
+ # sender_password = "zoge jatp yaib qtsz"# replace with the app password generated
775
+ # # receiver_email = "recipient_email@example.com"
776
+ # subject = "Product Analysis Report"
777
+
778
+ # # Create the email message container
779
+ # msg = MIMEMultipart('alternative')
780
+ # msg['From'] = sender_email
781
+ # msg['To'] = receiver_email
782
+ # msg['Subject'] = subject
783
+
784
+ # # Convert markdown to HTML
785
+ # html_content = markdown.markdown(markdown_content)
786
+
787
+ # # Attach the HTML content
788
+ # msg.attach(MIMEText(html_content, 'html'))
789
+
790
+ # try:
791
+ # # Set up the server using Gmail's SMTP
792
+ # server = smtplib.SMTP('smtp.gmail.com', 587)
793
+ # server.starttls() # Encrypt the connection
794
+ # server.login(sender_email, sender_password) # Use App Password instead of Gmail password
795
+
796
+ # # Send the email
797
+ # server.sendmail(sender_email, receiver_email, msg.as_string())
798
+ # server.quit()
799
+
800
+ # print("Email sent successfully!")
801
+ # except Exception as e:
802
+ # print(f"Error sending email: {str(e)}")
803
+
804
+ # # """ This takes input of company and return summary of the company"""
805
+ # def analysis_name(text):
806
+ # compi_urls = [i['link'] for i in text['news']][0:4]
807
+ # print(compi_urls)
808
+ # text = [jina(url) for url in compi_urls]
809
+ # ans = ' '.join(AI_Product_Analysis(i[:8000]) for i in text if len(i)>1500)
810
+ # # time.sleep(25)
811
+ # summ = AI_Product_Summary_prod(ans[:21000])
812
+ # return summ
813
+
814
+ # # """" This is for knowing about the Product"""
815
+ # # 11
816
+ # # groq
817
+ # def know_prod(name):
818
+ # ser = serper_prod(name)
819
+ # compi_urls = [i['link'] for i in ser['news']]
820
+ # text = [jina(url) for url in compi_urls]
821
+ # ans = ' '.join(AI_Product_Analysis(i[:8000]) for i in text if len(i)>1500)
822
+ # summ = AI_Product_Summary(ans[:20000],name)
823
+ # return summ
824
+
825
+ # # """ This takes input of company and return list of the compi"""
826
+ # # 11
827
+ # def compi_main(name):
828
+ # ret = serper_compi(name)
829
+ # compi_urls = [i['link'] for i in ret['organic']]
830
+ # title_list= [i['title'] for i in ret['organic']]
831
+ # text = [jina(url) for url in compi_urls]
832
+ # ans = ' '.join(AI_Search_compi(i[:8000],title_list,name) for i in text if len(i)>1500)
833
+ # lst = AI_Search_extract_cmpy(ans)
834
+ # return lst
835
+
836
+ # # """ This takes input of company list and return summary of the company"""
837
+ # #21
838
+ # def summary_name(otp):
839
+ # names=[]
840
+ # title=otp
841
+ # for idx, i in enumerate(otp):
842
+ # results = serper_prod(i) # Call your function with the company name
843
+ # globals()[f'compi_{chr(65 + idx)}'] = results
844
+ # # print(i)
845
+ # # print(f'compi_{chr(65 + idx)}')
846
+ # names.append(f'compi_{chr(65 + idx)}')
847
+ # text_data = [globals()[name] for name in names]
848
+ # summ_data = [analysis_name(i) for i in text_data]
849
+ # cmpy_summ = AI_Company_Summary(" ".join(summ_data))
850
+ # return cmpy_summ
851
+
852
+ # # """ This takes inputs of compi summary and product summary and return summary of the company"""
853
+ # #1
854
+ # def analysis_prod(prod_summ,cmpy_summ):
855
+ # return AI_Analysis(prod_summ,cmpy_summ)
856
+
857
+ # # Streamlit Interface
858
+
859
+ # def main():
860
+ # st.title("Product and Competitor Analysis Tool")
861
+
862
+ # # Input company name
863
+ # company_name = st.text_input("Enter Company Name", value="Sample Company")
864
+ # email = st.text_input("Enter your email (Optional)")
865
+
866
+ # # Perform Analysis
867
+ # if st.button("Analyze"):
868
+ # start_time = time.time()
869
+
870
+ # st.write(f"Analyzing {company_name}...")
871
+
872
+ # # Analyze product
873
+ # prod_info = know_prod(company_name)
874
+ # st.write("### Product Information:")
875
+ # st.write(prod_info)
876
+
877
+ # end_prd_anal = time.time()
878
+ # st.write(f"Time taken to analyze the product: {(end_prd_anal - start_time)/60} Mins")
879
+
880
+ # # Analyze competitors
881
+ # st.write("### Competitor Information:")
882
+ # otp = compi_main(company_name)
883
+ # print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$')
884
+ # print(otp)
885
+ # st.write(otp)
886
+ # end_compi = time.time()
887
+ # st.write(f"Time taken to analyze the competitors: {end_compi - end_prd_anal} seconds")
888
+
889
+ # # Summary
890
+ # st.write("### Summary:")
891
+ # cmpy_summ = summary_name(otp)
892
+ # st.write(cmpy_summ)
893
+
894
+ # end_time_summary = time.time()
895
+ # st.write(f"Time taken to generate summary: {end_time_summary - end_compi} seconds")
896
+
897
+ # analysis_total = analysis_prod(prod_info,cmpy_summ)
898
+ # st.write("### Analysis:" + analysis_total)
899
+ # # Send via email (Optional)
900
+ # if email:
901
+ # send_email_gmail(email, analysis_total)
902
+ # st.write(f"Sending analysis to {email}...")
903
+ # # (Implement email sending logic here)
904
+ # # ...
905
+
906
+ # if __name__ == "__main__":
907
+ # main()