Spaces:
Sleeping
Sleeping
File size: 15,111 Bytes
7c30d52 3ddc044 7c30d52 3ddc044 7c30d52 3ddc044 01610a1 3ddc044 7c30d52 3ddc044 7c30d52 3ddc044 7c30d52 3ddc044 7c30d52 3ddc044 01610a1 7c30d52 01610a1 3ddc044 01610a1 3ddc044 01610a1 3ddc044 7c30d52 3ddc044 01610a1 3ddc044 01610a1 3ddc044 7c30d52 3ddc044 01610a1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 | import streamlit as st
import google.generativeai as genai
import os
import PyPDF2 as pdf
from docx import Document
from pptx import Presentation
from dotenv import load_dotenv
import json
import io
# Load environment variables
load_dotenv()
# Configure Gemini API
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
# Function to get response from Gemini API
def 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 "{}" # Return empty JSON
except 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 file
def 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 document
def 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 file
def 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 split text into manageable chunks
def 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 tests
input_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 content
def 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 spacing
byte_io = io.BytesIO()
doc.save(byte_io)
byte_io.seek(0)
return byte_io
# Define fields and subjects
fields_subjects = {
"Law": ["Constitutional Law", "Criminal Law", "Contract Law", "Tort Law", "Property Law", "Family Law", "Administrative Law", "International Law", "Corporate Law", "Environmental Law"],
"Science": ["Physics", "Chemistry", "Biology", "Geology", "Astronomy", "Ecology", "Botany", "Zoology", "Genetics", "Environmental Science"],
"Medicine": ["Anatomy", "Physiology", "Pathology", "Pharmacology", "Microbiology", "Surgery", "Pediatrics", "Internal Medicine", "Psychiatry", "Radiology"],
"Engineering": ["Civil Engineering", "Mechanical Engineering", "Electrical Engineering", "Chemical Engineering", "Aerospace Engineering", "Computer Engineering", "Environmental Engineering", "Industrial Engineering", "Structural Engineering", "Biomedical Engineering"],
"Mathematics": ["Algebra", "Calculus", "Geometry", "Statistics", "Probability", "Number Theory", "Combinatorics", "Topology", "Differential Equations", "Mathematical Logic"],
"Computer Science": ["Algorithms", "Data Structures", "Operating Systems", "Database Systems", "Networks", "Software Engineering", "Artificial Intelligence", "Machine Learning", "Human-Computer Interaction", "Computer Graphics"],
"History": ["Ancient History", "Medieval History", "Modern History", "Economic History", "Military History", "Cultural History", "Political History", "Social History", "Intellectual History", "History of Science"],
"Economics": ["Microeconomics", "Macroeconomics", "Econometrics", "Development Economics", "International Economics", "Labor Economics", "Public Economics", "Industrial Organization", "Behavioral Economics", "Environmental Economics"],
"Psychology": ["Cognitive Psychology", "Developmental Psychology", "Clinical Psychology", "Social Psychology", "Industrial-Organizational Psychology", "Neuropsychology", "Health Psychology", "Forensic Psychology", "Educational Psychology", "Experimental Psychology"],
"Education": ["Curriculum Development", "Educational Psychology", "Instructional Design", "Educational Technology", "Special Education", "Early Childhood Education", "Higher Education", "Adult Education", "Education Policy", "Comparative Education"]
}
# Streamlit App
st.set_page_config(page_title="Interactify")
page = st.sidebar.radio("Select Page", ["Home", "Ask Me About Your Slides", "History"])
if page == "Home":
st.title("Interactify")
# Dropdown for field selection
field = st.selectbox("Select Field", list(fields_subjects.keys()))
# Dropdown for subject selection
subject = st.selectbox("Select Subject", fields_subjects[field])
# File uploader for slides (PDF, Word, PPT, or text) input
uploaded_file = st.file_uploader("Upload Your Document (PDF, DOCX, PPTX, TXT)...", type=["pdf", "docx", "pptx", "txt"])
# Text input for page range
page_range_input = st.text_input("Enter page ranges (e.g., 78-79):")
# Initialize session state for history
if 'history' not in st.session_state:
st.session_state.history = []
# Submit button for processing the document
submit = 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! Use the format 'start-end'.")
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.get(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 copy generated content
st.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 DOCX
if 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'
)
except Exception as e:
st.error(f"Error: {str(e)}")
else:
st.warning("Please upload your document.")
elif page == "Ask Me About Your Slides":
st.title("Ask Me About Your Slides")
# File uploader for slides (PDF, Word, PPT, or text) input
uploaded_file = st.file_uploader("Upload Your Document (PDF, DOCX, PPTX, TXT)...", type=["pdf", "docx", "pptx", "txt"])
# Text area for user question
user_question = st.text_area("Type your question about the document content:")
if uploaded_file and user_question:
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()
# Combine all text for context
full_text = "\n".join(document_text)
question_prompt = f"Based on the content of the document, answer the following question:\n{user_question}\n\nDocument Content:\n{full_text}"
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 and enter your question.")
elif page == "History":
st.title("History")
# Display history
if 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.")
# Footer
st.markdown("---")
st.markdown("© 2024 by Christley")
# Ensure formulas are rendered correctly
st.markdown("For LaTeX formula rendering, use `$` to surround inline formulas, and `$$` for display formulas.")
|