Abrar20 commited on
Commit
8001b58
·
verified ·
1 Parent(s): 715b9e4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -0
app.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PyPDF2 import PdfReader
3
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
4
+ import os
5
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings
6
+ import google.generativeai as genai
7
+ from langchain_community.vectorstores import FAISS
8
+ from langchain_google_genai import ChatGoogleGenerativeAI
9
+ from langchain.chains.question_answering import load_qa_chain
10
+ from langchain.prompts import PromptTemplate
11
+ from dotenv import load_dotenv
12
+ from fastapi import FastAPI, Request
13
+ from fastapi.middleware.cors import CORSMiddleware
14
+ import json
15
+
16
+ # Initialize FastAPI app
17
+ api_app = FastAPI()
18
+
19
+ # CORS settings to allow cross-origin requests
20
+ api_app.add_middleware(
21
+ CORSMiddleware,
22
+ allow_origins=["*"],
23
+ allow_credentials=True,
24
+ allow_methods=["*"],
25
+ allow_headers=["*"],
26
+ )
27
+
28
+ # Load environment variables
29
+ load_dotenv()
30
+
31
+ # Check if the API key is loaded correctly
32
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
33
+ if not GOOGLE_API_KEY:
34
+ raise ValueError("API key not found in environment variables. Please check 'key.env'.")
35
+
36
+ # Configure the API key
37
+ genai.configure(api_key=GOOGLE_API_KEY)
38
+
39
+ def get_pdf_text(pdf_docs):
40
+ text = ""
41
+ for pdf in pdf_docs:
42
+ pdf_reader = PdfReader(pdf)
43
+ for page in pdf_reader.pages:
44
+ text += page.extract_text()
45
+ return text
46
+
47
+ def get_text_chunks(text):
48
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
49
+ chunks = text_splitter.split_text(text)
50
+ return chunks
51
+
52
+ def get_vector_store(text_chunks):
53
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=GOOGLE_API_KEY)
54
+ vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
55
+ vector_store.save_local("faiss_index")
56
+
57
+ def get_conversational_chain():
58
+ prompt_template = """
59
+ You are an expert waste management advisor, specializing in helping businesses in various industries optimize their use of waste materials. Your role is to:
60
+ 1. Recommend types of waste materials that could be beneficial or reusable in the specified industry.
61
+ 2. Estimate potential cost savings from using waste materials instead of raw materials.
62
+ 3. Highlight additional benefits of using waste materials, such as environmental impact, regulatory compliance, or brand enhancement.
63
+
64
+ Consider the specific needs of the industry, typical waste materials, and potential areas for savings when providing your suggestions.
65
+
66
+ ## Task:
67
+ Industry: {industry_name}
68
+ Current Waste or Material Interests (if provided): {waste_interest}
69
+ Main Goals (e.g., reduce costs, increase sustainability): {main_goals}
70
+
71
+ Provide a detailed response with:
72
+ 1. **Types of Waste That May Be Useful**: Include how each type of waste can be repurposed in this industry.
73
+ 2. **Estimated Savings**: Calculate or estimate potential cost savings from using the suggested waste materials instead of raw materials. Mention approximate savings based on typical industry metrics or scenarios.
74
+ 3. **Benefits of Using Waste**: Describe any additional advantages, such as sustainability, compliance with regulations, or brand reputation enhancement.
75
+
76
+ ## Example Response Format:
77
+ **Useful Waste Types:**
78
+ - **Waste Type 1**: Explanation of its use and benefits in the {industry_name} industry.
79
+ - **Waste Type 2**: Explanation of its use and benefits in the {industry_name} industry.
80
+
81
+ **Estimated Savings:**
82
+ - **Waste Type 1**: By using [Waste Type 1] instead of [corresponding raw material], you could save approximately [savings percentage or amount, e.g., 20-30% of material costs].
83
+ - **Waste Type 2**: By reusing [Waste Type 2], the industry could reduce costs by around [estimated savings figure, based on common industry benchmarks].
84
+
85
+ **Benefits of Using Waste:**
86
+ 1. Environmental Impact: Describe how repurposing waste helps reduce environmental impact or waste disposal requirements.
87
+ 2. Compliance: Explain any regulatory benefits, such as meeting industry waste reduction standards.
88
+ 3. Brand Image: Highlight how adopting sustainable practices enhances public perception or brand value.
89
+
90
+ Begin your response now.
91
+ """
92
+ model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
93
+ prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
94
+ chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
95
+
96
+ return chain
97
+
98
+ def user_input(user_question):
99
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=GOOGLE_API_KEY)
100
+
101
+ # Check if FAISS index exists before loading
102
+ faiss_index_path = "faiss_index/index.faiss"
103
+ if not os.path.exists(faiss_index_path):
104
+ return {"error": "FAISS index not found. Please ensure the documents are processed first."}
105
+
106
+ new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
107
+ docs = new_db.similarity_search(user_question)
108
+
109
+ chain = get_conversational_chain()
110
+
111
+ response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
112
+
113
+ return {"response": response["output_text"]}
114
+
115
+ # FastAPI endpoint to expose the API
116
+ @api_app.post("/api/ask")
117
+ async def ask_question(request: Request):
118
+ req_data = await request.json()
119
+ user_question = req_data.get("question", "")
120
+ if not user_question:
121
+ return {"error": "No question provided."}
122
+
123
+ # Call the function that retrieves the answer
124
+ result = user_input(user_question)
125
+ return result
126
+
127
+ # Streamlit UI
128
+ def main():
129
+ st.set_page_config(page_title=" AI Waste Expert ")
130
+ st.header("🍃 AI Waste Advisor")
131
+
132
+ # Input field for user's question
133
+ conc = st.text_input("Do You Want to Know Which Waste Can be Useful for Your Industry or Learn about waste management?")
134
+
135
+ # Show an example input below the input field
136
+ st.caption("Example: 'Which waste product can I use for my cement industry?'")
137
+
138
+ if conc:
139
+ user_question = f"{conc}. And Please give me suggestions, in this context.Act Like Ai advisor who can give suggestions on Which Waste Can be Useful for their Industry or assist them to lear about waste management? Include how much they can save using the waste instead of the raw material and the benefits of using it. Give in bangladesh context and Give only the suggestions in the response ."
140
+ result = user_input(user_question)
141
+ if "error" in result:
142
+ st.error(result["error"])
143
+ else:
144
+ st.write("Reply: ", result["response"])
145
+
146
+ with st.sidebar:
147
+ st.title("Documents:")
148
+
149
+ # Check if the FAISS index exists
150
+ if not os.path.exists("faiss_index/index.faiss"):
151
+ with st.spinner("Processing documents..."):
152
+ # Process the provided PDFs
153
+ pdf_files = ["waste_guideline.pdf"]
154
+ raw_text = get_pdf_text([open(pdf, "rb") for pdf in pdf_files])
155
+ text_chunks = get_text_chunks(raw_text)
156
+ get_vector_store(text_chunks) st.success("Documents processed and FAISS index created.")
157
+ else:
158
+ st.info("FAISS index loaded from 'faiss_index'.")
159
+
160
+ if __name__ == "__main__":
161
+ main()