Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242import streamlit as stimport google.generativeai as genaiimport osimport PyPDF2 as pdffrom docx import Documentfrom pptx import Presentationfrom dotenv import load_dotenvimport jsonimport ioimport base64from docx.shared import Ptfrom matplotlib import pyplot as plt
# Load environment variablesload_dotenv()
# Configure Gemini APIgenai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
# Function to get response from Gemini APIdef get_gemini_response(input_text): model = genai.GenerativeModel('gemini-pro') try: response = model.generate_content(input_text) if response and response.text: return response.text else: 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): reader = pdf.PdfReader(uploaded_file) text = [] for page_num in range(len(reader.pages)): page = reader.pages[page_num] text.append(page.extract_text()) return text
# Function to extract text from uploaded Word documentdef input_word_text(uploaded_file): doc = Document(uploaded_file) text = [] for para in doc.paragraphs: text.append(para.text) return text
# Function to extract text from uploaded PPT filedef input_ppt_text(uploaded_file): presentation = Presentation(uploaded_file) text = [] for slide in presentation.slides: for shape in slide.shapes: if hasattr(shape, "text"): text.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 file if 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 ranges page_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 pages generated_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 text input_prompt = input_prompts[subject] input_prompt_filled = input_prompt.format(page_content=page_content) # Get response from Gemini API response = get_gemini_response(input_prompt_filled) # Display raw response for debugging st.markdown("**Raw Response:**") st.write(response) try: # Parse response response_json = json.loads(response) # Display and collect Explanation, Example, Mini Test, and Test Solution explanation = 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 format page_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 history st.session_state.history.append(generated_content) # Provide option to download generated content as .docx docx_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 asking if 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!")app.pyAdded+242