Explore the full case study, featuring a concise overview of the problems identified, solutions developed, technical challenges, and key implementation decisions.
AI-powered educational document processing and semantic retrieval.
Transforming unstructured pedagogical documents into structured, searchable knowledge using OCR, LLMs, embeddings and Retrieval-Augmented Generation.
DocFlow AI is an AI-powered document processing platform designed to help educators organize, analyze and retrieve information from pedagogical documents.
Educational documents often contain valuable information, but extracting and finding specific content can be time-consuming when that information is stored in unstructured files.
DocFlow AI explores how OCR, Large Language Models, semantic chunking and vector search can be combined to turn these documents into structured and searchable knowledge.
The platform processes documents through an automated pipeline and makes their content available for contextual retrieval using a Retrieval-Augmented Generation (RAG) architecture.
Pedagogical information is commonly distributed across documents in different formats, making it difficult to:
- Extract relevant information from unstructured files.
- Organize content by subject, educational level and pedagogical category.
- Find specific information across multiple documents.
- Retrieve contextual information without manually reading entire files.
DocFlow AI implements a document processing pipeline that:
- Receives PDF, DOCX and image files.
- Extracts text using OCR and document parsing.
- Uses Gemini AI to structure relevant pedagogical information.
- Divides content into semantically meaningful chunks.
- Generates vector embeddings for each chunk.
- Stores document information and vector representations in PostgreSQL with pgvector.
- Retrieves relevant content through semantic similarity and uses it as context for AI-generated responses.
| Feature | Description |
|---|---|
| Document Upload | Supports PDF, DOCX and image files (PNG, JPG and JPEG), with file type and size validation. |
| Text Extraction | Extracts text through specialized parsers for PDF, DOCX and image formats. |
| AI-Powered Structuring | Uses Gemini 2.5 Flash to transform extracted text into structured pedagogical data, including subjects, educational levels, skills, methodologies and assessments. |
| Semantic Chunking | Organizes structured content into six specialized categories: lesson plans, activities, assessments, BNCC skills, recommendations and insights. |
| Vector Embeddings | Generates 3072-dimensional embeddings using gemini-embedding-001. |
| Semantic Search | Uses PostgreSQL and pgvector with cosine similarity to retrieve relevant document chunks. |
| Retrieval-Augmented Generation | Combines retrieved document context with Gemini 2.5 Flash to generate contextual answers and return their sources. |
| Data Persistence | Stores original documents, structured pedagogical data, semantic chunks and embeddings in PostgreSQL. |
| Automated Testing | Includes unit, integration and API route tests using Pytest. |
| CI/CD | Includes automated workflows configured with GitHub Actions and Jenkins. |
DocFlow AI is organized into two main workflows: document ingestion and Retrieval-Augmented Generation (RAG).
The backend follows a layered architecture, separating API routes, business services, AI processing modules and database persistence.
Document processing is exposed through separate API endpoints. Each endpoint triggers a specific stage of the ingestion workflow.
flowchart TD
A["Document Upload"] --> B["DocumentService"]
B --> C[("documents")]
C --> D["ExtractDocumentService"]
D --> E["Extractor"]
E --> F["PDFParser / DOCXParser / ImageParser"]
F --> G["Extracted Text"]
G --> C
C --> H["DocumentStructuredService"]
H --> I["DocumentStructurer"]
I --> J["Gemini 2.5 Flash"]
J --> K["Structured Pedagogical Data"]
K --> L[("documents_structured")]
L --> M["DocumentChunkService"]
M --> N["DocumentChunker"]
N --> O["LessonPlanChunker"]
N --> P["ActivityChunker"]
N --> Q["AssessmentChunker"]
N --> R["BNCCChunker"]
N --> S["RecommendationChunker"]
N --> T["InsightChunker"]
O --> U["Generated Chunks"]
P --> U
Q --> U
R --> U
S --> U
T --> U
U --> V[("documents_chunks")]
V --> W["DocumentEmbeddingService"]
W --> X["EmbeddingGenerator"]
X --> Y["Gemini Embedding 001"]
Y --> Z[("PostgreSQL + pgvector")]
After document chunks have been generated and their embeddings stored, the application can perform semantic searches and generate contextual responses.
flowchart TD
A["User Question"] --> B["POST /rag/query or /rag/search"]
B --> C["RAGService"]
C --> D["EmbeddingGenerator"]
D --> E["gemini-embedding-001"]
E --> F["VectorRetriever"]
DB[("PostgreSQL + pgvector")] --> F
F --> G["Cosine Similarity Search"]
G --> H["Top-K Relevant Chunks"]
H --> I{"Requested Operation"}
I -->|Search| J["Return Retrieved Chunks"]
I -->|Query| K["RAGGenerator"]
K --> L["Gemini 2.5 Flash"]
L --> M["Contextual Answer + Sources"]
The application separates responsibilities into distinct layers:
| Layer | Responsibility |
|---|---|
| API Routes | Exposes document processing and RAG endpoints through FastAPI. |
| Services | Coordinates business logic and document processing operations. |
| AI Modules | Handles parsing, structuring, chunking, embedding generation and RAG. |
| Models | Defines database entities using SQLAlchemy ORM. |
| Database | Stores documents, structured information, chunks and vector embeddings. |
This separation makes the application easier to maintain, test and extend.
During development, several technical decisions shaped the architecture and document processing workflow.
FastAPI was selected for its straightforward integration with Python-based AI services and its support for building structured REST APIs.
Its Pydantic-based validation and automatic API documentation also help maintain clear contracts between application components.
PostgreSQL was chosen to manage relational application data, while pgvector extends the same database with vector storage and similarity search capabilities.
This approach allows the application to manage document metadata, structured content, semantic chunks and embeddings without introducing a separate vector database.
Document content is divided into six specialized categories:
- Lesson Plans
- Activities
- Assessments
- BNCC Skills
- Recommendations
- Insights
This separation allows retrieval to be filtered by pedagogical purpose. For example, a recommendation query can prioritize recommendation-related chunks instead of retrieving unrelated lesson plan content.
The goal is to improve retrieval relevance by providing more specific context to the RAG pipeline.
The application uses specialized parsers for PDF, DOCX and image files.
For PDFs, PyMuPDF extracts existing text. When a page has no extractable text, the parser renders the page and applies OCR using Tesseract.
Image files are processed through Pillow and pytesseract, while DOCX files are handled with python-docx.
This approach supports both digitally generated and scanned documents.
The RAG pipeline separates information retrieval from response generation.
User questions are converted into embeddings and matched against stored document chunks using cosine similarity. Retrieved content is then assembled into the context provided to Gemini.
The generation prompt instructs the model to rely on the retrieved context and indicate when the available information is insufficient.
This approach helps reduce responses that are disconnected from the documents stored in the system.
DocFlow AI uses PostgreSQL, hosted on Neon, with SQLAlchemy ORM for database interaction and pgvector for vector storage and semantic similarity search.
The database follows a three-entity document processing model, separating original documents, AI-structured information and semantic chunks.
erDiagram
DOCUMENTS ||--o| DOCUMENTS_STRUCTURED : "document_id"
DOCUMENTS_STRUCTURED ||--o{ DOCUMENTS_CHUNKS : "structured_document_id"
DOCUMENTS {
varchar id PK
varchar filename
varchar stored_filename
varchar file_path
text extracted_text
varchar status
timestamp created_at
}
DOCUMENTS_STRUCTURED {
varchar id PK
varchar document_id FK,UK
varchar subject
varchar level
json contents
json skills
json methodologies
json assessment
timestamp created_at
}
DOCUMENTS_CHUNKS {
varchar id PK
varchar structured_document_id FK
varchar chunk_type
integer chunk_order
text content
json chunk_metadata
vector_3072 embedding
timestamp created_at
}
| Entity | Responsibility |
|---|---|
documents |
Stores uploaded file information, file paths, extracted text and processing status. |
documents_structured |
Stores AI-structured pedagogical information, including subjects, educational levels, skills and methodologies. |
documents_chunks |
Stores semantically segmented content, chunk metadata and vector embeddings. |
- Documents β Structured Documents (1:0..1): each document can have at most one structured representation, enforced by a unique foreign key on
document_id. - Structured Documents β Chunks (1:N): each structured document can contain multiple semantic chunks.
- Referential Integrity: foreign keys maintain relationships between document processing stages.
- Cascade Deletion: chunks are configured for deletion when their parent structured document is removed.
The documents_chunks table includes an embedding column implemented with pgvector.
- Data type:
vector(3072). - Embedding model:
gemini-embedding-001. - Purpose: semantic representation of document chunks.
- Retrieval: cosine similarity search for contextually relevant content.
JSON columns are used to store variable pedagogical information:
contents: extracted educational content.skills: skills and learning objectives.methodologies: teaching methodologies.assessment: assessment-related information.chunk_metadata: additional context associated with each semantic chunk.
The RAG implementation combines vector-based retrieval with Large Language Model generation.
Instead of relying only on the model's general knowledge, the application retrieves relevant information from processed documents and provides it as context for response generation.
- The user submits a natural-language question.
- The question is converted into an embedding using
gemini-embedding-001. - pgvector performs a cosine similarity search.
- The most relevant chunks are retrieved according to the
top_kparameter. - Retrieved content is assembled into the context.
- Gemini generates a contextual response using the retrieved information.
- The API returns the answer and its sources.
| Method | Endpoint | Description |
|---|---|---|
POST |
/rag/query |
Executes the complete RAG pipeline and returns an answer with sources. |
POST |
/rag/search |
Performs semantic search without generating an AI response. |
{
"query": "How to plan an engaging lesson on fractions?",
"top_k": 5,
"chunk_type": "lesson_plan"
}The top_k parameter controls the number of chunks retrieved, while chunk_type can be used to filter the search by pedagogical category.
DocFlow AI exposes RESTful endpoints through FastAPI, organized into document processing and Retrieval-Augmented Generation (RAG) operations.
| Method | Endpoint | Description |
|---|---|---|
POST |
/documents/upload |
Uploads and validates PDF, DOCX and image files. |
POST |
/documents/{document_id}/extract |
Extracts text from an uploaded document. |
POST |
/documents/{document_id}/structure |
Converts extracted text into structured pedagogical data using Gemini. |
POST |
/documents/{document_id}/chunk |
Splits structured content into specialized semantic chunks. |
POST |
/documents/{document_id}/embeddings |
Generates vector embeddings for document chunks. |
| Method | Endpoint | Description |
|---|---|---|
POST |
/rag/search |
Retrieves semantically relevant chunks using vector similarity search. |
POST |
/rag/query |
Generates contextual answers based on retrieved document content. |
| Method | Endpoint | Description |
|---|---|---|
GET |
/health |
Checks whether the API is running. |
GET |
/getdocuments |
Retrieves structured documents stored in the database. |
API Documentation: FastAPI automatically provides interactive Swagger UI documentation at /docs when the application is running.
| Category | Technologies |
|---|---|
| Language | Python |
| API Framework | FastAPI |
| ORM | SQLAlchemy |
| Database | PostgreSQL |
| Vector Search | pgvector |
| Generative AI | Google Gemini 2.5 Flash |
| Embeddings | gemini-embedding-001 (3072 dimensions) |
| PDF Processing | PyMuPDF (fitz) |
| DOCX Processing | python-docx |
| Image Processing | Pillow |
| OCR | Tesseract OCR (pytesseract) |
| Testing | Pytest |
| Containerization | Docker |
| CI/CD | GitHub Actions, Jenkins |
| Database Hosting | Neon PostgreSQL |
DocFlow AI includes automated unit and integration tests using Pytest to validate document processing, AI integrations, semantic retrieval and API behavior.
The latest test execution reported:
| Metric | Result |
|---|---|
| Overall Code Coverage | 90% |
| Tests Passed | 31 |
| Statements Analyzed | 542 |
| Execution Time | 34.32 seconds |
- Document upload and validation.
- PDF, DOCX and image parsing.
- Document structuring.
- Semantic chunk generation.
- Embedding generation.
- RAG retrieval and response generation.
- Database operations and API routes.
pytestpytest --cov=app --cov-report=term-missingThe coverage report identifies executed and untested lines, helping guide future improvements to the test suite.
DocFlow AI uses GitHub Actions and Jenkins to automate Docker builds, automated testing and application deployment.
The GitHub Actions workflow is triggered by pushes and pull requests targeting the main branch.
CI workflow:
- Checks out the repository.
- Builds the Docker image.
- Runs code quality checks using Flake8.
- Executes unit tests with Pytest.
- Executes integration tests with coverage reporting.
Deployment workflow:
After a successful CI run triggered by a push to main:
- Triggers deployment on Render using a deploy hook.
- Waits for the deployment to complete.
- Performs an API health check through the
/healthendpoint.
The Jenkins pipeline automates the application lifecycle in a Docker environment.
Pipeline stages:
- Checkout: Retrieves the source code.
- Build: Builds and tags Docker images using the build number and
latest. - Testing: Executes the Pytest suite with coverage.
- Deployment: Stops and removes the previous container, then starts the updated application container.
Jenkins credentials are used to configure database connections securely.
| Capability | GitHub Actions | Jenkins |
|---|---|---|
| Docker Image Build | Yes | Yes |
| Code Linting | Flake8 | Not configured |
| Automated Tests | Unit and integration | Pytest suite |
| Coverage | Integration tests | Full test suite |
| Deployment | Render | Docker container |
| Health Check | API /health |
Not configured |
Both pipelines help maintain code quality and automate application delivery through containerized workflows.
Although DocFlow AI implements a complete document ingestion and RAG workflow, some limitations remain.
- External AI Dependency: Document structuring, embeddings and response generation depend on Google's Gemini services.
- Free-Tier Restrictions: API quotas and usage limits restrict processing capacity and the number of requests that can be handled.
- Frontend Availability: The project currently focuses on backend functionality and exposes its capabilities through REST API endpoints and Swagger documentation.
- Model Specialization: The current implementation relies on general-purpose Gemini models rather than a model specifically adapted to educational documents.
- Develop a dedicated frontend to make document processing and semantic search accessible through a visual interface.
- Evaluate open-source language and embedding models to reduce dependency on external AI providers.
- Explore self-hosted AI infrastructure for greater control over processing, availability and costs.
- Further specialize document processing and retrieval for educational use cases.
- Expand automated tests and improve coverage of less-tested AI integration paths.
These improvements aim to evolve DocFlow AI into a more independent and specialized platform for educational document processing.
Developing DocFlow AI provided practical experience with several concepts in backend engineering and AI integration.
Key learnings include:
- Integrating Large Language Models and embedding services into backend applications.
- Processing heterogeneous documents using text extraction and OCR.
- Transforming unstructured information into structured data.
- Designing specialized semantic chunking strategies.
- Implementing vector similarity search with PostgreSQL and pgvector.
- Building RAG pipelines that combine semantic retrieval with contextual response generation.
- Organizing AI-related responsibilities into maintainable backend services.
The project strengthened my understanding of how traditional backend engineering concepts can be combined with generative AI to solve practical problems.
- Docker and Docker Compose.
- Gemini API key.
git clone https://github.com/matheusconaga/docflow-ai.git
cd docflow-aiCreate a .env file in the project root:
DATABASE_URL=
DATABASE_TEST_URL=
GEMINI_API_KEY=Fill in the values required by your local environment.
docker compose up --buildOnce the application is running, access:
http://localhost:8000/docs
The Swagger interface provides interactive access to the available API endpoints.
For a local Python environment:
python -m venv venvActivate the environment:
# Windows PowerShell
.\venv\Scripts\Activate
# Linux / macOS
source venv/bin/activateInstall dependencies:
pip install -r requirements.txtMake sure PostgreSQL is running and the pgvector extension is available. Configure the environment variables in .env, then run the database setup:
python -m app.db.create_tables
python -m app.db.migrations.add_pgvectorStart the API:
uvicorn app.main:app --reloadOpen http://localhost:8000/docs to explore the API.
Processing note: the document workflow exposes separate endpoints for extraction, structuring, chunking and embedding generation. Embeddings must be generated before documents can be used in the RAG retrieval workflow.
Copyright Β© 2026 Matheus Lula. All rights reserved.
This project is intended for portfolio and educational purposes only. Unauthorized commercial use, distribution or reproduction is prohibited.
Software Engineer β’ Python β’ FastAPI β’ TypeScript β’ Node.js β’ PostgreSQL
I develop web applications, backend services and API integrations, with an interest in software architecture, automation and AI-powered solutions.
This project explores the application of backend engineering, vector databases and Large Language Models to solve a practical document processing problem.
