Skip to content

rafal-fryc/doc-formatter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

DocFormat AI

DocFormat AI is an intelligent document formatting application that transforms Word documents using AI-powered formatting automation. The system learns from reference documents and applies consistent formatting across your files, saving hours of manual work while maintaining professional standards.

Overview

DocFormat AI addresses the common challenge of maintaining consistent document formatting across large document sets. Whether you need to standardize reports, convert tables to structured lists, or apply corporate formatting guidelines, this application uses artificial intelligence to understand your formatting preferences and apply them automatically.

The application provides two primary formatting modes: reference-based formatting where you upload a template document and the system extracts its style rules, and interactive editing where you can manually adjust formatting parameters like fonts, spacing, and list styles through a visual interface. Both approaches leverage AI to ensure high-quality results while preserving document content integrity.

Key Features

Intelligent Reference-Based Formatting

The reference document feature allows you to upload a template file that demonstrates your desired formatting style. The AI analyzes the reference document's structure, typography, spacing, and layout patterns, then applies these rules to your target documents. This approach is particularly powerful for batch formatting scenarios where you need to maintain consistency across multiple files.

Structural Transformation capabilities enable the system to recognize when documents have different structures and intelligently convert between them. For example, if your reference document uses a heading-plus-bullets pattern and your source document contains tabular data, the AI will automatically transform table rows into properly formatted sections with headings and bullet points, matching the reference style exactly.

Interactive Format Editor

The interactive editor provides granular control over document formatting through an intuitive interface. You can adjust font families, sizes, colors, line spacing, paragraph spacing, margins, and list styles (bulleted or numbered) for each section of your document. Changes are applied in real-time, and the system generates a preview showing exactly how your formatted document will appear.

The editor includes content editing capabilities that allow you to modify text directly while maintaining formatting consistency. This hybrid approach combines the speed of automated formatting with the flexibility of manual control when needed.

Document Management

The application includes a comprehensive document history system that tracks all your formatting operations. Each formatted document is stored with its original file, allowing you to compare versions, download results, or delete outdated entries. The history view displays document names, upload dates, processing status, and provides quick access to download formatted files.

User authentication ensures that each user's documents remain private and accessible only to them. The system uses OAuth-based login with session management, providing secure access without requiring password management.

Technical Architecture

DocFormat AI is built on a modern web stack designed for performance, type safety, and developer productivity. The application uses React 19 for the frontend with Tailwind CSS 4 for styling, providing a responsive and accessible user interface. The backend runs on Express 4 with tRPC 11, enabling end-to-end type safety between client and server without manual API contract maintenance.

Technology Stack

Component Technology Purpose
Frontend Framework React 19 Component-based UI with modern hooks
Styling Tailwind CSS 4 Utility-first responsive design
UI Components shadcn/ui Accessible, customizable components
Backend Framework Express 4 HTTP server and middleware
API Layer tRPC 11 Type-safe RPC with automatic validation
Database MySQL/TiDB Relational data storage
ORM Drizzle Type-safe database queries
Authentication Manus OAuth Secure user authentication
Document Processing docx, mammoth DOCX file manipulation
AI Integration OpenAI API Document analysis and formatting
File Storage AWS S3 Scalable file storage

Architecture Patterns

The application follows a procedure-oriented architecture where all business logic is encapsulated in tRPC procedures. Each procedure defines its input schema using Zod validation, implements the business logic, and returns typed results. This approach eliminates the need for separate REST endpoints, API clients, or shared contract files.

Authentication context is automatically injected into each request, making the current user available to all procedures through ctx.user. Protected procedures verify authentication before executing, while public procedures remain accessible to all users. This pattern simplifies authorization logic and ensures consistent security enforcement.

The database layer uses Drizzle ORM to define schemas and execute queries with full TypeScript type inference. Schema changes are managed through migrations generated by drizzle-kit, ensuring database consistency across environments. Query helpers in server/db.ts encapsulate common data access patterns and return raw results for procedures to consume.

Installation and Setup

Prerequisites

Before installing DocFormat AI, ensure your development environment meets these requirements:

  • Node.js 22 or higher
  • pnpm package manager (installed globally via npm install -g pnpm)
  • MySQL or TiDB database instance
  • AWS S3 bucket for file storage (or S3-compatible service)
  • OpenAI API key for AI-powered formatting

Environment Configuration

Create a .env file in the project root with the following variables:

# Database connection
DATABASE_URL=mysql://user:password@host:port/database

# Authentication
JWT_SECRET=your-jwt-secret-key
OAUTH_SERVER_URL=https://api.manus.im
VITE_OAUTH_PORTAL_URL=https://login.manus.im
VITE_APP_ID=your-app-id

# AI Integration
BUILT_IN_FORGE_API_URL=https://forge.manus.im
BUILT_IN_FORGE_API_KEY=your-forge-api-key
VITE_FRONTEND_FORGE_API_KEY=your-frontend-api-key
VITE_FRONTEND_FORGE_API_URL=https://forge.manus.im

# Application
VITE_APP_TITLE=DocFormat AI
VITE_APP_LOGO=/logo.svg

Installation Steps

Clone the repository and install dependencies:

git clone https://github.com/yourusername/doc-formatter.git
cd doc-formatter
pnpm install

Initialize the database schema:

pnpm db:push

Start the development server:

pnpm dev

The application will be available at http://localhost:3000.

Production Deployment

Build the application for production:

pnpm build

Start the production server:

pnpm start

For containerized deployment, use the included Dockerfile:

docker build -t doc-formatter .
docker run -p 3000:3000 --env-file .env doc-formatter

Usage Guide

Reference-Based Formatting

Reference-based formatting is ideal when you have a template document that demonstrates your desired style and structure. This approach works well for standardizing document sets, converting formats, or applying corporate branding guidelines.

Step 1: Upload Your Document - Navigate to the formatting page and upload the Word document you want to format. The system accepts .docx files up to 10MB in size.

Step 2: Upload Reference Document - Upload a second document that demonstrates the formatting style you want to apply. This reference document should contain examples of headings, paragraphs, lists, and other elements formatted according to your preferences.

Step 3: Process and Download - Click the "Format Document" button to start processing. The AI analyzes both documents, extracts formatting rules from the reference, and applies them to your target document. When processing completes, download your formatted document.

The system intelligently handles structural transformations when the reference and target documents have different layouts. For example, if your reference uses heading-and-bullets while your target contains tables, the AI will convert table rows into sections with headings and bullet points, preserving all content while matching the reference structure.

Interactive Format Editor

The interactive editor provides manual control over formatting when you need precise adjustments or want to format without a reference document.

Step 1: Upload and Analyze - Upload your document and click "Analyze Document" to extract its current structure. The system identifies sections, headings, and paragraphs.

Step 2: Edit Formatting - Use the editor interface to adjust formatting parameters for each section. You can modify fonts, sizes, colors, spacing, margins, and list styles. The "Content" tab allows you to edit text directly.

Step 3: Preview and Download - Review your changes in the preview pane, then click "Apply Changes" to generate the formatted document. Download the result when processing completes.

Document History

Access your formatting history through the "Formatting History" page. This view displays all documents you've processed, including upload dates, file names, and processing status. Click the download icon to retrieve formatted documents, or use the trash icon to delete entries you no longer need.

Development

Project Structure

doc-formatter/
├── client/                 # Frontend React application
│   ├── src/
│   │   ├── components/    # Reusable UI components
│   │   ├── pages/         # Page-level components
│   │   ├── lib/           # Utility functions and tRPC client
│   │   ├── App.tsx        # Route configuration
│   │   └── main.tsx       # Application entry point
│   └── public/            # Static assets
├── server/                # Backend Express application
│   ├── _core/            # Framework infrastructure
│   ├── db.ts             # Database query helpers
│   ├── routers.ts        # tRPC procedure definitions
│   ├── documentProcessor.ts  # Document formatting logic
│   └── structuralTransformer.ts  # Structure conversion
├── drizzle/              # Database schema and migrations
│   └── schema.ts         # Table definitions
└── shared/               # Shared types and constants

Adding Features

To add new features to DocFormat AI, follow this workflow:

1. Update Database Schema - Modify drizzle/schema.ts to add new tables or columns, then run pnpm db:push to apply changes.

2. Create Query Helpers - Add database access functions to server/db.ts that return raw Drizzle query results.

3. Define Procedures - Create tRPC procedures in server/routers.ts that implement your business logic using the query helpers.

4. Build UI Components - Create React components in client/src/pages/ that call your procedures using trpc.*.useQuery or trpc.*.useMutation hooks.

5. Write Tests - Add test files in server/*.test.ts using Vitest to verify your procedures work correctly.

Testing

Run the test suite:

pnpm test

Run tests in watch mode during development:

pnpm test --watch

The project uses Vitest for unit and integration testing. Test files are located alongside the code they test, using the *.test.ts naming convention.

API Documentation

tRPC Procedures

The application exposes these tRPC procedures for document operations:

documents.upload

Uploads a document file to S3 and creates a database record.

Input:

{
  filename: string;
  content: string; // base64-encoded file content
  mimeType: string;
}

Output:

{
  id: string;
  filename: string;
  url: string;
}

documents.format

Formats a document using AI-powered processing.

Input:

{
  documentId: string;
  referenceDocumentId?: string; // optional reference for style extraction
}

Output:

{
  success: boolean;
  formattedDocumentId: string;
  downloadUrl: string;
}

documents.list

Retrieves the current user's document history.

Input: None (uses authenticated user context)

Output:

Array<{
  id: string;
  filename: string;
  status: 'pending' | 'completed' | 'failed';
  createdAt: Date;
  formattedUrl?: string;
}>

documents.delete

Deletes a document from the user's history.

Input:

{
  documentId: string;
}

Output:

{
  success: boolean;
}

editor.applyEdits

Applies manual formatting edits to a document.

Input:

{
  documentId: string;
  contentEdits: Record<string, string>; // section ID to new content
  formattingEdits: Record<string, FormattingOptions>; // section ID to formatting
}

Output:

{
  success: boolean;
  formattedDocumentId: string;
  downloadUrl: string;
}

Contributing

Contributions to DocFormat AI are welcome. Please follow these guidelines:

Code Style - The project uses TypeScript with strict type checking enabled. All code must pass tsc compilation without errors. Follow the existing code style and use ESLint for linting.

Testing Requirements - All new features must include test coverage. Write unit tests for business logic and integration tests for procedures that involve multiple components.

Pull Request Process - Fork the repository, create a feature branch, implement your changes with tests, and submit a pull request with a clear description of the changes and their purpose.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Support

For questions, bug reports, or feature requests, please open an issue on GitHub or contact the development team at support@docformat.ai.

Acknowledgments

DocFormat AI is built with open-source technologies and benefits from the contributions of the broader developer community. Special thanks to the teams behind React, tRPC, Drizzle, and the many other libraries that make this project possible.


Built with ❤️ by the DocFormat AI Team

About

An AI-powered document formatting tool that learns user preferences and applies consistent formatting to Word documents · Built with Manus

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages