GiantAnalytics commited on
Commit
833eadd
·
verified ·
1 Parent(s): 074a121

Creating app.py

Browse files
Files changed (1) hide show
  1. app.py +142 -0
app.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import tempfile
3
+ import os
4
+ import shutil
5
+ from langchain.embeddings.openai import OpenAIEmbeddings
6
+ from langchain.text_splitter import CharacterTextSplitter
7
+ from langchain.vectorstores import FAISS
8
+ from langchain_community.document_loaders import WebBaseLoader
9
+ from langchain.chains.question_answering import load_qa_chain
10
+ from langchain_openai import ChatOpenAI
11
+ from reportlab.lib.pagesizes import letter
12
+ from reportlab.pdfgen import canvas
13
+ from reportlab.pdfbase.pdfmetrics import stringWidth
14
+ import re
15
+
16
+ # Hardcoded OpenAI API Key
17
+ os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY')
18
+
19
+ # Streamlit UI
20
+ st.title("🔍 AI Benefits Analysis for Any Company")
21
+
22
+ # User input: Only Website URL (with placeholder)
23
+ website_url = st.text_input("Enter Website URL", placeholder="e.g., https://www.companywebsite.com")
24
+
25
+ # Fixed question for AI analysis
26
+ fixed_question = (
27
+ "Analyze how Artificial Intelligence (AI) can benefit this company based on its industry, "
28
+ "key operations, and challenges. Provide insights on AI-driven improvements in customer experience, "
29
+ "automation, sales, risk management, decision-making, and innovation. Include an AI implementation roadmap, "
30
+ "challenges, solutions, and future opportunities with real-world examples."
31
+ )
32
+
33
+ # Temporary directory to store FAISS index
34
+ temp_dir = tempfile.gettempdir()
35
+ faiss_db_path = os.path.join(temp_dir, "faiss_index_dir")
36
+
37
+ # Function to fetch and process website data
38
+ def build_embeddings(url):
39
+ st.info("Fetching and processing website data...")
40
+
41
+ # Load website data
42
+ loader = WebBaseLoader(url)
43
+ raw_text = loader.load()
44
+
45
+ # Chunking the fetched text
46
+ text_splitter = CharacterTextSplitter(separator='\n', chunk_size=500, chunk_overlap=50)
47
+ docs = text_splitter.split_documents(raw_text)
48
+
49
+ # Creating embeddings
50
+ embeddings = OpenAIEmbeddings()
51
+ docsearch = FAISS.from_documents(docs, embeddings)
52
+
53
+ # Save FAISS index
54
+ if os.path.exists(faiss_db_path):
55
+ shutil.rmtree(faiss_db_path)
56
+ os.makedirs(faiss_db_path)
57
+ docsearch.save_local(faiss_db_path)
58
+
59
+ return docsearch
60
+
61
+ # Function to save text to a PDF file
62
+ def save_text_to_pdf(text, file_path):
63
+ c = canvas.Canvas(file_path, pagesize=letter)
64
+ width, height = letter
65
+
66
+ # Define margins
67
+ margin_x = 50
68
+ margin_y = 50
69
+ max_width = width - 2 * margin_x # Usable text width
70
+
71
+ # Title
72
+ c.setFont("Helvetica-Bold", 16)
73
+ c.drawString(margin_x, height - margin_y, "AI Benefits Analysis Report")
74
+
75
+ # Move cursor down
76
+ y_position = height - margin_y - 30
77
+ c.setFont("Helvetica", 12)
78
+
79
+ # Function to wrap text within max_width
80
+ def wrap_text(text, font_name, font_size, max_width):
81
+ words = text.split()
82
+ lines = []
83
+ current_line = ""
84
+
85
+ for word in words:
86
+ test_line = current_line + " " + word if current_line else word
87
+ if stringWidth(test_line, font_name, font_size) <= max_width:
88
+ current_line = test_line
89
+ else:
90
+ lines.append(current_line)
91
+ current_line = word
92
+
93
+ if current_line:
94
+ lines.append(current_line)
95
+
96
+ return lines
97
+
98
+ # Process text
99
+ lines = text.split("\n")
100
+ wrapped_lines = []
101
+ for line in lines:
102
+ # Convert markdown to readable format
103
+ line = re.sub(r'###\s*(.*)', r'\n\n\1\n\n', line) # Convert ### headings
104
+ line = re.sub(r'\*\*(.*?)\*\*', r'\1', line) # Remove bold **text**
105
+ wrapped_lines.extend(wrap_text(line, "Helvetica", 12, max_width))
106
+
107
+ # Write text line by line with proper spacing
108
+ for line in wrapped_lines:
109
+ if y_position < margin_y: # If at bottom of page, create a new page
110
+ c.showPage()
111
+ c.setFont("Helvetica", 12)
112
+ y_position = height - margin_y
113
+ c.drawString(margin_x, y_position, line)
114
+ y_position -= 16 # Line spacing
115
+
116
+ c.save()
117
+
118
+ # Run everything in one click
119
+ if st.button("Get AI Insights") and website_url:
120
+ docsearch = build_embeddings(website_url)
121
+
122
+ # AI Benefits Analysis
123
+ st.subheader("💬 AI Benefits Analysis")
124
+
125
+ chain = load_qa_chain(ChatOpenAI(model="gpt-4o"), chain_type="stuff")
126
+ docs = docsearch.similarity_search(fixed_question)
127
+ response = chain.run(input_documents=docs, question=fixed_question)
128
+
129
+ st.write("**AI Insights:**", response)
130
+
131
+ # Save the AI insights as a PDF
132
+ pdf_file = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
133
+ save_text_to_pdf(response, pdf_file.name)
134
+
135
+ # Provide download link for the generated PDF file
136
+ with open(pdf_file.name, "rb") as f:
137
+ st.download_button(
138
+ label="Download AI Insights as PDF File",
139
+ data=f,
140
+ file_name="ai_benefits_analysis_report.pdf",
141
+ mime="application/pdf"
142
+ )