# Project export: HiveMind

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: TreeHacks 2025
- Tagline: HiveMind: Your Second Brain for Smarter Learning.
- Devpost: https://devpost.com/software/hivemind-18cula
- GitHub: https://github.com/rajashekarcs2023/HiveMind
- Demo: https://github.com/rajashekarcs2023/knowledge-balance-network
- Video: https://www.youtube.com/embed/krXZVuJfAOQ?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Result: winner (Education Grand Prize ($1k Cash + Meta Ray Ban Smart Glasses x4 + Marine Layer Zoom Hoodie x4))
- Team: 1 GitHub contributor(s) — rajashekarcs2023 (8 commits)

## Devpost submission (written by the team)

### Overview

Problem Education is one of the most powerful tools for personal and professional growth, yet the way knowledge is imparted remains largely standardized and inflexible. Many students struggle with course material because traditional learning methods fail to cater to individual learning needs. Some students grasp concepts quickly, while others require additional time and explanation, leading to gaps in comprehension that affect academic performance and long-term retention. Moreover, collaboration and peer learning opportunities are often limited, leaving students to navigate their academic struggles alone. Some students grasp concepts effortlessly and can help their peers, but there is no structured way to connect them. Our goal is to change this by creating an intelligent, AI-driven educational platform that adapts to each student’s needs, making learning more effective, engaging, and inclusive.

### Inspiration

The idea for HiveMind was born from observing the disparity in student learning experiences, and have a framework based system to collectively improve everyone in the class week by week, leaving no one behind. We created a system that fosters collaborative learning environment, collective growth and collective improvement until everyone in the class is on same level of understanding and comprehension.

### What it does

HiveMind is an AI-powered educational platform that enhances student learning through continuous collective growth through peer learning sessions. By seamlessly integrating with online learning environments, the platform analyzes student responses and categorizes them into different levels of understanding. This classification enables the system to provide tailored support, ensuring that students who need extra help receive it, while those who have mastered concepts can reinforce their knowledge by guiding others. The platform assesses student performance through AI-driven quizzes and assignments, determining their comprehension levels. Based on this analysis, students are placed into one of four learning hubs: those requiring foundational support, those needing additional clarification, those who have a strong grasp of concepts, and those who have achieved mastery. This hub is made up of a right balance of 4 students and this matching is done by the custom algorithm. The system then facilitates peer matching, allowing students with higher scores to assist those in lower scores. Additionally, Its seamless integration with existing learning platforms ensures that students receive real-time feedback and targeted support without disrupting their educational workflow.

### How we built it

HiveMind was developed using a combination of advanced web technologies, machine learning frameworks, and 3D visualization tools. Our backend, built with Python, manages data processing, user authentication, and AI-driven assessments. We implemented custom algorithms to evaluate student performance, generating meaningful insights that adapt to their learning needs. The frontend, developed with TypeScript, Three.js, and Next.js, provides an intuitive interface where students can track their progress through an interactive 3D brain visualization. To enable real-time peer matching and vector-based assessments, we incorporated vector embeddings using IRIS Vector database, and Perplexity Sonar API reasoning that analyze student responses and categorize them accordingly. These embeddings are stored efficiently to facilitate quick retrieval, ensuring smooth transitions between different learning levels. Once the peers are matched, they will go through a Zoom session which is monitored by an AI agent which evaluates the progress of the student as well as the hub. Throughout the development process, we optimized the platform for scalability, ensuring that HiveMind could accommodate a growing number of users without performance bottlenecks. The integration of AI, real-time analytics, and peer-to-peer networking allowed us to create a seamless experience that enhances student engagement.

### Challenges we ran into

One of the biggest challenges we faced was merging the 3D dashboard into our existing system, which already included vector embeddings and a peer-to-peer network. This led to numerous Git merge conflicts, causing unexpected issues that disrupted our workflow. With time running out, we had to make a critical decision—to start fresh with a new GitHub repository in the final hours of development. This shift required us to carefully migrate existing functionalities while ensuring that all components remained fully functional. Rendering the 3D brain visualization was another major hurdle. Achieving a balance between performance and visual appeal proved difficult, as real-time interactions required optimized rendering techniques. We experimented with various configurations in Three.js, adjusting parameters to ensure smooth animations and intuitive navigation. Additionally, maintaining compatibility across different devices added another layer of complexity, as rendering performance varied based on system specifications. Despite these challenges, our team remained persistent, debugging issues, restructuring code, and finding creative solutions to ensure that HiveMind functioned as intended. Overcoming these obstacles reinforced our teamwork and problem-solving skills, making the final product even more rewarding.

### Accomplishments we're proud of

Building HiveMind was an ambitious challenge, and we are proud of what we have achieved so far. One of our biggest accomplishments is successfully implementing an AI-driven assessment system that evaluates student comprehension in real-time. Our machine learning models accurately categorize students based on their understanding, enabling tailored learning experiences that adapt dynamically to individual needs. We also developed a structured peer-matching system that facilitates collaboration between students at different knowledge levels, fostering a strong sense of community and support within the platform. Another major achievement is our intuitive , which provides students with a clear and interactive representation of their learning progress. By integrating AI-driven insights with visually appealing analytics, we have transformed the way students perceive their academic journey. Additionally, our backend infrastructure is optimized for scalability, ensuring that HiveMind can handle a growing number of users without compromising performance. Successfully integrating the platform with online learning tools while maintaining a seamless user experience was a significant milestone that highlights our technical expertise and problem-solving abilities.

### What we learned

Throughout the development of HiveMind, we encountered numerous challenges that pushed us to think critically and innovate. One of the most valuable lessons we learned was the importance of real-time processing in educational platforms. Immediate feedback is crucial for student engagement, and optimizing our AI models to deliver quick yet accurate assessments requires extensive experimentation and fine-tuning. We also gained a deeper understanding of the complexities involved in integrating AI-driven tools with existing educational platforms. Ensuring compatibility with learning management systems, designing efficient data pipelines, and maintaining user privacy were all critical considerations that shaped our development process. Furthermore, we realized that while AI can enhance learning, human interaction remains an essential element of education. This insight reinforced our belief in combining AI-driven recommendations with peer-based learning to create a balanced and effective system. From a user experience perspective, we learned the significance of designing interfaces that encourage participation without overwhelming students. Keeping the UI simple yet powerful was a challenge that required iterative testing and feedback. Understanding the psychology of learning and motivation helped us refine our platform to make it more engaging and beneficial for students.

### What's next

HiveMind is only at the beginning of its journey, and we have exciting plans for its future. One of our key next steps is integrating the platform with Zoom, enabling real-time transcription and AI-powered suggestions during class discussions. This feature will enhance virtual learning by providing students with relevant questions, summaries, and recommendations, making online education more interactive and insightful. We also aim to enhance our adaptive learning models to provide even more personalized learning paths. By refining our AI algorithms, we can ensure that each student receives targeted resources and exercises tailored to their specific needs. Another major focus is incorporating gamification elements, such as achievement badges, leaderboard rankings, and interactive challenges, to keep students motivated and engaged throughout their learning journey. In the long term, we plan to expand HiveMind’s reach by forming partnerships with universities, online learning platforms, and EdTech companies. By integrating our system into large-scale educational environments, we can impact a wider audience and help bridge learning gaps across diverse student populations. Our vision is to make education more personalized, collaborative, and accessible, ensuring that every student has the tools they need to succeed.

## README (from the GitHub repository)

# HiveMind
### **🚀 Data Points: What Really Matters for Learning & Vector Search?**
Our system plan is to **captures true learning states, mental models, and progressions** and store them as vector embeddings.

---

## **📌 Learning States: What Do We Really Want to Capture?**
Instead of just tracking **what students do**, we will **capture how they learn** by focusing on **cognitive patterns** rather than simple engagement metrics.

| **Dimension** | **Why It’s Important** | **Better Data Points to Capture** |
|--------------|-----------------------|--------------------------------|
| **Cognitive State** | Tracks how well a student **grasps concepts** | - Confidence level (self-reported after a lesson) <br> - Knowledge decay (time since last correct answer) <br> - Concept reinforcement need (based on mistakes over time) |
| **Mental Model Evolution** | Represents how a student **connects different ideas** | - Concept transition map (which concepts were easy vs. difficult) <br> - Misconceptions (identified from common wrong answers) <br> - Thought process analysis (how they break down a problem) |
| **Pattern Recognition Ability** | Determines whether a student **can generalize knowledge** | - How often do they solve new problems **without hints**? <br> - Do they get stuck on the **same type of problem**? <br> - Do they struggle more on **abstract vs. concrete topics**? |
| **Learning Modality & Adaptation** | Determines the best way they learn **over time** | - Do they learn best via **case studies, visual demos, or hands-on exercises**? <br> - Do they need **personalized reinforcement on weak areas**? <br> - Do they adapt to **new types of problems easily**? |
| **Frustration vs. Flow State** | Measures when a student **gets frustrated or engaged** | - Do they abandon topics frequently? <br> - How long do they stay engaged on difficult material? <br> - How does their pace change **when facing new concepts**? |

---

## **📌 The Better Data Points We Should Capture for Vectorization**
### **1️⃣ Cognitive Understanding Score (Self-Reported & AI-Assessed)**
- **After each lesson or quiz, students rate their confidence** in a concept from **1-10**.
- AI **adjusts their real confidence score** based on **quiz performance** and **error patterns**.

📌 **Example Data to Capture:**
| User_ID | Topic | Self-Reported Confidence | AI-Adjusted Confidence | Errors Made |
|---------|-------|-------------------------|------------------------|-------------|
| user_001 | Backpropagation | 7/10 | 4/10 | Misused activation function |
| user_002 | Transformer Models | 6/10 | 6/10 | Incorrect token embedding |
| user_003 | Reinforcement Learning | 5/10 | 3/10 | Confused reward shaping |

🔹 **Why This Matters?**  
✅ **AI can recommend reinforcement learning material** for students who think they understand a concept but actually don’t.  
✅ **Confidence mismatches are vectorized**, so we can **compare similar struggling students** and **match them to successful learners**.

---

### **2️⃣ Misconception Tracking (Concept Evolution Map)**
- Instead of just logging **quiz scores**, we log **WHY the student got it wrong**.
- Misconceptions get vectorized so AI can **suggest targeted corrections**.

📌 **Example Data to Capture:**
| User_ID | Topic | Misconception | Suggested Fix |
|---------|-------|--------------|---------------|
| user_001 | Neural Networks | Thought "weight updates" happen per layer, not per neuron | "Visualize per-neuron weight changes in backpropagation" |
| user_002 | Transformer Models | Confused **attention weights** with positional encoding | "Try breaking down transformer layers step by step" |

🔹 **Why This Matters?**  
✅ **Vectorizing misconceptions allows AI to cluster students who make similar mistakes** and correct them faster.  
✅ **Instead of repeating entire lessons, students get ultra-personalized corrections.**  

---

### **3️⃣ Learning Transition Paths (How Well Do They Generalize?)**
- **Does the student learn concept A → B smoothly, or do they struggle?**
- AI **detects when a student struggles to transition to a related concept**.

📌 **Example Data to Capture:**
| User_ID | Topic | Previous Concept | Transition Difficulty |
|---------|-------|----------------|----------------------|
| user_001 | Recurrent Networks | Fully Connected Layers | HIGH |
| user_002 | Word Embeddings | N-Grams | MEDIUM |
| user_003 | Convolutional Networks | Edge Detection | LOW |

🔹 **Why This Matters?**  
✅ If many students struggle with **Concept A → Concept B**, AI **suggests a better bridge topic or analogy**.  
✅ Vector search can **retrieve personalized reinforcement exercises** for transition problems.  

---

### **4️⃣ Learning Modality (Do They Learn Better Through Video, Coding, or Text?)**
- AI **tracks learning mode effectiveness** for each student.
- If a student **performs better after coding exercises** than after watching a video, AI **adjusts their content recommendations.**

📌 **Example Data to Capture:**
| User_ID | Topic | Modality | Success Rate |
|---------|-------|---------|--------------|
| user_001 | Backpropagation | Video | 40% |
| user_002 | Backpropagation | Coding Exercise | 80% |
| user_003 | Backpropagation | Peer Discussion | 60% |

🔹 **Why This Matters?**  
✅ Instead of a **one-size-fits-all curriculum**, students get **content in their most effective learning mode.**  
✅ AI can **recommend peer mentors** based on similar learning styles.  

---

### **5️⃣ Frustration vs. Flow State Detection**
- Tracks **when students quit, rage-click, or slow down significantly**.
- If **frustration is detected**, AI can **intervene with alternative explanations or a break recommendation.**

📌 **Example Data to Capture:**
| User_ID | Topic | Learning Pace | Frustration Detected? |
|---------|-------|--------------|----------------------|
| user_001 | LSTMs | 2x Slower than usual | Yes |
| user_002 | CNNs | Normal Speed | No |

🔹 **Why This Matters?**  
✅ AI **doesn't just recommend new topics—it knows when a student needs a break.**  
✅ Vector search **retrieves frustration-related insights** from other students who struggled with the same topic.

---

## **📌 New CSV Structure for Vectorization**
### **Before Vectorization (Raw Data)**
| User_ID | Topic | Self-Confidence | AI-Adjusted Confidence | Errors | Transition Difficulty | Learning Modality | Frustration |
|---------|-------|----------------|------------------------|--------|----------------------|-----------------|-------------|
| user_001 | Backpropagation | 7 | 4 | Misused Activation | HIGH | Coding | Yes |
| user_002 | Word Embeddings | 6 | 6 | Confused Attention Weights | MEDIUM | Text | No |

### **After Vectorization (Stored in IRIS Vector DB)**
| User_ID | Learning_State_Vector |
|---------|-----------------------|
| user_001 | `[0.25, -0.78, 0.61, -0.42, 0.33]` |
| user_002 | `[0.55, 0.21, -0.47, 0.88, -0.33]` |

🔹 **Now, AI can retrieve students who share similar learning states and suggest improvements based on past learners.**  


## Detected evidence (automated analysis)

Indexed codebase: 204 recognized source files, 383 KB.
- CSS (language) — detected in the code
- FastAPI (technology) — detected in the code
- Firebase (technology) — detected in the code
- HTML (language) — detected in the code
- JavaScript (language) — detected in the code
- Next.js (technology) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- Supabase (technology) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code
- Flask (technology) — claimed on Devpost, not found in the code
- Google Gemini (technology) — claimed on Devpost, not found in the code
- Streamlit (technology) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (120 of 233)

```
.DS_Store
app/.DS_Store
app/api/matching.py
app/main.py
backend/.DS_Store
backend/app/api/routes.py
backend/app/database/__init__.py
backend/app/database/iris_client.py
backend/app/database/setup.py
backend/app/database/setup1.py
backend/app/database/supabase_client.py
backend/app/main.py
backend/app/main1.py
backend/app/models/schemas.py
backend/app/scripts/__init__.py
backend/app/scripts/prepare_data.py
backend/app/scripts/prepare_data1.py
backend/app/services/__init__.py
backend/app/services/vector_search.py
backend/app/services/vector_search1.py
backend/install/intersystems_irispython-5.0.1-8026-cp38.cp39.cp310.cp311.cp312-cp38.cp39.cp310.cp311.cp312-macosx_10_9_universal2.whl
backend/install/intersystems_irispython-5.0.1-8026-cp38.cp39.cp310.cp311.cp312-cp38.cp39.cp310.cp311.cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
backend/install/intersystems_irispython-5.0.1-8026-cp38.cp39.cp310.cp311.cp312-cp38.cp39.cp310.cp311.cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
backend/install/intersystems_irispython-5.0.1-8026-cp38.cp39.cp310.cp311.cp312-cp38.cp39.cp310.cp311.cp312-win_amd64.whl
backend/install/intersystems_irispython-5.0.1-8026-cp38.cp39.cp310.cp311.cp312-cp38.cp39.cp310.cp311.cp312-win32.whl
backend/iristest.py
backend/knowledge-network/.gitignore
backend/knowledge-network/components.json
backend/knowledge-network/next.config.ts
backend/knowledge-network/package.json
backend/knowledge-network/postcss.config.mjs
backend/knowledge-network/README.md
backend/knowledge-network/src/app/ai-assistant/page.tsx
backend/knowledge-network/src/app/api/ai/chat/route.ts
backend/knowledge-network/src/app/api/auth/[...nextauth]/route.ts
backend/knowledge-network/src/app/assessment/[subjectId]/intro/page.tsx
backend/knowledge-network/src/app/assessment/[subjectId]/matching/page.tsx
backend/knowledge-network/src/app/assessment/[subjectId]/results/page.tsx
backend/knowledge-network/src/app/assessment/[subjectId]/take/page.tsx
backend/knowledge-network/src/app/assessment/page.tsx
backend/knowledge-network/src/app/assessment/results/page.tsx
backend/knowledge-network/src/app/assessment/take/page.tsx
backend/knowledge-network/src/app/globals.css
backend/knowledge-network/src/app/groups/[groupId]/page.tsx
backend/knowledge-network/src/app/groups/page.tsx
backend/knowledge-network/src/app/hive-intelligence/page.tsx
backend/knowledge-network/src/app/layout.tsx
backend/knowledge-network/src/app/network-balance/page.tsx
backend/knowledge-network/src/app/page.tsx
backend/knowledge-network/src/app/profile/page.tsx
backend/knowledge-network/src/components/ai/ChatHistory.tsx
backend/knowledge-network/src/components/ai/ChatInput.tsx
backend/knowledge-network/src/components/ai/ChatWindow.tsx
backend/knowledge-network/src/components/ai/index.ts
backend/knowledge-network/src/components/ai/NotesContext.tsx
backend/knowledge-network/src/components/ai/SubjectsList.tsx
backend/knowledge-network/src/components/dashboard/DashboardStats.tsx
backend/knowledge-network/src/components/dashboard/StudentDashboard.tsx
backend/knowledge-network/src/components/graphs/KnowledgeGraph.tsx
backend/knowledge-network/src/components/groups/ConceptualGapAnalysis.tsx
backend/knowledge-network/src/components/groups/GroupDetailedView.tsx
backend/knowledge-network/src/components/groups/GroupDetailView.tsx
backend/knowledge-network/src/components/groups/GroupFeed.tsx
backend/knowledge-network/src/components/groups/HubMetrics.tsx
backend/knowledge-network/src/components/groups/PeerSessionScheduler.tsx
backend/knowledge-network/src/components/intelligence/AIInsightsPanel.tsx
backend/knowledge-network/src/components/intelligence/index.ts
backend/knowledge-network/src/components/intelligence/TrendingClusters.tsx
backend/knowledge-network/src/components/layout/ClientLayout.tsx
backend/knowledge-network/src/components/layout/index.ts
backend/knowledge-network/src/components/layout/MainLayout.tsx
backend/knowledge-network/src/components/layout/Sidebar.tsx
backend/knowledge-network/src/components/network/SubjectHubVisualizer.tsx
backend/knowledge-network/src/components/search/SmartSearchBar.tsx
backend/knowledge-network/src/components/ui/button.tsx
backend/knowledge-network/src/components/ui/card.tsx
backend/knowledge-network/src/components/ui/input.tsx
backend/knowledge-network/src/components/ui/resizable.tsx
backend/knowledge-network/src/constants/index.ts
backend/knowledge-network/src/hooks/useAssessment.ts
backend/knowledge-network/src/hooks/useGroupData.ts
backend/knowledge-network/src/lib/utils.ts
backend/knowledge-network/src/services/assessment.ts
backend/knowledge-network/src/services/groups.ts
backend/knowledge-network/src/services/users.ts
backend/knowledge-network/src/styles/globals.css
backend/knowledge-network/src/types/assessment.ts
backend/knowledge-network/src/types/global.d.ts
backend/knowledge-network/src/types/group.ts
backend/knowledge-network/src/types/index.ts
backend/knowledge-network/src/types/next-auth.d.ts
backend/knowledge-network/src/types/speech-recognition.d.ts
backend/knowledge-network/src/types/subjects.ts
backend/knowledge-network/src/types/user.ts
backend/knowledge-network/src/utils/analytics.ts
backend/knowledge-network/src/utils/api.ts
backend/knowledge-network/tailwind.config.ts
backend/knowledge-network/tsconfig.json
backend/matching_system.py
backend/qdrant_db/.lock
backend/qdrant_db/collection/knowledge_network/storage.sqlite
backend/qdrant_db/meta.json
backend/requirements.txt
backend/sonar_genhub.py
backend/test_connection.py
backend/Users:radhikadanda:knowledg 2.textClipping
backend/Users:radhikadanda:knowledg 3.textClipping
backend/Users:radhikadanda:knowledg 4.textClipping
backend/Users:radhikadanda:knowledg.textClipping
backend/view_data.py
Hivemind Landing Page/.gitignore
Hivemind Landing Page/backend/main.py
Hivemind Landing Page/dashboard.html
Hivemind Landing Page/eslint.config.js
Hivemind Landing Page/frontend/index.html
Hivemind Landing Page/frontend/script.js
Hivemind Landing Page/frontend/styles.css
Hivemind Landing Page/index.html
Hivemind Landing Page/package.json
Hivemind Landing Page/public/brain_gltf/scene.gltf
[113 more files omitted for size]
```

### Dependencies

- backend/knowledge-network/package.json: @heroicons/react@^2.2.0, @radix-ui/react-slot@^1.1.2, @types/d3@^7.4.3, @types/node@^20, @types/react@^19.0.8, @types/react-dom@^19.0.3, class-variance-authority@^0.7.1, clsx@^2.1.1, d3@^7.9.0, date-fns@^4.1.0, lucide-react@^0.475.0, next@15.1.7, next-auth@^4.24.11, postcss@^8, react@^19.0.0, react-dom@^19.0.0, react-markdown@^9.0.3, react-resizable-panels@^2.1.7, react-split@^2.0.14, tailwind-merge@^3.0.1, tailwindcss@^3.4.1, tailwindcss-animate@^1.0.7, typescript@^5
- backend/requirements.txt: fastapi, pandas, python-dotenv, qdrant-client@>=1.7.0, requests, sentence-transformers@>=2.0.0, supabase, uvicorn
- Hivemind Landing Page/package.json: @eslint/js@^9.19.0, @react-three/drei@^9.121.5, @react-three/fiber@^8.17.14, @tailwindcss/vite@^4.0.6, @types/react@^19.0.8, @types/react-dom@^19.0.3, @vitejs/plugin-react@^4.3.4, eslint@^9.19.0, eslint-plugin-react@^7.37.4, eslint-plugin-react-hooks@^5.0.0, eslint-plugin-react-refresh@^0.4.18, firebase@^11.3.1, globals@^15.14.0, lucide-react@^0.475.0, react@^18.3.1, react-dom@^18.3.1, react-dropzone@^14.3.5, react-just-parallax@^3.1.16, react-router-dom@^7.1.5, scroll-lock@^2.1.5, tailwindcss@^4.0.6, three@^0.173.0, vite@^6.1.0
- knowledge-network/package.json: @heroicons/react@^2.2.0, @radix-ui/react-slot@^1.1.2, @types/d3@^7.4.3, @types/node@^20, @types/react@^19.0.8, @types/react-dom@^19.0.3, class-variance-authority@^0.7.1, clsx@^2.1.1, d3@^7.9.0, date-fns@^4.1.0, lucide-react@^0.475.0, next@15.1.7, next-auth@^4.24.11, postcss@^8, react@^19.0.0, react-dom@^19.0.0, react-markdown@^9.0.3, react-resizable-panels@^2.1.7, react-split@^2.0.14, tailwind-merge@^3.0.1, tailwindcss@^3.4.1, tailwindcss-animate@^1.0.7, typescript@^5

### Recent commits (newest first)

- merged two repos into one
- combined the repos
- Combined two GitHub repos
- Update README.md
- Merge remote-tracking branch 'origin/main'
- final commit ui
- Update README.md
- commit all backend
- commit all
- commit the clean frontend
- commit hive intelligence
- frontend commit
- basic structure completed
- Initial commit

## Key source files (fetched from GitHub, selected and truncated for size)

### backend/requirements.txt

```
# requirements.txt
supabase
python-dotenv
fastapi
uvicorn
requests
pandas
sentence-transformers>=2.0.0
qdrant-client>=1.7.0
```

### knowledge-network/package.json

```
{
  "name": "knowledge-network",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@heroicons/react": "^2.2.0",
    "@radix-ui/react-slot": "^1.1.2",
    "@types/d3": "^7.4.3",
    "class-variance-authority": "^0.7.1",
    "clsx": "^2.1.1",
    "d3": "^7.9.0",
    "date-fns": "^4.1.0",
    "lucide-react": "^0.475.0",
    "next": "15.1.7",
    "next-auth": "^4.24.11",
    "react": "^19.0.0",
    "react-dom": "^19.0.0",
    "react-markdown": "^9.0.3",
    "react-resizable-panels": "^2.1.7",
    "react-split": "^2.0.14",
    "tailwind-merge": "^3.0.1",
    "tailwindcss-animate": "^1.0.7"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^19.0.8",
    "@types/react-dom": "^19.0.3",
    "postcss": "^8",
    "tailwindcss": "^3.4.1",
    "typescript": "^5"
  }
}

```

### Hivemind Landing Page/package.json

```
{
  "name": "treehackshivemind",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint .",
    "preview": "vite preview"
  },
  "dependencies": {
    "@react-three/drei": "^9.121.5",
    "@react-three/fiber": "^8.17.14",
    "@tailwindcss/vite": "^4.0.6",
    "firebase": "^11.3.1",
    "lucide-react": "^0.475.0",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-dropzone": "^14.3.5",
    "react-just-parallax": "^3.1.16",
    "react-router-dom": "^7.1.5",
    "scroll-lock": "^2.1.5",
    "tailwindcss": "^4.0.6",
    "three": "^0.173.0"
  },
  "devDependencies": {
    "@eslint/js": "^9.19.0",
    "@types/react": "^19.0.8",
    "@types/react-dom": "^19.0.3",
    "@vitejs/plugin-react": "^4.3.4",
    "eslint": "^9.19.0",
    "eslint-plugin-react": "^7.37.4",
    "eslint-plugin-react-hooks": "^5.0.0",
    "eslint-plugin-react-refresh": "^0.4.18",
    "globals": "^15.14.0",
    "vite": "^6.1.0"
  }
}

```

### backend/knowledge-network/package.json

```
{
  "name": "knowledge-network",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@heroicons/react": "^2.2.0",
    "@radix-ui/react-slot": "^1.1.2",
    "@types/d3": "^7.4.3",
    "class-variance-authority": "^0.7.1",
    "clsx": "^2.1.1",
    "d3": "^7.9.0",
    "date-fns": "^4.1.0",
    "lucide-react": "^0.475.0",
    "next": "15.1.7",
    "next-auth": "^4.24.11",
    "react": "^19.0.0",
    "react-dom": "^19.0.0",
    "react-markdown": "^9.0.3",
    "react-resizable-panels": "^2.1.7",
    "react-split": "^2.0.14",
    "tailwind-merge": "^3.0.1",
    "tailwindcss-animate": "^1.0.7"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^19.0.8",
    "@types/react-dom": "^19.0.3",
    "postcss": "^8",
    "tailwindcss": "^3.4.1",
    "typescript": "^5"
  }
}

```

### app/main.py

```python
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.matching import router as matching_router

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(matching_router) 
```

### Hivemind Landing Page/src/main.jsx

```javascript
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import './index.css';

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);
```

### Hivemind Landing Page/src/App.jsx

```javascript
import './index.css'
import { Routes, Route, useLocation } from 'react-router-dom';
import Header from './components/Header';
import Hero from './components/Hero';
import Benefits from './components/Benifits';
import Collaboration from './components/Collaboration';
import Services from './components/Services';
import Roadmap from './components/Roadmap';
import Dashboard from './pages/Dashboard';
import BrainModel from './components/BrainModel';
import { DifferentialEquationsPage, DSAPage, FluidMechanicsPage } from './pages/SubjectPages';
import BrainCanvas from './components/BrainModel';

// Homepage component that contains all the landing page sections
const HomePage = () => (
  <div className="pt-20 lg:pt-24 overflow-hidden">
    <Header />
    <Hero />
    <Benefits />
    <Collaboration />
    <Services />
    <Roadmap />
  </div>
);

function App() { 
  const location = useLocation();
  const isHomePage = location.pathname === '/';

  return (
    <>
      {/* Only show Header on non-subject pages */}
      {isHomePage && <Header />}
      
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/dashboard" element={<Dashboard />} />
        <Route path="/differential-equations" element={<DifferentialEquationsPage />} />
        <Route path="/dsa" element={<DSAPage />} />
        <Route path="/fluid-mechanics" element={<FluidMechanicsPage />} />
      </Routes>
    </>
  );
}

export default App;
```

### Hivemind Landing Page/backend/main.py

```python
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Dict
import openai
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import Qdrant
from langchain_community.chat_models import ChatOpenAI
from langchain.text_splitter import RecursiveCharacterTextSplitter
import os
from dotenv import load_dotenv
from qdrant_client import QdrantClient

load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

client = QdrantClient(host="localhost", port=6333)
embeddings = OpenAIEmbeddings()
vector_store = Qdrant(
    client=client,
    collection_name="notes",
    embeddings=embeddings,
)

class Note(BaseModel):
    content: str
    metadata: Dict = {}

class Query(BaseModel):
    question: str

notes_db = []

@app.post("/upload")
async def upload_note(note: Note):
    try:
        # Split text into chunks
        text_splitter = RecursiveCharacterTextSplitter(
            chunk_size=1000,
            chunk_overlap=200
        )
        chunks = text_splitter.split_text(note.content)
        
        # Add to vector store
        vector_store.add_texts(
            texts=chunks,
            metadatas=[note.metadata for _ in chunks]
        )
        
        notes_db.append(note)
        return {"message": "Note uploaded successfully"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/query")
async def query_notes(query: Query):
    try:
        if not notes_db:
            raise HTTPException(status_code=404, detail="No notes found")
        
        # Search for relevant documents
        docs = vector_store.similarity_search(query.question, k=3)
        
        # Prepare context
        context = "\n\n".join([doc.page_content for doc in docs])
        
        # Generate response
        llm = ChatOpenAI(temperature=0.7)
        prompt = f"""Based on these notes, please answer the question.
        Only use information from the provided notes.

        Notes:
        {context}

        Question: {query.question}

        Answer:"""
        
        response = llm.predict(prompt)
        return {"response": response}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

```

### backend/app/main.py

```python
# main.py
import os
os.environ["TOKENIZERS_PARALLELISM"] = "false"
import pathlib

from fastapi import FastAPI, HTTPException, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional
import iris
import os
import tempfile
from dotenv import load_dotenv
from openai import OpenAI
from langchain_community.document_loaders import PyPDFLoader, TextLoader
from langchain.text_splitter import CharacterTextSplitter
from qdrant_client import QdrantClient
from qdrant_client.http import models
from sentence_transformers import SentenceTransformer
from app.services.vector_search import VectorSearch
from app.services.vector_search1 import VectorSearch1
from app.models.schemas import SearchQuery, SearchResult
from uuid import uuid4

# Create data directory if it doesn't exist
data_dir = pathlib.Path("data")
data_dir.mkdir(exist_ok=True)

# Initialize FastAPI app
app = FastAPI(title="Knowledge Balance Network")
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Load environment variables
load_dotenv()

# IRIS Database connection setup
try:
    username = 'demo'
    password = 'demo'
    hostname = os.getenv('IRIS_HOSTNAME', 'localhost')
    port = '1972'
    namespace = 'USER'
    CONNECTION_STRING = f"{hostname}:{port}/{namespace}"
    
    print(f"Connecting to IRIS database: {CONNECTION_STRING}")
    conn = iris.connect(CONNECTION_STRING, username, password)
    cursor = conn.cursor()
    
    # Initialize vector search for IRIS
    vector_search = VectorSearch(cursor)
    learning_groups_search = VectorSearch1(cursor)  
    
    print("Successfully initialized IRIS vector search")
    
except Exception as e:
    print(f"Failed to initialize IRIS database connection: {str(e)}")
    raise

# Initialize Qdrant client (local)
qdrant_client = QdrantClient(path="./qdrant_db")
# Or for cloud: QdrantClient(host="localhost", port=6333)

# Initialize the encoder
encoder = SentenceTransformer('all-MiniLM-L6-v2')

# Create collection if it doesn't exist
try:
    qdrant_client.create_collection(
        collection_name="knowledge_network",
        vectors_config=models.VectorParams(
            size=encoder.get_sentence_embedding_dimension(),
            distance=models.Distance.COSINE
        )
    )
except Exception:
    pass  # Collection already exists

def process_file(file_path: str) -> List[str]:
    """Process uploaded files and split into smaller chunks"""
    text_splitter = CharacterTextSplitter(
        chunk_size=500,
        chunk_overlap=50
    )
    
    if file_path.endswith('.pdf'):
        loader = PyPDFLoader(file_path)
    else:
        loader = TextLoader(file_path)
        
    documents = loader.load()
    return text_splitter.split_text(''.join([doc.page_content for doc in documents]))

@app.get("/")
async def root():
    """Root endpoint to verify API is running"""
    return {"message": "Knowledge Balance Network API is running"}

@app.get("/test")
async def test_connection():
    """Test endpoint to verify database connection"""
    try:
        cursor.execute("SELECT 1")
        return {"status": "success", "message": "Database connection is working"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Database connection failed: {str(e)}")

@app.post("/search", response_model=List[SearchResult])
async def search_discussions(query: SearchQuery):
    """
    Search for discussions using IRIS vector similarity
    """
    try:
        results = vector_search.search_discussions(query.query, query.limit)
        return results
    except Exception as e:
        raise HTTPException(
            status_code=500, 
            detail=f"Error performing search: {str(e)}"
        )

@app.post("/upload")
async def upload_files(files: List[UploadFile] = File(...)):
    """Handle file uploads and store in Qdrant"""
    if not files:
        raise HTTPException(status_code=400, detail="No files provided")
        
    uploaded_files = []
    
    for file in files:
        # Save uploaded file to data directory
        file_path = data_dir / file.filename
        with open(file_path, "wb") as buffer:
            content = await file.read()
            buffer.write(content)
            
        try:
            if not file_path.exists():
                raise HTTPException(
                    status_code=404,
                    detail=f"File not found: {file.filename}"
                )
                
            # Process file and extract text
            text_chunks = process_file(str(file_path))
            
            # Encode text chunks
            embeddings = encoder.encode(text_chunks)
            
            # Add to Qdrant with UUID ids
            points = models.Batch(
                ids=[str(uuid4()) for _ in range(len(text_chunks))],  # Generate UUIDs
                vectors=embeddings.tolist(),
                payloads=[{
                    "text": chunk,
                    "source": file.filename,
                    "chunk_index": i  # Optional: keep track of chunk order
                } for i, chunk in enumerate(text_chunks)]
            )
            
            qdrant_client.upsert(
                collection_name="knowledge_network",
                points=points
            )
            
            uploaded_files.append({
                "filename": file.filename,
                "chunks": len(text_chunks)
            })
            
        finally:
            # Clean up the temporary file
            if file_path.exists():
                file_path.unlink()
    
    return {
        "message": f"Successfully processed {len(uploaded_files)} files",
        "files": uploaded_files
    }

@app.post("/api/ai/chat")
async def chat(request: dict):
    try:
        query = request.get("query")
        if not query:
            raise HTTPException(st
[truncated — 3288 more characters]
```

### knowledge-network/src/types/index.ts

```typescript
export interface Note {
  id: string;
  title: string;
  content: string;
  createdAt: Date;
  updatedAt: Date;
}

export interface Subject {
  id: string;
  name: string;  // This will be the course name (e.g., "Mathematics", "Physics", etc.)
  notes: Note[];
} 
```

[180 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]