Spaces:
Sleeping
Sleeping
Mervin Gaa commited on
Commit ·
e5e5bf7
0
Parent(s):
first commit
Browse filesFiles changed (12)
- README.mdAdded+197
- backend/DockerfileAdded+7
- backend/main.pyAdded+150
- backend/requirements.txtAdded+5
- frontend/package.jsonAdded+18
- frontend/postcss.config.jsAdded+6
- frontend/public/index.htmlAdded+57
- frontend/src/App.jsxAdded+321
- frontend/src/main.jsxAdded+9
- frontend/tailwind.config.jsAdded+21
- frontend/vite.config.jsAdded+9
- railway.tomlAdded+10
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197# Parquet to CSV Converter
A full-stack web app for converting large `.parquet` files to `.csv` from a browser. The backend uses FastAPI and DuckDB, writes files to temporary disk storage, and streams the CSV download instead of loading the full output into memory.
## Tech Stack
- Frontend: React, Vite, Tailwind CSS- Backend: Python, FastAPI- Conversion engine: DuckDB- File handling: python-multipart, aiofiles, StreamingResponse- Deployment: Railway.app
## Project Structure
```textparquet-to-csv/├── backend/│ ├── main.py│ ├── requirements.txt│ └── Dockerfile├── frontend/│ ├── public/│ │ └── index.html│ ├── src/│ │ ├── App.jsx│ │ └── main.jsx│ ├── package.json│ ├── tailwind.config.js│ ├── postcss.config.js│ └── vite.config.js├── railway.toml└── README.md```
## Run Locally
### 1. Start the Backend
```bashcd backendpython -m venv .venvsource .venv/bin/activatepip install -r requirements.txtuvicorn main:app --reload --host 0.0.0.0 --port 8000```
On Windows PowerShell:
```powershellcd backendpython -m venv .venv.\.venv\Scripts\Activate.ps1pip install -r requirements.txtuvicorn main:app --reload --host 0.0.0.0 --port 8000```
Confirm the backend is running:
```bashcurl http://localhost:8000/health```
Expected response:
```json{"status":"healthy"}```
### 2. Start the Frontend
Open a second terminal:
```bashcd frontendnpm installnpm run dev```
Visit the local frontend URL shown by Vite, usually:
```texthttp://localhost:5173```
The frontend defaults to:
```texthttp://localhost:8000```
for API requests. To use another backend URL locally, create `frontend/.env`:
```textVITE_API_URL=https://your-backend-url```
## Deploy to Railway
### 1. Push to GitHub
Create a GitHub repository and push this project:
```bashgit initgit add .git commit -m "Initial Parquet to CSV converter"git branch -M maingit remote add origin https://github.com/YOUR_USERNAME/parquet-to-csv.gitgit push -u origin main```
### 2. Create the Backend Service
1. Open Railway.app.2. Create a new project.3. Choose "Deploy from GitHub repo".4. Select this repository.5. Create a service for the `backend` directory.6. Railway will use `backend/Dockerfile`.7. Generate or copy the public backend domain from the Railway service settings.
The backend health endpoint will be:
```texthttps://YOUR-BACKEND-DOMAIN/health```
### 3. Create the Frontend Service
1. In the same Railway project, add another service from the same GitHub repo.2. Set the service root/source directory to `frontend`.3. Set the build command to:
```bashnpm install && npm run build```
4. Set the start command to:
```bashnpm run preview -- --host 0.0.0.0 --port $PORT```
5. Add this environment variable to the frontend service:
```textVITE_API_URL=https://YOUR-BACKEND-DOMAIN```
6. Redeploy the frontend service after setting the variable.7. Generate or copy the public frontend domain from the Railway service settings.
### 4. Share the App
Send the Railway frontend URL to the remote user:
```texthttps://YOUR-FRONTEND-DOMAIN```
They can open the URL in a browser, upload a `.parquet` file, and download the converted CSV without installing anything.
## Notes for Large Files
- The app enforces a 10GB upload limit.- Files over 5GB show a warning in the browser.- DuckDB performs the conversion; pandas is not used.- Uploads and converted CSV files are stored in a temporary directory and cleaned up after streaming.- CORS is fully open so the frontend can call the backend from a separate Railway domain.
## API
### `GET /`
Returns:
```json{"status":"ok"}```
### `GET /health`
Returns:
```json{"status":"healthy"}```
### `POST /convert`
Accepts multipart form data with a `.parquet` file field named `file`.
Returns a streamed CSV response with:
```textContent-Disposition: attachment; filename=output.csv```1234567FROM python:3.11-slimWORKDIR /appCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtCOPY . .EXPOSE 8000CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150import asyncioimport shutilimport tempfilefrom pathlib import Pathfrom typing import AsyncIterator
import aiofilesimport duckdbfrom fastapi import BackgroundTasks, FastAPI, File, HTTPException, Request, UploadFilefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse, StreamingResponse
MAX_UPLOAD_SIZE = 10 * 1024 * 1024 * 1024CHUNK_SIZE = 1024 * 1024
app = FastAPI(title="Parquet to CSV Converter", version="1.0.0")
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=False, allow_methods=["*"], allow_headers=["*"],)
@app.middleware("http")async def enforce_upload_size(request: Request, call_next): if request.method == "POST" and request.url.path == "/convert": content_length = request.headers.get("content-length") if content_length: try: if int(content_length) > MAX_UPLOAD_SIZE: return JSONResponse( status_code=413, content={"detail": "File is too large. Maximum upload size is 10GB."}, ) except ValueError: return JSONResponse( status_code=400, content={"detail": "Invalid Content-Length header."}, ) return await call_next(request)
@app.get("/")async def root(): return {"status": "ok"}
@app.get("/health")async def health(): return {"status": "healthy"}
def quote_duckdb_path(path: Path) -> str: normalized = path.resolve().as_posix() return "'" + normalized.replace("'", "''") + "'"
def convert_parquet_to_csv(input_path: Path, output_path: Path) -> None: sql = ( f"COPY (SELECT * FROM {quote_duckdb_path(input_path)}) " f"TO {quote_duckdb_path(output_path)} (HEADER, DELIMITER ',')" ) connection = duckdb.connect(database=":memory:") try: connection.execute(sql) finally: connection.close()
async def save_upload_to_disk(upload: UploadFile, destination: Path) -> None: bytes_written = 0 async with aiofiles.open(destination, "wb") as output_file: while True: chunk = await upload.read(CHUNK_SIZE) if not chunk: break
bytes_written += len(chunk) if bytes_written > MAX_UPLOAD_SIZE: raise HTTPException( status_code=413, detail="File is too large. Maximum upload size is 10GB.", )
await output_file.write(chunk)
if bytes_written == 0: raise HTTPException(status_code=400, detail="Uploaded file is empty.")
async def stream_file(path: Path) -> AsyncIterator[bytes]: async with aiofiles.open(path, "rb") as csv_file: while True: chunk = await csv_file.read(CHUNK_SIZE) if not chunk: break yield chunk
def cleanup_temp_dir(temp_dir: str) -> None: shutil.rmtree(temp_dir, ignore_errors=True)
@app.post("/convert")async def convert(background_tasks: BackgroundTasks, file: UploadFile = File(...)): if not file.filename: raise HTTPException(status_code=400, detail="No file was uploaded.")
if not file.filename.lower().endswith(".parquet"): raise HTTPException(status_code=400, detail="Please upload a .parquet file.")
temp_dir = tempfile.mkdtemp(prefix="parquet-to-csv-") input_path = Path(temp_dir) / "input.parquet" output_path = Path(temp_dir) / "output.csv"
try: await save_upload_to_disk(file, input_path) await asyncio.to_thread(convert_parquet_to_csv, input_path, output_path)
if not output_path.exists(): raise HTTPException(status_code=500, detail="CSV conversion did not produce a file.")
background_tasks.add_task(cleanup_temp_dir, temp_dir) return StreamingResponse( stream_file(output_path), media_type="text/csv", headers={"Content-Disposition": "attachment; filename=output.csv"}, background=background_tasks, ) except HTTPException: cleanup_temp_dir(temp_dir) raise except duckdb.Error as exc: cleanup_temp_dir(temp_dir) raise HTTPException( status_code=422, detail=f"DuckDB could not convert this Parquet file: {exc}", ) from exc except Exception as exc: cleanup_temp_dir(temp_dir) raise HTTPException( status_code=500, detail="Conversion failed. Please check the file and try again.", ) from exc finally: await file.close()12345fastapiuvicorn[standard]duckdbpython-multipartaiofiles123456789101112131415161718{ "scripts": { "dev": "vite --host 0.0.0.0", "build": "vite build", "preview": "vite preview --host 0.0.0.0", "start": "vite preview --host 0.0.0.0 --port ${PORT:-4173}" }, "dependencies": { "@vitejs/plugin-react": "^4.3.4", "vite": "^5.4.11", "react": "^18.3.1", "react-dom": "^18.3.1", "tailwindcss": "^3.4.17", "postcss": "^8.4.49", "autoprefixer": "^10.4.20" }, "devDependencies": {}}123456export default { plugins: { tailwindcss: {}, autoprefixer: {}, },};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657<!doctype html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="description" content="Convert large Parquet files to CSV in your browser, powered by DuckDB." /> <title>Parquet to CSV Converter</title> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Sora:wght@400;500;600;700;800&display=swap" rel="stylesheet" /> <script> window.tailwind = { theme: { extend: { fontFamily: { sans: ['Sora', 'system-ui', 'sans-serif'], }, keyframes: { progress: { '0%': { transform: 'translateX(-110%)' }, '100%': { transform: 'translateX(210%)' }, }, }, animation: { progress: 'progress 1.4s ease-in-out infinite', }, }, }, }; </script> <script src="https://cdn.tailwindcss.com"></script> <style> :root { font-family: 'Sora', system-ui, sans-serif; background: #020617; }
* { box-sizing: border-box; }
body { margin: 0; } </style> </head> <body> <div id="root"></div> <script type="module" src="/src/main.jsx"></script> </body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321import { useRef, useState } from 'react';
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000';const FIVE_GB = 5 * 1024 * 1024 * 1024;const TEN_GB = 10 * 1024 * 1024 * 1024;
function formatBytes(bytes) { if (!Number.isFinite(bytes) || bytes === 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB', 'TB']; const index = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1); return `${(bytes / 1024 ** index).toFixed(index === 0 ? 0 : 2)} ${units[index]}`;}
function DownloadIcon() { return ( <svg className="h-10 w-10" viewBox="0 0 24 24" fill="none" aria-hidden="true"> <path d="M12 3v11m0 0 4-4m-4 4-4-4M4 17v1a3 3 0 0 0 3 3h10a3 3 0 0 0 3-3v-1" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /> </svg> );}
function FileIcon() { return ( <svg className="h-5 w-5" viewBox="0 0 24 24" fill="none" aria-hidden="true"> <path d="M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7l-5-5Z" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /> <path d="M14 2v5h5M8.5 13h7M8.5 17h7M8.5 9h2" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /> </svg> );}
export default function App() { const [selectedFile, setSelectedFile] = useState(null); const [isDragging, setIsDragging] = useState(false); const [isConverting, setIsConverting] = useState(false); const [status, setStatus] = useState('Choose a Parquet file to begin.'); const [error, setError] = useState(''); const [downloadUrl, setDownloadUrl] = useState(''); const [downloadName, setDownloadName] = useState('output.csv'); const fileInputRef = useRef(null); const downloadLinkRef = useRef(null);
const chooseFile = (file) => { setError(''); setDownloadUrl('');
if (!file) return;
if (!file.name.toLowerCase().endsWith('.parquet')) { setSelectedFile(null); setStatus('Choose a Parquet file to begin.'); setError('That file type is not supported. Please choose a .parquet file.'); return; }
if (file.size > TEN_GB) { setSelectedFile(null); setStatus('Choose a Parquet file to begin.'); setError('This file is larger than 10GB. Please choose a smaller Parquet file.'); return; }
setSelectedFile(file); setStatus('Ready to convert.');
if (file.size > FIVE_GB) { setStatus('Ready to convert. Large files over 5GB may take several minutes.'); } };
const handleInputChange = (event) => { chooseFile(event.target.files?.[0]); };
const handleDrop = (event) => { event.preventDefault(); setIsDragging(false); chooseFile(event.dataTransfer.files?.[0]); };
const handleDragOver = (event) => { event.preventDefault(); setIsDragging(true); };
const handleDragLeave = (event) => { event.preventDefault(); setIsDragging(false); };
const reset = () => { if (downloadUrl) { URL.revokeObjectURL(downloadUrl); }
setSelectedFile(null); setIsDragging(false); setIsConverting(false); setStatus('Choose a Parquet file to begin.'); setError(''); setDownloadUrl(''); setDownloadName('output.csv');
if (fileInputRef.current) { fileInputRef.current.value = ''; } };
const convertFile = async () => { if (!selectedFile) return;
setIsConverting(true); setError(''); setDownloadUrl(''); setStatus('Uploading and converting your file...');
const formData = new FormData(); formData.append('file', selectedFile);
try { const response = await fetch(`${API_URL}/convert`, { method: 'POST', body: formData, });
if (!response.ok) { let message = 'Conversion failed. Please try again.'; try { const data = await response.json(); message = data.detail || message; } catch { message = response.statusText || message; } throw new Error(message); }
setStatus('Preparing your CSV download...'); const blob = await response.blob(); const url = URL.createObjectURL(blob); const csvName = selectedFile.name.replace(/\.parquet$/i, '.csv') || 'output.csv';
setDownloadUrl(url); setDownloadName(csvName); setStatus('Conversion complete. Your download should start automatically.');
window.setTimeout(() => { if (downloadLinkRef.current) { downloadLinkRef.current.click(); } }, 0); } catch (caughtError) { const message = caughtError instanceof Error ? caughtError.message : 'Network error. Please check the backend URL and try again.'; setError(message); setStatus('Conversion stopped.'); } finally { setIsConverting(false); } };
return ( <main className="min-h-screen bg-slate-950 text-slate-100"> <div className="mx-auto flex min-h-screen w-full max-w-5xl flex-col px-5 py-8 sm:px-8 lg:px-10"> <header className="py-8 text-center sm:py-12"> <p className="text-sm font-semibold uppercase tracking-[0.28em] text-cyan-300"> DuckDB streaming conversion </p> <h1 className="mt-4 text-4xl font-extrabold tracking-normal text-white sm:text-6xl"> Parquet → CSV Converter </h1> <p className="mx-auto mt-5 max-w-2xl text-base leading-7 text-slate-300 sm:text-lg"> Upload a Parquet file and convert it to CSV from your browser. Built for very large datasets without loading the full file into memory. </p> </header>
<section className="grid flex-1 gap-5 lg:grid-cols-[1.2fr_0.8fr]"> <div className="rounded-lg border border-slate-800 bg-slate-900/70 p-5 shadow-2xl shadow-black/30 sm:p-6"> <button type="button" className={`flex min-h-[280px] w-full flex-col items-center justify-center rounded-lg border-2 border-dashed px-6 py-10 text-center transition ${ isDragging ? 'border-cyan-300 bg-cyan-300/10 text-cyan-100' : 'border-slate-600 bg-slate-950/50 text-slate-300 hover:border-cyan-400 hover:bg-slate-900' }`} onClick={() => fileInputRef.current?.click()} onDrop={handleDrop} onDragOver={handleDragOver} onDragLeave={handleDragLeave} disabled={isConverting} > <span className="rounded-full bg-cyan-400/10 p-4 text-cyan-300"> <DownloadIcon /> </span> <span className="mt-6 text-xl font-bold text-white"> {selectedFile ? selectedFile.name : 'Drop your .parquet file here'} </span> <span className="mt-3 max-w-md text-sm leading-6 text-slate-400"> Click to browse or drag a file onto this area. Files up to 10GB are accepted. </span> <input ref={fileInputRef} className="hidden" type="file" accept=".parquet" onChange={handleInputChange} /> </button>
<div className="mt-5"> <button type="button" onClick={convertFile} disabled={!selectedFile || isConverting} className="flex h-12 w-full items-center justify-center rounded-lg bg-cyan-400 px-5 text-sm font-bold text-slate-950 transition hover:bg-cyan-300 disabled:cursor-not-allowed disabled:bg-slate-700 disabled:text-slate-400" > {isConverting ? ( <> <span className="mr-3 h-4 w-4 animate-spin rounded-full border-2 border-slate-950 border-t-transparent" /> Converting... </> ) : ( 'Convert to CSV' )} </button> </div> </div>
<aside className="rounded-lg border border-slate-800 bg-slate-900/70 p-5 shadow-2xl shadow-black/30 sm:p-6"> <h2 className="text-lg font-bold text-white">File details</h2>
{selectedFile ? ( <div className="mt-5 space-y-4"> <div className="flex items-start gap-3 rounded-lg border border-slate-800 bg-slate-950/60 p-4"> <span className="mt-0.5 text-cyan-300"> <FileIcon /> </span> <div className="min-w-0"> <p className="break-words text-sm font-semibold text-white">{selectedFile.name}</p> <p className="mt-1 text-sm text-slate-400">{formatBytes(selectedFile.size)}</p> </div> </div>
{selectedFile.size > FIVE_GB && ( <div className="rounded-lg border border-amber-400/40 bg-amber-400/10 p-4 text-sm leading-6 text-amber-100"> This file is over 5GB, so upload and conversion may take several minutes. </div> )} </div> ) : ( <p className="mt-5 rounded-lg border border-slate-800 bg-slate-950/60 p-4 text-sm leading-6 text-slate-400"> No file selected yet. </p> )}
<div className="mt-6"> <h2 className="text-lg font-bold text-white">Status</h2> <p className="mt-3 text-sm leading-6 text-slate-300">{status}</p>
{isConverting && ( <div className="mt-4 h-2 overflow-hidden rounded-full bg-slate-800"> <div className="h-full w-1/2 animate-progress rounded-full bg-cyan-300" /> </div> )}
{error && ( <div className="mt-4 rounded-lg border border-red-400/40 bg-red-500/10 p-4 text-sm leading-6 text-red-100"> {error} </div> )}
{downloadUrl && ( <div className="mt-5 space-y-3"> <a ref={downloadLinkRef} href={downloadUrl} download={downloadName} className="flex h-11 items-center justify-center rounded-lg border border-cyan-300 px-4 text-sm font-bold text-cyan-100 transition hover:bg-cyan-300 hover:text-slate-950" > Download CSV </a> <button type="button" onClick={reset} className="flex h-11 w-full items-center justify-center rounded-lg border border-slate-700 px-4 text-sm font-bold text-slate-100 transition hover:border-slate-400 hover:bg-slate-800" > Convert another file </button> </div> )} </div> </aside> </section>
<footer className="py-8 text-center text-sm text-slate-500"> Free tool. Handles 200M+ rows. Powered by DuckDB. </footer> </div> </main> );}123456789import React from 'react';import ReactDOM from 'react-dom/client';import App from './App.jsx';
ReactDOM.createRoot(document.getElementById('root')).render( <React.StrictMode> <App /> </React.StrictMode>,);123456789101112131415161718192021/** @type {import('tailwindcss').Config} */export default { content: ['./index.html', './src/**/*.{js,jsx}'], theme: { extend: { fontFamily: { sans: ['Sora', 'system-ui', 'sans-serif'], }, keyframes: { progress: { '0%': { transform: 'translateX(-110%)' }, '100%': { transform: 'translateX(210%)' }, }, }, animation: { progress: 'progress 1.4s ease-in-out infinite', }, }, }, plugins: [],};123456789import { defineConfig } from 'vite';import react from '@vitejs/plugin-react';
export default defineConfig({ plugins: [react()], server: { port: 5173, },});12345678910[build]builder = "dockerfile"
[[services]]name = "backend"source = "backend"
[[services]]name = "frontend"source = "frontend"README.mdAdded+197
backend/DockerfileAdded+7
backend/main.pyAdded+150
backend/requirements.txtAdded+5
frontend/package.jsonAdded+18
frontend/postcss.config.jsAdded+6
frontend/public/index.htmlAdded+57
frontend/src/App.jsxAdded+321
frontend/src/main.jsxAdded+9
frontend/tailwind.config.jsAdded+21
frontend/vite.config.jsAdded+9
railway.tomlAdded+10