Spaces:
Build error
Build error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118import osimport shutilfrom fastapi import FastAPI, UploadFile, File, HTTPException, Formfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelimport requestsfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_community.vectorstores.faiss import FAISSfrom langchain.chains.question_answering import load_qa_chainfrom langchain.prompts import PromptTemplatefrom langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAIimport google.generativeai as genaifrom dotenv import load_dotenvapp = FastAPI()# Configure CORSapp.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)# Load environment variablesload_dotenv()# Configure Google APIgenai.configure(api_key=os.getenv("GOOGLE_API_KEY"))class QuestionInput(BaseModel):question: strclass UploadInput(BaseModel):url: str = Form(None)def scrape_data(url):return "scraped data"def split_text_into_chunks(text):splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)text_chunks = splitter.split_text(text)return text_chunksdef create_vector_store(chunks):embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")vector_store = FAISS.from_texts(chunks, embedding=embeddings)vector_store.save_local("faiss_index")def setup_conversation_chain(template):model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)prompt = PromptTemplate(template=template, input_variables=["context", "question"])chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)return chain@app.post("/upload")async def upload_files(url: str = Form(None)):try:# print(url)# all_text = ""# # Process URL# if url:# # check if url is valid (request doesnt give error)# if # doesnt give error# all_text = scrape_data(url)# else:# raise HTTPException(status_code=400, detail="Invalid URL")# if not all_text:# raise HTTPException(status_code=400, detail="No content to process")# chunks = split_text_into_chunks(all_text)# create_vector_store(chunks)return {"message": "Content uploaded and processed successfully"}except HTTPException as http_exc:print(f"HTTP Exception: {http_exc.detail}")raise http_excexcept Exception as e:print(f"Unhandled Exception: {e}")raise HTTPException(status_code=500, detail=str(e))@app.post("/ask")async def ask_question(question_input: QuestionInput):try:embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")indexed_data = FAISS.load_local("reviews_index", embeddings, allow_dangerous_deserialization=True)docs = indexed_data.similarity_search(question_input.question)prompt_template = """Your alias is AI Rate Professor. Your task is to provide a thorough response based on the given context, ensuring all relevant details are included.If the requested information isn't available, simply state, "answer not available in context," then answer based on your understanding, connecting with the context.Don't provide incorrect information.\n\nContext: \n {context}?\nQuestion: \n {question}\nAnswer:"""chain = setup_conversation_chain(prompt_template)response = chain({"input_documents": docs, "question": question_input.question}, return_only_outputs=True)print(response["output_text"])return {"answer": response["output_text"]}except Exception as e:raise HTTPException(status_code=500, detail=str(e))# prompt_template = """# Your alias is AI Rate Professor. Your task is to provide a thorough response based on the given context, ensuring all relevant details are included.# If the requested information isn't available, simply state, "answer not available in context," then answer based on your understanding, connecting with the context.# Don't provide incorrect information.\n\n# Context: \n {context}?\n# Question: \n {question}\n# Answer:# """123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115import osimport shutilfrom fastapi import FastAPI, UploadFile, File, HTTPException, Formfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelimport requestsfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_community.vectorstores.faiss import FAISSfrom langchain.chains.question_answering import load_qa_chainfrom langchain.prompts import PromptTemplatefrom langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAIimport google.generativeai as genaifrom dotenv import load_dotenvapp = FastAPI()# Configure CORSapp.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)load_dotenv()genai.configure(api_key="AIzaSyCCIYW0HamEfEMyGMXhQypyYtiY4O2ixUg")class QuestionInput(BaseModel):question: strclass UploadInput(BaseModel):url: str = Form(None)def scrape_data(url):return "scraped data"def split_text_into_chunks(text):splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)text_chunks = splitter.split_text(text)return text_chunksdef create_vector_store(chunks):embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")vector_store = FAISS.from_texts(chunks, embedding=embeddings)vector_store.save_local("faiss_index")def setup_conversation_chain(template):model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)prompt = PromptTemplate(template=template, input_variables=["context", "question"])chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)return chain@app.post("/upload")async def upload_files(url: str = Form(None)):try:# print(url)# all_text = ""# # Process URL# if url:# # check if url is valid (request doesnt give error)# if # doesnt give error# all_text = scrape_data(url)# else:# raise HTTPException(status_code=400, detail="Invalid URL")# if not all_text:# raise HTTPException(status_code=400, detail="No content to process")# chunks = split_text_into_chunks(all_text)# create_vector_store(chunks)return {"message": "Content uploaded and processed successfully"}except HTTPException as http_exc:print(f"HTTP Exception: {http_exc.detail}")raise http_excexcept Exception as e:print(f"Unhandled Exception: {e}")raise HTTPException(status_code=500, detail=str(e))@app.post("/ask")async def ask_question(question_input: QuestionInput):try:embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")indexed_data = FAISS.load_local("reviews_index", embeddings, allow_dangerous_deserialization=True)docs = indexed_data.similarity_search(question_input.question)prompt_template = """Your alias is AI Rate Professor. Your task is to provide a thorough response based on the given context, ensuring all relevant details are included.If the requested information isn't available, simply state, "answer not available in context," then answer based on your understanding, connecting with the context.Don't provide incorrect information.\n\nContext: \n {context}?\nQuestion: \n {question}\nAnswer:"""chain = setup_conversation_chain(prompt_template)response = chain({"input_documents": docs, "question": question_input.question}, return_only_outputs=True)print(response["output_text"])return {"answer": response["output_text"]}except Exception as e:raise HTTPException(status_code=500, detail=str(e))# prompt_template = """# Your alias is AI Rate Professor. Your task is to provide a thorough response based on the given context, ensuring all relevant details are included.# If the requested information isn't available, simply state, "answer not available in context," then answer based on your understanding, connecting with the context.# Don't provide incorrect information.\n\n# Context: \n {context}?\n# Question: \n {question}\n# Answer:# """
app.py+114-117