import dynamic from 'next/dynamic'; const PdfPreview=dynamic(()=>import('../components/PdfPreview'),{ssr:false,loading:()=>
正在加载 PDF 预览…
}); import Head from 'next/head'; import {useEffect,useState} from 'react'; import {FileText,Braces,Plus,Trash2,ArrowRight,Play,Download,Copy,Upload,Sparkles,ChevronRight,Check,Code2} from 'lucide-react'; import {Field,buildSchema,sampleFields,sampleText} from '../lib/schema'; const types:Field['type'][]=['string','number','boolean','object','array']; function Editor({fields,onChange,depth=0}:{fields:Field[];onChange:(f:Field[])=>void;depth?:number}){ const update=(i:number,patch:Partial)=>onChange(fields.map((f,n)=>n===i?{...f,...patch}:f)); return
{fields.map((f,i)=>
update(i,{name:e.target.value})}/>update(i,{description:e.target.value})}/>
{(f.type==='object'||f.type==='array')&&
{f.name} {f.fields?.length||0} 个嵌套字段{f.type==='array'&&!f.fields?.length&&当前为文本数组}
update(i,{fields:children})} depth={depth+1}/>
}
)}{depth<5&&}
; } export default function Home(){ const [fields,setFields]=useState(sampleFields),[text,setText]=useState(sampleText),[file,setFile]=useState(null),[url,setUrl]=useState(''),[tab,setTab]=useState('config'),[format,setFormat]=useState('formatted'),[result,setResult]=useState(null),[busy,setBusy]=useState(false),[error,setError]=useState(''),[notice,setNotice]=useState(''),[health,setHealth]=useState(null),[token,setToken]=useState(''),[task,setTask]=useState(null),[instructions,setInstructions]=useState(''),[resultView,setResultView]=useState('tables'),[schemas,setSchemas]=useState([]),[schemaChoice,setSchemaChoice]=useState(''); useEffect(()=>{fetch('/api/v1/health').then(r=>r.json()).then(setHealth).catch(()=>{});try{const saved=localStorage.getItem('extractor-fields');if(saved){const parsed=JSON.parse(saved);buildSchema(parsed);setFields(parsed);}const last=localStorage.getItem('extractor-task');if(last){const restored=JSON.parse(last);setTask(restored);setFields(restored.fields);setText('');}}catch{}},[]); useEffect(()=>{if(!file)return;const u=URL.createObjectURL(file);setUrl(u);return()=>URL.revokeObjectURL(u);},[file]); function change(f:Field[]){setTask(null);setInstructions('');localStorage.removeItem('extractor-task');setFields(f);setResult(null);localStorage.setItem('extractor-fields',JSON.stringify(f));} async function copy(s:string){try{await navigator.clipboard.writeText(s);setNotice('已复制');setTimeout(()=>setNotice(''),2000);}catch{setError('复制失败,请手动选择文本复制');}} function download(data:any,name:string){const u=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=u;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(u),1000);} const auth=()=>token?{Authorization:`Bearer ${token}`} as Record:{}; async function loadSchemas(){try{const r=await fetch('/api/v1/schemas',{headers:auth()});const p=await r.json();if(!r.ok)throw new Error(p.error?.message||'读取 schema 失败');setSchemas(p.schemas);setNotice(p.schemas.length?'可复用 schema 已刷新':'暂无已保存 schema');setTimeout(()=>setNotice(''),2000);}catch(e:any){setError(e.message);}} async function saveSchema(){const name=window.prompt('为当前 schema 命名');if(!name)return;try{const r=await fetch('/api/v1/schemas',{method:'POST',headers:{...auth(),'Content-Type':'application/json'},body:JSON.stringify({name,fields})});const p=await r.json();if(!r.ok)throw new Error(p.error?.message||'保存失败');await loadSchemas();setSchemaChoice(p.id);}catch(e:any){setError(e.message);}} async function refreshTask(id:string){const r=await fetch(`/api/v1/tasks/${id}`,{headers:auth()});if(!r.ok)return;const t=await r.json();setTask(t);const out=await fetch(t.links.result,{headers:auth()});if(out.status===200){setResult(await out.json());setTab('results');}} useEffect(()=>{if(!task?.id)return;let active=true;const sync=async()=>{try{const r=await fetch(`/api/v1/tasks/${task.id}/result`,{headers:token?{Authorization:`Bearer ${token}`}:{}});if(r.status===200&&active){setResult(await r.json());}}catch{}};sync();const timer=setInterval(sync,3000);return()=>{active=false;clearInterval(timer);};},[task?.id,token]); async function markdown(t=task){const r=await fetch(t.links.instructions,{headers:auth()});if(!r.ok)throw new Error('无法读取任务说明,请检查访问令牌');return await r.text();} async function copyInstructions(){try{await copy(await markdown());}catch(e:any){setError(e.message);}} async function downloadInstructions(){try{const md=await markdown();const u=URL.createObjectURL(new Blob([md],{type:'text/markdown;charset=utf-8'}));const a=document.createElement('a');a.href=u;a.download=`task-${task.id}.md`;a.click();setTimeout(()=>URL.revokeObjectURL(u),1000);}catch(e:any){setError(e.message);}} function csv(table:any){const rows=[table.columns,...table.rows];const content='\ufeff'+rows.map((row:any[])=>row.map(v=>'"'+String(v??'').replaceAll('"','""')+'"').join(',')).join('\r\n');const u=URL.createObjectURL(new Blob([content],{type:'text/csv;charset=utf-8'}));const a=document.createElement('a');a.href=u;a.download=table.name+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(u),1000);} async function run(){setError('');try{buildSchema(fields);}catch(e:any){setError(e.message);return;}setBusy(true);try{const body=new FormData();body.append('fields',JSON.stringify(fields));body.append('title',(file?.name||'文档提取任务').slice(0,120));if(file)body.append('file',file);else if(task&&!text){const source=await fetch(task.links.document,{headers:auth()});if(!source.ok)throw new Error('无法读取已保存原件');body.append('file',await source.blob(),task.document.name);}else body.append('text',text);const r=await fetch('/api/v1/tasks',{method:'POST',body,headers:auth()});const p=await r.json();if(!r.ok)throw new Error(p.error?.message||'请求失败');setTask(p);setResult(null);setInstructions(await markdown(p));localStorage.setItem('extractor-task',JSON.stringify(p));setNotice('任务已保存,复制 Markdown 给 agent 即可');setTimeout(()=>setNotice(''),3500);}catch(e:any){setError(e.message);}finally{setBusy(false);}} return <>Fieldwork · 模块化信息提取器
fieldworkLOCAL STUDIO
API 文档
DOCUMENT → STRUCTURED DATA

让信息,各归其位。

定义你关心的字段,把繁杂文档转为可直接使用的数据。

本地工作空间PDF / IMAGE / TEXT
01文档来源
SOURCE
{task&&!file?
{task.document.name}{(task.document.size/1024).toFixed(1)} KB · 已保存任务原件
{(task.document.mime==='application/pdf'||/\.pdf$/i.test(task.document.name))?:

文档已安全保存在本机

Agent 可从任务 API 下载原始文件点击「粘贴文本」或上传新文件可开始新任务
}
:file?
{file.name}{(file.size/1024).toFixed(1)} KB
{file.type.startsWith('image/')?上传文档预览:(file.type==='application/pdf'||/\.pdf$/i.test(file.name))?:

文本文件已就绪

创建任务后,agent 可通过 API 下载文件
}
:
原始文档 可编辑