Spaces:
Sleeping
Sleeping
Update app.py
Browse files123411 unmodified lines161718import streamlit as stst.set_page_config(page_title="ChatbotGuide", layout="wide")st.title("Chatbot Guide")11 unmodified linesopenai_api_key = st.text_input("Enter your OpenAI API key", type="password")submit = st.button("Submit")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969711 unmodified lines109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143import streamlit as stimport pandas as pd# source: eagle0504/document-search-q-seriesdef read_and_textify_advanced(files: List[str], chunk_size: int) -> List[str]:"""Reads PDF files and extracts text from each page, breaking the text into specified segments.This function iterates over a list of uploaded PDF files, extracts text from each page,and compiles a list of texts and corresponding source information, segmented into smaller partsof approximately 'chunk_size' words each.Args:files (List[st.uploaded_file_manager.UploadedFile]): A list of uploaded PDF files.chunk_size (int): The number of words per text segment. Default is 50.Returns: A list of strings, where each string is a segment of text extracted from a PDF page."""text_list = [] # List to store extracted text segments# Iterate over each filefor file in files:pdfReader = PyPDF2.PdfReader(file) # Create a PDF reader object# Iterate over each page in the PDFfor i in range(len(pdfReader.pages)):pageObj = pdfReader.pages[i] # Get the page objecttext = pageObj.extract_text() # Extract text from the pageif text:# Split text into chunks of approximately 'chunk_size' wordswords = text.split(". ")for j in range(len(words)):# Get the chunk of text from j-chunk_size to j+chunk_sizestart = max(0, j - chunk_size)end = min(len(words), j + chunk_size + 1)chunk = ". ".join(words[start:end]) + '.'text_list.append(chunk)# Create a source identifier for each chunk and add it to the listelse:# If no text extracted, still add a placeholdertext_list.append("")pageObj.clear() # Clear the page object (optional, for memory management)return text_listdef get_questions(context, instructions) -> str:"""Given a text context, generates a list of questions using OpenAI's GPT-3 API.Args:- context: A string representing the context for which questions should be generated.Returns:- A string containing the question generated by the API."""try:response = client.chat.completions.create(model="gpt-4o-mini",messages=[{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": f"{instructions}\n\nText: {context}\n\nQuestions:\n"}])# Extract question text from the responsequestion_text = response.choices[0].message.contentreturn question_textexcept:# Return an empty string if there was an errorreturn ""def get_answers(row, instructions) -> str:"""Given a dataframe row containing context and questions, generates an answer using OpenAI's GPT-3 API.Args:- row: A pandas dataframe row containing 'context' and 'questions' columns.Returns:- A string containing the answer generated by the API."""try:response = client.chat.completions.create(model="gpt-4o-mini",messages=[{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": f"{instructions}\n\nText: {row.context}\n\nQuestions:\n{row.questions}\n\nAnswers:\n"}])# Extract answer text from the responseanswer_text = response.choices[0].message.contentreturn answer_textexcept Exception as e:# Print the error message and return an empty string if there was an errorprint (e)return ""st.set_page_config(page_title="ChatbotGuide", layout="wide")st.title("Chatbot Guide")11 unmodified linesopenai_api_key = st.text_input("Enter your OpenAI API key", type="password")submit = st.button("Submit")if submit:if openai_api_key:try:client = OpenAI(api_key=openai_api_key)if uploaded_files:textify_output = read_and_textify_advanced(uploaded_files, sentence_chunks)df = pd.DataFrame(textify_output)df.columns = ['context']if question_protocol == "":question_protocol = "Write questions based on the text"df['questions'] = df.apply(lambda row: get_questions(row['context'], question_protocol), axis=1)if answer_protocol == "":answer_protocol = "Write answers based on the text"df['answers'] = df.apply(lambda row: get_answers(row, answer_protocol), axis=1)df = df.drop['context']csv = df.to_csv(index=False).encode('utf-8')st.download_button(label="Download Q/A pairs as CSV",data=csv,file_name='questions_answers.csv',mime='text/csv',)else:st.error("Please upload at least 1 PDF")except:st.error("OpenAI API key is invalid")
app.py+125