Spaces:
Sleeping
Sleeping
Update app.py
Browse files6 unmodified lines78910111213141510 unmodified lines2627282930313233343522 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412426 unmodified linesfrom dotenv import load_dotenvimport jsonimport ioimport base64from docx.shared import Ptfrom matplotlib import pyplot as plt# Load environment variablesload_dotenv()10 unmodified linesreturn response.textelse:st.error("Received an empty response from the model.")return "{}"except Exception as e:st.error(f"Error while getting response from API: {str(e)}")return "{}"# Function to extract text from uploaded PDF filedef input_pdf_text(uploaded_file):22 unmodified linestext.append(shape.text)return text# Function to generate formula imagedef render_formula_as_image(formula):fig, ax = plt.subplots()ax.text(0.5, 0.5, f"${formula}$", size=30, ha='center', va='center')ax.set_axis_off()buf = io.BytesIO()plt.savefig(buf, format='png')plt.close(fig)buf.seek(0)return base64.b64encode(buf.read()).decode('utf-8')# Function to download content as a .docx filedef create_docx(content):doc = Document()for page in content:doc.add_heading(f"Page {page['Page']}", level=2)doc.add_paragraph(f"Explanation: {page['Explanation']}")doc.add_paragraph(f"Example: {page['Example']}")doc.add_paragraph(f"Mini Test: {page['Mini Test']}")doc.add_paragraph(f"Test Solution: {page['Test Solution']}")doc.add_page_break()buf = io.BytesIO()doc.save(buf)buf.seek(0)return buf# Prompt Template for generating explanations, examples, and mini testsinput_prompts = {"Mathematics": """You are an expert in mathematics. Your task is to explain the content on the given page, provide a relevant example, and create a mini test with solutions.The explanation must cover both basic and advanced concepts with necessary formulas and illustrations.I want the response in the following structured format:{{"Explanation": "", "Example": "", "Mini Test": "", "Test Solution": ""}}""","Statistics": """You are an expert in statistics. Your task is to explain the content on the given page, provide a relevant example, and create a mini test with solutions.You should focus on key statistical principles and clarify the meaning of statistical models in an easy-to-understand way.I want the response in the following structured format:{{"Explanation": "", "Example": "", "Mini Test": "", "Test Solution": ""}}""","Computer Science": """You are an expert in computer science. Your task is to explain the content on the given page, provide a relevant example, and create a mini test with solutions.The explanation must include algorithms, data structures, or relevant programming paradigms as per the page content.I want the response in the following structured format:{{"Explanation": "", "Example": "", "Mini Test": "", "Test Solution": ""}}"""}# Streamlit Appst.set_page_config(page_title="Interactify")st.title("Interactify")# Dropdown for subject selectionsubject = st.selectbox("Select Subject", ["Mathematics", "Statistics", "Computer Science"])# File uploader for slides (PDF, Word, PPT, or text) inputuploaded_file = st.file_uploader("Upload Your Document (PDF, DOCX, PPTX, TXT)...", type=["pdf", "docx", "pptx", "txt"])# Collapsible section for questionswith st.expander("Ask a question about the document content"):user_question = st.text_area("Type your question:")# Text input for page rangepage_range_input = st.text_input("Enter page ranges (e.g., 1-2):")# Initialize session state for historyif 'history' not in st.session_state:st.session_state.history = []# Submit button for processing the documentsubmit = st.button("Submit")if submit:if uploaded_file:try:# Extract text from the uploaded fileif uploaded_file.type == "application/pdf":document_text = input_pdf_text(uploaded_file)elif uploaded_file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":document_text = input_word_text(uploaded_file)elif uploaded_file.type == "application/vnd.openxmlformats-officedocument.presentationml.presentation":document_text = input_ppt_text(uploaded_file)elif uploaded_file.type == "text/plain":document_text = uploaded_file.read().decode("utf-8").split('\n')else:st.error("Unsupported file type!")st.stop()# Process page rangespage_ranges = []if page_range_input:try:ranges = page_range_input.split(',')for r in ranges:start, end = map(int, r.split('-'))page_ranges.append(range(start - 1, end))except ValueError:st.error("Invalid page range format!")st.stop()else:page_ranges = [range(len(document_text))]# Process selected pagesgenerated_content = []st.markdown("### Generated Content:")for range_set in page_ranges:for page_num in range_set:if page_num < len(document_text):st.markdown(f"#### Page {page_num + 1}")page_content = document_text[page_num]# Prepare prompt with extracted page textinput_prompt = input_prompts[subject]input_prompt_filled = input_prompt.format(page_content=page_content)# Get response from Gemini APIresponse = get_gemini_response(input_prompt_filled)# Display raw response for debuggingst.markdown("**Raw Response:**")st.write(response)try:# Parse responseresponse_json = json.loads(response)# Display and collect Explanation, Example, Mini Test, and Test Solutionexplanation = response_json.get("Explanation", "No explanation available.")example = response_json.get("Example", "No example available.")mini_test = response_json.get("Mini Test", "No mini test available.")test_solution = response_json.get("Test Solution", "No test solution available.")st.markdown("**Explanation:**")st.write(explanation)st.markdown("**Example:**")st.write(example)st.markdown("**Mini Test:**")st.write(mini_test)st.markdown("**Test Solution:**")st.write(test_solution)# Collect generated content in JSON formatpage_content_json = {"Page": page_num + 1,"Explanation": explanation,"Example": example,"Mini Test": mini_test,"Test Solution": test_solution}generated_content.append(page_content_json)except json.JSONDecodeError:st.error("Failed to decode JSON response from the model.")else:st.warning(f"Page {page_num + 1} is out of range.")# Add generated content to historyst.session_state.history.append(generated_content)# Provide option to download generated content as .docxdocx_data = create_docx(generated_content)st.download_button(label="Download Generated Content", data=docx_data, file_name="generated_content.docx", mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document")# Handle question askingif user_question:question_prompt = f"Based on the content of the document, answer the following question:\n{user_question}"response = get_gemini_response(question_prompt)st.markdown("### Answer to Your Question:")st.write(response)except Exception as e:st.error(f"Error: {str(e)}")else:st.error("Please upload a file!")6 unmodified lines78910111210 unmodified lines2324252627282930313222 unmodified lines5556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762776 unmodified linesfrom dotenv import load_dotenvimport jsonimport io# Load environment variablesload_dotenv()10 unmodified linesreturn response.textelse:st.error("Received an empty response from the model.")return "{}" # Return empty JSONexcept Exception as e:st.error(f"Error while getting response from API: {str(e)}")return "{}" # Return empty JSON# Function to extract text from uploaded PDF filedef input_pdf_text(uploaded_file):22 unmodified linestext.append(shape.text)return text# Function to split text into manageable chunksdef split_text(text, max_chunk_size=2000):"""Split text into chunks with a maximum size."""chunks = []while len(text) > max_chunk_size:chunk = text[:max_chunk_size]text = text[max_chunk_size:]chunks.append(chunk)chunks.append(text)return chunks# Prompt Template for generating explanations, examples, and mini testsinput_prompts = {"Mathematics": """You are an expert in mathematics. Your task is to explain the content on the given page, provide a relevant example, and create a mini test with solutions.Page Content: {page_content}I want the response in the following structured format:{{"Explanation": "", "Example": "", "Mini Test": "", "Test Solution": ""}}""","Statistics": """You are an expert in statistics. Your task is to explain the content on the given page, provide a relevant example, and create a mini test with solutions.Page Content: {page_content}I want the response in the following structured format:{{"Explanation": "", "Example": "", "Mini Test": "", "Test Solution": ""}}""","Computer Science": """You are an expert in computer science. Your task is to explain the content on the given page, provide a relevant example, and create a mini test with solutions.Page Content: {page_content}I want the response in the following structured format:{{"Explanation": "", "Example": "", "Mini Test": "", "Test Solution": ""}}"""}# Function to generate DOCX file from contentdef generate_docx(generated_content):doc = Document()doc.add_heading('Generated Content', level=1)for content in generated_content:doc.add_heading(f'Page {content["Page"]}', level=2)doc.add_paragraph(f"**Explanation:**\n{content.get('Explanation', 'No explanation available.')}")doc.add_paragraph(f"**Example:**\n{content.get('Example', 'No example available.')}")doc.add_paragraph(f"**Mini Test:**\n{content.get('Mini Test', 'No mini test available.')}")doc.add_paragraph(f"**Test Solution:**\n{content.get('Test Solution', 'No test solution available.')}")doc.add_paragraph() # Add a blank line for spacingbyte_io = io.BytesIO()doc.save(byte_io)byte_io.seek(0)return byte_io# Streamlit Appst.set_page_config(page_title="Interactify")page = st.sidebar.radio("Select Page", ["Home", "History"])if page == "Home":st.title("Interactify")# Dropdown for subject selectionsubject = st.selectbox("Select Subject", ["Mathematics", "Statistics", "Computer Science"])# File uploader for slides (PDF, Word, PPT, or text) inputuploaded_file = st.file_uploader("Upload Your Document (PDF, DOCX, PPTX, TXT)...", type=["pdf", "docx", "pptx", "txt"])# Text area for user questionuser_question = st.text_area("Type your question about the document content:")# Text input for page rangepage_range_input = st.text_input("Enter page ranges (e.g., 78-79):")# Initialize session state for historyif 'history' not in st.session_state:st.session_state.history = []# Submit button for processing the documentsubmit = st.button("Submit")if submit:if uploaded_file:try:# Extract text from the uploaded fileif uploaded_file.type == "application/pdf":document_text = input_pdf_text(uploaded_file)elif uploaded_file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":document_text = input_word_text(uploaded_file)elif uploaded_file.type == "application/vnd.openxmlformats-officedocument.presentationml.presentation":document_text = input_ppt_text(uploaded_file)elif uploaded_file.type == "text/plain":document_text = uploaded_file.read().decode("utf-8").split('\n')else:st.error("Unsupported file type!")st.stop()# Process page rangespage_ranges = []if page_range_input:try:ranges = page_range_input.split(',')for r in ranges:start, end = map(int, r.split('-'))page_ranges.append(range(start - 1, end))except ValueError:st.error("Invalid page range format! Use the format 'start-end'.")st.stop()else:page_ranges = [range(len(document_text))]# Process selected pagesgenerated_content = []st.markdown("### Generated Content:")for range_set in page_ranges:for page_num in range_set:if page_num < len(document_text):st.markdown(f"#### Page {page_num + 1}")page_content = document_text[page_num]# Prepare prompt with extracted page textinput_prompt = input_prompts[subject]input_prompt_filled = input_prompt.format(page_content=page_content)# Get response from Gemini APIresponse = get_gemini_response(input_prompt_filled)# Display raw response for debuggingst.markdown("**Raw Response:**")st.write(response)try:# Parse responseresponse_json = json.loads(response)# Display and collect Explanation, Example, Mini Test, and Test Solutionexplanation = response_json.get("Explanation", "No explanation available.")example = response_json.get("Example", "No example available.")mini_test = response_json.get("Mini Test", "No mini test available.")test_solution = response_json.get("Test Solution", "No test solution available.")st.markdown("**Explanation:**")st.write(explanation)st.markdown("**Example:**")st.write(example)st.markdown("**Mini Test:**")st.write(mini_test)st.markdown("**Test Solution:**")st.write(test_solution)# Collect generated content in JSON formatpage_content_json = {"Page": page_num + 1,"Explanation": explanation,"Example": example,"Mini Test": mini_test,"Test Solution": test_solution}generated_content.append(page_content_json)except json.JSONDecodeError:st.error("Failed to decode JSON response from the model.")else:st.warning(f"Page {page_num + 1} is out of range.")# Add generated content to historyst.session_state.history.append(generated_content)# Provide option to copy generated contentst.markdown("### Copy Generated Content")generated_content_str = json.dumps(generated_content, indent=4)st.code(generated_content_str)if st.button("Copy to Clipboard"):st.experimental_set_query_params(text=generated_content_str)st.success("Content copied to clipboard!")# Provide download option for DOCXif generated_content:docx_file = generate_docx(generated_content)st.download_button(label="Download Generated Content as DOCX",data=docx_file,file_name='generated_content.docx',mime='application/vnd.openxmlformats-officedocument.wordprocessingml.document')# Process user questionif user_question:question_prompt = f"Based on the content of the document, answer the following question:\n{user_question}"response = get_gemini_response(question_prompt)st.markdown("### Answer to Your Question:")st.write(response)except Exception as e:st.error(f"Error: {str(e)}")else:st.warning("Please upload your document.")elif page == "History":st.title("History")# Display historyif st.session_state.history:st.markdown("### Previous Generated Content")for i, content in enumerate(st.session_state.history, start=1):with st.expander(f"History {i}"):st.json(content)else:st.write("No history available.")# Footerst.markdown("---")st.markdown("© 2024 by Christley")
app.py+197-162