texcomp / README.md
Samuel
update
18e1c52
---
title: LaTeX Compiler
emoji: πŸ“„
colorFrom: purple
colorTo: indigo
sdk: docker
pinned: false
license: mit
app_port: 7860
---
# LaTeX Compiler Web App
A full-featured LaTeX compiler web application that converts LaTeX documents to PDF using pdflatex. Built with Flask backend and vanilla JavaScript frontend, deployable on Hugging Face Spaces using Docker.
## Features
- πŸš€ **Web Interface**: Upload `.tex` files or paste LaTeX code directly
- πŸ“„ **PDF Generation**: Compile LaTeX to PDF using pdflatex
- πŸ”Œ **REST API**: JSON and file upload endpoints
- 🎨 **Modern UI**: Responsive design with Tailwind CSS
- 🐳 **Docker Ready**: Easy deployment with Docker
- πŸ€— **Hugging Face Compatible**: Ready for Hugging Face Spaces
## Project Structure
```
latex-compiler/
β”œβ”€β”€ app.py # Flask backend server
β”œβ”€β”€ index.html # Frontend interface
β”œβ”€β”€ Dockerfile # Docker configuration
└── README.md # This file (with HF config)
```
## Hugging Face Spaces Deployment
### Quick Deploy
1. **Create a new Space:**
- Go to [Hugging Face Spaces](https://huggingface.co/spaces)
- Click "Create new Space"
- Choose **Docker** as the SDK
- Name your space (e.g., `latex-compiler`)
2. **Upload files:**
Upload all four files to your Space:
- `README.md` (this file - **must include YAML frontmatter**)
- `Dockerfile`
- `app.py`
- `index.html`
3. **Configuration:**
The YAML frontmatter at the top of this README configures your Space:
```yaml
---
title: LaTeX Compiler # Your app name
emoji: πŸ“„ # Icon for your Space
colorFrom: purple # Gradient start color
colorTo: indigo # Gradient end color
sdk: docker # REQUIRED: Use Docker SDK
pinned: false # Pin to your profile
license: mit # License type
app_port: 7860 # REQUIRED: Port your app runs on
---
```
4. **Wait for build:**
- Hugging Face will automatically build your Docker image
- This takes **10-15 minutes** due to texlive-full installation
- Watch the build logs in the "Logs" tab
- Once complete, your app will be live!
5. **Access your Space:**
- Your app will be available at: `https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE_NAME`
### Important Notes for Hugging Face
- βœ… **Port 7860 is REQUIRED** - Hugging Face Spaces expects this port
- βœ… **Docker SDK is REQUIRED** - Must be specified in YAML frontmatter
- βœ… **README.md must have YAML frontmatter** - Configuration at the top of this file
- ⚠️ Build time is long (~10-15 min) due to texlive-full package size
- ⚠️ First compile may be slower as LaTeX initializes fonts
## Local Development
### Prerequisites
- Docker installed on your system
- OR Python 3.8+ and texlive-full for non-Docker setup
### Run with Docker (Recommended)
1. **Build the Docker image:**
```bash
docker build -t latex-compiler .
```
2. **Run the container:**
```bash
docker run -p 7860:7860 latex-compiler
```
3. **Access the application:**
Open your browser and navigate to `http://localhost:7860`
### Run without Docker (Local Development)
1. **Install dependencies:**
```bash
# Ubuntu/Debian
sudo apt-get update
sudo apt-get install python3 python3-pip texlive-full latexmk
# macOS
brew install python texlive
# Install Python packages
pip3 install flask flask-cors
```
2. **Run the application:**
```bash
python3 app.py
```
3. **Access the application:**
Open your browser and navigate to `http://localhost:7860`
## API Documentation
### Endpoints
#### `POST /compile`
Compile LaTeX code to PDF.
**Request Method 1: JSON**
```bash
curl -X POST http://localhost:7860/compile \
-H "Content-Type: application/json" \
-d '{"code": "\\documentclass{article}\\begin{document}Hello World\\end{document}"}' \
--output output.pdf
```
**Request Method 2: File Upload**
```bash
curl -X POST http://localhost:7860/compile \
-F "file=@document.tex" \
--output output.pdf
```
**Success Response:**
- Status: `200 OK`
- Content-Type: `application/pdf`
- Body: PDF binary data
**Error Response:**
- Status: `400 Bad Request`
- Content-Type: `application/json`
```json
{
"error": "Compilation failed",
"log": "LaTeX error log details..."
}
```
#### `GET /`
Serves the web frontend interface.
#### `GET /docs`
Displays comprehensive API documentation.
## Usage Examples
### Python Example
```python
import requests
latex_code = r"""
\documentclass{article}
\usepackage[utf8]{inputenc}
\title{My Document}
\author{John Doe}
\begin{document}
\maketitle
\section{Introduction}
This is a sample document.
\end{document}
"""
response = requests.post(
'http://localhost:7860/compile',
json={'code': latex_code}
)
if response.status_code == 200:
with open('output.pdf', 'wb') as f:
f.write(response.content)
print("PDF created successfully!")
else:
print("Error:", response.json())
```
### JavaScript Example
```javascript
const latexCode = `
\\documentclass{article}
\\begin{document}
Hello from JavaScript!
\\end{document}
`;
fetch('http://localhost:7860/compile', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ code: latexCode })
})
.then(response => response.blob())
.then(blob => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'output.pdf';
a.click();
});
```
### File Upload Example
```python
import requests
with open('document.tex', 'rb') as f:
files = {'file': f}
response = requests.post(
'http://localhost:7860/compile',
files=files
)
if response.status_code == 200:
with open('output.pdf', 'wb') as f:
f.write(response.content)
```
### Using on Hugging Face Spaces
```python
import requests
# Replace with your actual Space URL
SPACE_URL = "https://YOUR_USERNAME-latex-compiler.hf.space"
latex_code = r"""
\documentclass{article}
\begin{document}
Hello from Hugging Face!
\end{document}
"""
response = requests.post(
f'{SPACE_URL}/compile',
json={'code': latex_code}
)
if response.status_code == 200:
with open('output.pdf', 'wb') as f:
f.write(response.content)
```
## Features & Limitations
### Supported
βœ… Standard LaTeX packages (texlive-full includes 99% of packages)
βœ… Mathematical equations and symbols
βœ… Tables, figures, and images (embedded)
βœ… Bibliography and citations
βœ… Custom document classes
βœ… Multiple compilation passes (handled automatically)
### Limitations
⚠️ Compilation timeout: 30 seconds
⚠️ Recommended file size: < 10MB
⚠️ Only pdflatex engine (XeLaTeX and LuaLaTeX not included)
⚠️ No support for external file dependencies (images must be embedded or base64)
## Troubleshooting
### Common Errors
**"Compilation failed"**
- Check your LaTeX syntax
- View the error log in the web interface
- Ensure all required packages are declared
**"Compilation timeout"**
- Your document is too complex
- Try simplifying or splitting into smaller documents
**"No file selected"**
- Ensure you've selected a `.tex` file before clicking compile
### Docker Build Issues
**Build fails due to texlive-full size:**
```bash
# Increase Docker memory limit in Docker Desktop settings
# Recommended: 4GB+ RAM, 10GB+ disk space
```
**Port 7860 already in use:**
```bash
# Use a different port locally
docker run -p 8080:7860 latex-compiler
# Then access at http://localhost:8080
```
### Hugging Face Spaces Issues
**Space stuck in "Building" state:**
- Check the build logs for errors
- Ensure Dockerfile is correct
- Verify all files are uploaded
- texlive-full installation takes 10-15 minutes (this is normal)
**Space shows "Application Error":**
- Check that `app_port: 7860` is in README.md frontmatter
- Verify Flask app runs on host `0.0.0.0` and port `7860`
- Review Space logs for Python errors
**"Connection refused" errors:**
- Ensure `EXPOSE 7860` is in Dockerfile
- Verify `app.run(host='0.0.0.0', port=7860)` in app.py
## Technical Stack
- **Backend**: Flask 3.x (Python)
- **Frontend**: Vanilla JavaScript + Tailwind CSS
- **LaTeX Engine**: pdflatex (TeX Live 2022)
- **Containerization**: Docker (Ubuntu 22.04 base)
- **Deployment**: Hugging Face Spaces (Docker SDK)
## Environment Variables (Optional)
You can customize the app with environment variables:
```bash
# In Hugging Face Spaces, add these in Settings > Variables
FLASK_ENV=production
MAX_CONTENT_LENGTH=10485760 # 10MB limit
```
## License
MIT License - feel free to use and modify!
## Contributing
Contributions welcome! Areas for improvement:
- Add XeLaTeX/LuaLaTeX support
- Implement file caching for faster recompilation
- Add syntax highlighting in code editor
- Support for multi-file LaTeX projects
- Real-time preview with live updates
- Integration with Overleaf-style collaborative editing
## Support
- **Hugging Face Discussions**: Use the Community tab on your Space
- **Issues**: Report bugs via GitHub or Space discussions
- **Documentation**: Visit `/docs` endpoint for API reference
- **Examples**: Check the Usage Examples section above
## Acknowledgments
- Built for the LaTeX community
- Powered by TeX Live and Flask
- Hosted on Hugging Face Spaces
---
**Need help?** Visit the `/docs` endpoint or check Hugging Face Spaces documentation at https://huggingface.co/docs/hub/spaces-overview