Creating a comprehensive visual study buddy as you've described is an ambitious and rewarding project. We'll break down the development process into manageable components and provide you with a complete Streamlit application that integrates the following features:
- To-Do List Management
- Q&A Generator using RAG Model (with LlamaIndex, LangChain)
- Real-Time Emotion Detection via Webcam
- Responsive Messages Based on Detected Emotions
Given that you're using a Mac and prefer using Ollama instead of OpenAI's API, we'll integrate Ollama for the language model functionalities. Additionally, we'll use Streamlit for the front-end interface, OpenCV and fer library for emotion detection, and other necessary libraries for the backend processes.
Table of Contents
- Prerequisites
- Setting Up the Development Environment
- Emotion Detection Module
- To-Do List Module
- Q&A Generator Module
- Integrating All Modules with Streamlit
- Complete Code
- Running the Application
- Additional Notes
Prerequisites
Before diving into the code, ensure you have the following installed on your Mac:
-
Python 3.7 or later: Ensure you have Python installed. You can check by running python3 --version in your terminal.
-
Homebrew (optional but recommended for installing dependencies like ffmpeg):
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
-
Ollama: Install and set up Ollama as per its official documentation.
-
Git: For version control and possibly using repositories from GitHub.
-
Streamlit: For the web app interface.
pip install streamlit
-
Other Python Libraries: We'll install these in the next section.
Setting Up the Development Environment
Create a new directory for your project and navigate into it:
mkdir visual_study_buddy
cd visual_study_buddy
Create a virtual environment to manage dependencies:
python3 -m venv venv
source venv/bin/activate
Install the necessary Python libraries:
pip install streamlit opencv-python-headless streamlit-webrtc fer pandas langchain llama-index requests pydantic
- streamlit-webrtc: To handle real-time webcam streaming in Streamlit.
- fer: A library for facial emotion recognition.
- langchain and llama-index: For building the Q&A generator with a RAG model.
- pydantic: For data validation.
Emotion Detection Module
We'll use the fer library, which leverages deep learning models to detect emotions from webcam feeds.
Steps:
- Capture Webcam Feed: Use
streamlit-webrtc to capture video from the user's webcam.
- Detect Emotions: Process each frame to detect emotions.
- Display Emotion and Respond: Based on the detected emotion, display appropriate messages.
To-Do List Module
Implement a simple to-do list where users can:
- Add Tasks: Input tasks they need to accomplish.
- Mark Tasks as Completed: Tick off tasks.
- Display Current Task: Highlight the task currently being focused on.
We'll use Streamlit's session state to manage the to-do list.
Q&A Generator Module
This module will allow users to input resources (like a website URL, PDF, or text) and generate Q&A based on the content using a Retrieval-Augmented Generation (RAG) approach.
Steps:
- Input Resource: Users can input a URL, upload a PDF, or paste text.
- Process Input: Extract and index the content using
llama-index.
- Generate Q&A: Use
langchain to query the indexed data and generate questions and answers.
- Display Q&A: Show the generated Q&A to the user.
We'll integrate Ollama as the language model backend.
Integrating All Modules with Streamlit
We'll create a Streamlit app that integrates:
- The To-Do List on the sidebar.
- The Emotion Detection and responsive messages on the main page.
- The Q&A Generator as another section/tab.
Complete Code
Below is the complete code integrating all the components discussed. Save this as app.py in your project directory.
# app.py
import streamlit as st
from streamlit_webrtc import webrtc_streamer, WebRtcMode
from fer import FER
import cv2
import numpy as np
import pandas as pd
from datetime import datetime
import os
from langchain import LLMChain, PromptTemplate
from langchain.llms import BaseLLM
import requests
from pydantic import BaseModel, Field
import json
# Import llama_index and other necessary modules
from llama_index import (
SimpleDirectoryReader,
GPTVectorStoreIndex,
LLMPredictor,
ServiceContext,
)
from langchain.chat_models import ChatOpenAI
# ------------- Constants -------------
# Ollama API endpoint
OLLAMA_API_URL = "http://localhost:11434/v1/perform"
# ------------- Helper Classes and Functions -------------
class OllamaLLM(BaseLLM):
"""Custom LLM wrapper for Ollama."""
@property
def _llm_type(self):
return "ollama"
def _call(self, prompt: str, stop: list = None) -> str:
headers = {"Content-Type": "application/json"}
payload = {"prompt": prompt}
response = requests.post(OLLAMA_API_URL, headers=headers, data=json.dumps(payload))
if response.status_code == 200:
return response.json()["response"]
else:
raise ValueError(f"Ollama API request failed: {response.text}")
def generate_response(prompt: str) -> str:
"""Generates a response using Ollama."""
llm = OllamaLLM()
chain = LLMChain(llm=llm, prompt=PromptTemplate(template="{prompt}", input_variables=["prompt"]))
response = chain.run(prompt=prompt)
return response
def extract_emotion(frame):
"""Detect emotion in a given frame."""
detector = FER(mtcnn=True)
emotions = detector.detect_emotions(frame)
if emotions:
# Assuming the most prominent face
emotions_scores = emotions[0]["emotions"]
dominant_emotion = max(emotions_scores, key=emotions_scores.get)
return dominant_emotion
else:
return None
def get_feedback_message(emotion):
"""Returns a message based on the detected emotion."""
if emotion == "happy":
return "Great to see you're happy! Let's keep the energy up!"
elif emotion == "angry":
return "Take a deep breath. You've got this!"
elif emotion == "sad":
return "Don't be down. You're doing great!"
elif emotion == "surprise":
return "Stay focused and let's continue!"
elif emotion == "neutral":
return "Stay concentrated and keep going!"
else:
return "Keep up the good work!"
# ------------- Streamlit App -------------
def main():
st.set_page_config(page_title="Visual Study Buddy", layout="wide")
st.title("📚 Visual Study Buddy")
# Initialize session state for to-do list
if "todos" not in st.session_state:
st.session_state.todos = []
if "current_task" not in st.session_state:
st.session_state.current_task = ""
# Sidebar - To-Do List
st.sidebar.header("To-Do List")
todo_input = st.sidebar.text_input("Add a new task")
if st.sidebar.button("Add Task"):
if todo_input:
st.session_state.todos.append({"task": todo_input, "completed": False, "timestamp": datetime.now()})
if not st.session_state.current_task:
st.session_state.current_task = todo_input
st.sidebar.success("Task added!")
else:
st.sidebar.error("Please enter a task.")
# Display To-Do List
todos_df = pd.DataFrame(st.session_state.todos)
if not todos_df.empty:
st.sidebar.write("### Your Tasks")
for idx, todo in enumerate(st.session_state.todos):
checkbox = st.sidebar.checkbox(todo["task"], key=f"task_{idx}", value=todo["completed"])
st.session_state.todos[idx]["completed"] = checkbox
if checkbox and st.session_state.current_task == todo["task"]:
# Move to next task
completed = [t for t in st.session_state.todos if t["completed"]]
if len(completed) < len(st.session_state.todos):
next_task = st.session_state.todos[len(completed)]["task"]
st.session_state.current_task = next_task
else:
st.session_state.current_task = ""
st.sidebar.write("---")
st.sidebar.write(f"**Current Task:** {st.session_state.current_task if st.session_state.current_task else 'All tasks completed! 🎉'}")
# Main Area
tab1, tab2 = st.tabs(["Emotion Detection", "Q&A Generator"])
# Tab 1: Emotion Detection
with tab1:
st.header("😊 Emotion Detection")
st.write("The study buddy is monitoring your emotions in real-time.")
# Placeholder for messages
message_placeholder = st.empty()
# WebRTC settings
webrtc_ctx = webrtc_streamer(
key="emotion-detector",
mode=WebRtcMode.SENDONLY,
rtc_configuration={"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]},
media_stream_constraints={"video": True, "audio": False},
async_processing=True,
)
# Process video frames
if webrtc_ctx.video_receiver:
frames = webrtc_ctx.video_receiver.get_frame_iterator()
for frame in frames:
img = frame.to_ndarray(format="bgr24")
emotion = extract_emotion(img)
if emotion:
feedback = get_feedback_message(emotion)
message_placeholder.success(f"Detected Emotion: **{emotion.capitalize()}**")
message_placeholder.info(feedback)
else:
message_placeholder.warning("No face detected.")
# Process each frame only once
break
# Tab 2: Q&A Generator
with tab2:
st.header("❓ Q&A Generator")
st.write("Generate questions and answers based on your study material.")
# Input options
resource_type = st.selectbox("Select Resource Type", ["URL", "PDF", "Text"])
if resource_type == "URL":
url_input = st.text_input("Enter the URL of the webpage")
if st.button("Process URL"):
if url_input:
# Process the URL content
# For simplicity, we'll fetch the text content from the URL
try:
import requests
from bs4 import BeautifulSoup
response = requests.get(url_input)
soup = BeautifulSoup(response.text, 'html.parser')
text = soup.get_text()
# Save to a temporary file
with open("temp_content.txt", "w", encoding='utf-8') as f:
f.write(text)
st.success("URL content processed.")
except Exception as e:
st.error(f"Error processing URL: {e}")
else:
st.error("Please enter a URL.")
elif resource_type == "PDF":
pdf_upload = st.file_uploader("Upload a PDF file", type=["pdf"])
if pdf_upload and st.button("Process PDF"):
try:
import PyPDF2
reader = PyPDF2.PdfReader(pdf_upload)
text = ""
for page in reader.pages:
text += page.extract_text() + "\n"
# Save to a temporary file
with open("temp_content.txt", "w", encoding='utf-8') as f:
f.write(text)
st.success("PDF content processed.")
except Exception as e:
st.error(f"Error processing PDF: {e}")
elif resource_type == "Text":
text_input = st.text_area("Enter your study text here")
if st.button("Process Text"):
if text_input:
with open("temp_content.txt", "w", encoding='utf-8') as f:
f.write(text_input)
st.success("Text content processed.")
else:
st.error("Please enter some text.")
# Q&A Generation
if os.path.exists("temp_content.txt"):
if st.button("Generate Q&A"):
try:
# Initialize LlamaIndex
documents = SimpleDirectoryReader('.').load_data()
llm_predictor = LLMPredictor(llm=OllamaLLM())
service_context = ServiceContext.from_defaults(llm_predictor=llm_predictor)
index = GPTVectorStoreIndex.from_documents(documents, service_context=service_context)
# Query the index
query = st.text_input("Enter your question here")
if st.button("Get Answer"):
if query:
response = index.as_query_engine().query(query)
st.write("**Q:**", query)
st.write("**A:**", response)
else:
st.error("Please enter a question.")
except Exception as e:
st.error(f"Error generating Q&A: {e}")
else:
st.info("Please process a resource to generate Q&A.")
st.sidebar.write("---")
st.sidebar.write("Developed by [Your Name]")
if __name__ == "__main__":
main()
Explanation of the Code
Let's break down the key components of the code:
-
Imports and Dependencies:
- streamlit: For creating the web app.
- streamlit_webrtc: To access the webcam for emotion detection.
- fer: For emotion recognition from video frames.
- langchain, llama_index: For building the Q&A generator with a RAG model.
- OllamaLLM: A custom class to interface with Ollama's API.
-
OllamaLLM Class:
- A custom Language Model (LLM) wrapper that sends prompts to the Ollama API and retrieves responses.
- Adjust the
OLLAMA_API_URL if your Ollama instance is running on a different URL or port.
-
Emotion Detection Functions:
extract_emotion: Uses fer to detect the dominant emotion in a video frame.
get_feedback_message: Returns a tailored message based on the detected emotion.
-
Streamlit App Structure:
- Sidebar:
- To-Do List management where users can add tasks, mark them as completed, and view the current task.
- Main Area:
- Tabs: "Emotion Detection" and "Q&A Generator".
-
Emotion Detection Tab:
- Accesses the webcam and processes video frames to detect emotions.
- Displays the detected emotion and a corresponding message.
-
Q&A Generator Tab:
- Allows users to input a resource (URL, PDF, or Text).
- Processes the input to extract text content.
- Uses
llama_index and langchain with the custom OllamaLLM to generate answers based on user questions.
-
To-Do List Management:
- Uses Streamlit's
session_state to persist tasks across user interactions.
- Allows adding new tasks and marking existing tasks as completed.
- Highlights the current task being worked on.
Running the Application
-
Ensure Ollama is Running:
- Start your Ollama server and ensure it's listening on the URL and port specified in
OLLAMA_API_URL.
- For example, if Ollama is running locally on port
11434, the URL should be http://localhost:11434/v1/perform.
-
Activate Virtual Environment:
source venv/bin/activate
-
Install Additional Dependencies:
-
Run the Streamlit App:
streamlit run app.py
-
Access the App:
- After running, Streamlit will provide a local URL (e.g.,
http://localhost:8501) where you can interact with your Visual Study Buddy.
Additional Notes
-
Emotion Detection Performance:
- The
fer library works best with clear frontal faces. Ensure good lighting and position the webcam appropriately.
- Depending on your Mac's camera quality and processing power, real-time emotion detection might have lags.
-
Ollama Integration:
- Ensure that Ollama's API is correctly set up and accessible from your network.
- Adjust the
OLLAMA_API_URL in the code if Ollama runs on a different endpoint.
-
Security Considerations:
- If deploying this app publicly, ensure that proper security measures are in place, especially since it accesses the user's webcam.
- Streamlit provides authentication mechanisms and deployment options that can be explored.
-
Enhancements:
- Persistent Storage: Implement a database (like SQLite) to persist the to-do list and other user data across sessions.
- Enhanced Q&A: Improve the Q&A generator by handling more complex queries and supporting additional resource types.
- User Authentication: Allow multiple users to have their own profiles and data.
-
Error Handling:
- The provided code includes basic error handling. Consider adding more robust mechanisms to handle unexpected errors gracefully.
-
Performance Optimization:
- Processing every video frame can be resource-intensive. Consider optimizing by processing frames at intervals.
This comprehensive guide and code should help you build your Visual Study Buddy. Feel free to customize and enhance the application further to suit your specific needs. Happy coding!