import streamlit as st from PyPDF2 import PdfReader from langchain.text_splitter import RecursiveCharacterTextSplitter import os from langchain_google_genai import GoogleGenerativeAIEmbeddings import google.generativeai as genai from langchain_community.vectorstores import FAISS from langchain_google_genai import ChatGoogleGenerativeAI from langchain.chains.question_answering import load_qa_chain from langchain.prompts import PromptTemplate from dotenv import load_dotenv from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware import json # Initialize FastAPI app api_app = FastAPI() # CORS settings to allow cross-origin requests api_app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Load environment variables load_dotenv() # Check if the API key is loaded correctly GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY") if not GOOGLE_API_KEY: raise ValueError("API key not found in environment variables. Please check 'key.env'.") # Configure the API key genai.configure(api_key=GOOGLE_API_KEY) def get_pdf_text(pdf_docs): text = "" for pdf in pdf_docs: pdf_reader = PdfReader(pdf) for page in pdf_reader.pages: text += page.extract_text() return text def get_text_chunks(text): text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000) chunks = text_splitter.split_text(text) return chunks def get_vector_store(text_chunks): embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=GOOGLE_API_KEY) vector_store = FAISS.from_texts(text_chunks, embedding=embeddings) vector_store.save_local("faiss_index") def get_conversational_chain(): prompt_template = """ You are an expert waste management advisor, specializing in helping businesses in various industries optimize their use of waste materials. Your role is to: 1. Recommend types of waste materials that could be beneficial or reusable in the specified industry. 2. Estimate potential cost savings from using waste materials instead of raw materials. 3. Highlight additional benefits of using waste materials, such as environmental impact, regulatory compliance, or brand enhancement. Consider the specific needs of the industry, typical waste materials, and potential areas for savings when providing your suggestions. ## Task: Industry: {industry_name} Current Waste or Material Interests (if provided): {waste_interest} Main Goals (e.g., reduce costs, increase sustainability): {main_goals} Provide a detailed response with: 1. **Types of Waste That May Be Useful**: Include how each type of waste can be repurposed in this industry. 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. 3. **Benefits of Using Waste**: Describe any additional advantages, such as sustainability, compliance with regulations, or brand reputation enhancement. ## Example Response Format: **Useful Waste Types:** - **Waste Type 1**: Explanation of its use and benefits in the {industry_name} industry. - **Waste Type 2**: Explanation of its use and benefits in the {industry_name} industry. **Estimated Savings:** - **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]. - **Waste Type 2**: By reusing [Waste Type 2], the industry could reduce costs by around [estimated savings figure, based on common industry benchmarks]. **Benefits of Using Waste:** 1. Environmental Impact: Describe how repurposing waste helps reduce environmental impact or waste disposal requirements. 2. Compliance: Explain any regulatory benefits, such as meeting industry waste reduction standards. 3. Brand Image: Highlight how adopting sustainable practices enhances public perception or brand value. Begin your response now. """ model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3) prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"]) chain = load_qa_chain(model, chain_type="stuff", prompt=prompt) return chain def user_input(user_question): embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=GOOGLE_API_KEY) # Check if FAISS index exists before loading faiss_index_path = "faiss_index/index.faiss" if not os.path.exists(faiss_index_path): return {"error": "FAISS index not found. Please ensure the documents are processed first."} new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True) docs = new_db.similarity_search(user_question) chain = get_conversational_chain() response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True) return {"response": response["output_text"]} # FastAPI endpoint to expose the API @api_app.post("/api/ask") async def ask_question(request: Request): req_data = await request.json() user_question = req_data.get("question", "") if not user_question: return {"error": "No question provided."} # Call the function that retrieves the answer result = user_input(user_question) return result # Streamlit UI def main(): st.set_page_config(page_title=" AI Waste Expert ") st.header("🍃 AI Waste Advisor") # Input field for user's question conc = st.text_input("Do You Want to Know Which Waste Can be Useful for Your Industry or Learn about waste management?") # Show an example input below the input field st.caption("Example: 'Which waste product can I use for my cement industry?'") if conc: 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 ." result = user_input(user_question) if "error" in result: st.error(result["error"]) else: st.write("Reply: ", result["response"]) with st.sidebar: st.title("Documents:") # Check if the FAISS index exists if not os.path.exists("faiss_index/index.faiss"): with st.spinner("Processing documents..."): # Process the provided PDFs pdf_files = ["waste_guideline.pdf"] raw_text = get_pdf_text([open(pdf, "rb") for pdf in pdf_files]) text_chunks = get_text_chunks(raw_text) get_vector_store(text_chunks) st.success("Documents processed and FAISS index created.") else: st.info("FAISS index loaded from 'faiss_index'.") if __name__ == "__main__": main()