Spaces:
Sleeping
Sleeping
File size: 9,028 Bytes
76fcab1 287e3a1 76fcab1 287e3a1 76fcab1 287e3a1 76fcab1 287e3a1 76fcab1 287e3a1 76fcab1 287e3a1 76fcab1 287e3a1 76fcab1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | """Shared semantic document layout: paragraphs, headings, lists and action tables."""
import io,re
def paragraphs(text):
"""Add whitespace boundaries only, preserving the words and numbered clauses."""
result=[]
for paragraph in re.split(r'\n\s*\n',str(text).strip()):
markers=list(re.finditer(r'[((]\d{1,2}[))]',paragraph))
pieces=[]
if len(markers)>=2:
starts=[0]+[m.start() for m in markers if m.start()>0]
pieces=[paragraph[a:b].strip() for a,b in zip(starts,starts[1:]+[len(paragraph)])]
else:pieces=[paragraph.strip()]
for piece in pieces:
while len(piece)>300:
end=piece.rfind('。',100,300)
if end<0:break
result.append(piece[:end+1].strip());piece=piece[end+1:].strip()
if piece:result.append(piece)
return '\n\n'.join(result)
def blocks(text):
rows=[]
def flush():
nonlocal rows
value=rows;rows=[];return ('table',value)
for raw in str(text).splitlines():
line=raw.strip()
if line.startswith('|') and line.endswith('|'):
cells=[v.strip() for v in re.split(r'(?<!\\)\|',line[1:-1])]
if not all(re.fullmatch(r':?-+:?',v.replace(' ','')) for v in cells):rows.append(cells)
continue
if rows:yield flush()
if not line:continue
heading=re.match(r'^(#{1,6})\s+(.+)',line)
if heading:yield ('heading',(len(heading[1]),heading[2]));continue
bullet=re.match(r'^[-*+]\s+(.+)',line)
numbered=re.match(r'^\d+[.)、]\s*(.+)',line)
if bullet:yield ('bullet',bullet[1]);continue
if numbered:yield ('paragraph',line);continue
for para in paragraphs(line).split('\n\n'):
if para:yield ('paragraph',para)
if rows:yield flush()
def plain(text):return re.sub(r'\*\*([^*]+)\*\*|`([^`]+)`',lambda m:m[1] or m[2],text)
def docx_bytes(artifact):
from docx import Document
from docx.shared import Cm,Pt,RGBColor
from docx.enum.table import WD_TABLE_ALIGNMENT,WD_CELL_VERTICAL_ALIGNMENT
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
doc=Document();section=doc.sections[0];section.page_width=Cm(21);section.page_height=Cm(29.7)
section.top_margin=Cm(2.2);section.bottom_margin=Cm(2);section.left_margin=Cm(2.1);section.right_margin=Cm(2.1)
for name,size in [('Normal',11.5),('Title',19),('Heading 1',14),('Heading 2',12.5),('Heading 3',11.5),('List Bullet',11),('List Number',11)]:
style=doc.styles[name];style.font.name='Calibri';style.font.size=Pt(size);style.font.color.rgb=RGBColor(0,0,0)
style.font.bold=name=='Title' or name.startswith('Heading')
style.element.get_or_add_rPr().rFonts.set(qn('w:eastAsia'),'楷体' if name=='Heading 2' else '黑体' if name!='Normal' and not name.startswith('List') else '宋体')
fmt=style.paragraph_format;fmt.line_spacing=1.5;fmt.space_before=Pt(0 if name=='Normal' else 10);fmt.space_after=Pt(7);fmt.widow_control=True
if name.startswith('Heading') or name=='Title':fmt.keep_with_next=True
def runs(p,value):
for piece in re.split(r'(\*\*.*?\*\*|`[^`]+`)',value):
r=p.add_run(piece[2:-2] if piece.startswith('**') and piece.endswith('**') else piece[1:-1] if piece.startswith('`') and piece.endswith('`') else piece)
if piece.startswith('**') and piece.endswith('**'):r.bold=True
title_done=False
for kind,value in blocks(artifact['content']):
if kind=='table':
width=max(len(row) for row in value);table=doc.add_table(rows=0,cols=width);table.style='Table Grid';table.alignment=WD_TABLE_ALIGNMENT.CENTER;table.autofit=False
borders=OxmlElement('w:tblBorders')
for edge in ('top','left','bottom','right','insideH','insideV'):
border=OxmlElement('w:'+edge);border.set(qn('w:val'),'single');border.set(qn('w:sz'),'4');border.set(qn('w:color'),'D9D9D9');borders.append(border)
table._tbl.tblPr.append(borders)
widths=[9.4,3,4.4] if width==3 else [16.8/width]*width
for col,cm in zip(table.columns,widths):col.width=Cm(cm)
for index,values in enumerate(value):
row=table.add_row();props=row._tr.get_or_add_trPr();props.append(OxmlElement('w:cantSplit'))
if index==0:props.append(OxmlElement('w:tblHeader'))
for i,cell in enumerate(row.cells):
cell.width=Cm(widths[i]);cell.vertical_alignment=WD_CELL_VERTICAL_ALIGNMENT.CENTER;p=cell.paragraphs[0];p.paragraph_format.space_after=Pt(4);p.paragraph_format.space_before=Pt(4);p.paragraph_format.line_spacing=1.2
p.alignment=1 if i>0 and width==3 else 0
margin=OxmlElement('w:tcMar')
for edge in ('top','left','bottom','right'):
pad=OxmlElement('w:'+edge);pad.set(qn('w:w'),'90');pad.set(qn('w:type'),'dxa');margin.append(pad)
cell._tc.get_or_add_tcPr().append(margin)
runs(p,values[i] if i<len(values) else '')
for run in p.runs:run.font.size=Pt(10.5);run.bold=index==0
if index==0:
shade=OxmlElement('w:shd');shade.set(qn('w:fill'),'EEF1F5');cell._tc.get_or_add_tcPr().append(shade)
continue
if not title_done:
title=value[1] if kind=='heading' else value
if len(title)>24 and '—' in title:title=re.sub(r'—+','\n',title,count=1)
p=doc.add_paragraph(style='Title');p.alignment=1;p.paragraph_format.space_before=Pt(0);p.paragraph_format.space_after=Pt(15);runs(p,title)
if len(title)>24:
for r in p.runs:r.font.size=Pt(16)
doc.core_properties.title=plain(title);title_done=True;continue
if kind=='heading':p=doc.add_paragraph(style='Heading '+str(min(max(value[0]-1,1),3)));runs(p,value[1])
else:p=doc.add_paragraph(style='List Bullet' if kind=='bullet' else 'List Number' if kind=='number' else 'Normal');runs(p,value)
footer=section.footer.paragraphs[0];footer.alignment=1;footer.add_run(f'Work OS · v{artifact["version"]} · '+('已核对' if artifact['approval_status']=='approved' else '待核对草稿')+' · 第 ')
field=OxmlElement('w:fldSimple');field.set(qn('w:instr'),'PAGE');footer._p.append(field);footer.add_run(' 页')
for run in footer.runs:run.font.size=Pt(9);run.font.color.rgb=RGBColor.from_string('708478')
# Some bundled Word templates carry a decorative border on Title/Normal.
for element in [style.element for style in doc.styles]+[p._p for p in doc.paragraphs]:
for border in list(element.iter(qn('w:pBdr'))):border.getparent().remove(border)
stream=io.BytesIO();doc.save(stream);return stream.getvalue()
def pdf_bytes(artifact,font='STSong-Light'):
from reportlab.platypus import SimpleDocTemplate,Paragraph,Spacer,Table,TableStyle
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from xml.sax.saxutils import escape
stream=io.BytesIO();doc=SimpleDocTemplate(stream,pagesize=A4,leftMargin=59,rightMargin=59,topMargin=62,bottomMargin=56)
body=ParagraphStyle('body',fontName=font,fontSize=11,leading=18,wordWrap='CJK',spaceAfter=8)
title=ParagraphStyle('title',parent=body,fontSize=17,leading=25,alignment=1,spaceAfter=16,keepWithNext=True)
heading=ParagraphStyle('heading',parent=body,fontSize=13,leading=20,spaceBefore=12,spaceAfter=9,keepWithNext=True)
cell=ParagraphStyle('cell',parent=body,fontSize=10,leading=15,spaceAfter=0)
story=[];first=True
for kind,value in blocks(artifact['content']):
if kind=='table':
width=max(len(row) for row in value);rows=[[Paragraph(escape(plain(row[i] if i<len(row) else '')),cell) for i in range(width)] for row in value]
table=Table(rows,colWidths=[267,85,125] if width==3 else [477/width]*width,repeatRows=1,hAlign='LEFT');table.setStyle(TableStyle([('GRID',(0,0),(-1,-1),.5,colors.HexColor('#cdd9d1')),('BACKGROUND',(0,0),(-1,0),colors.HexColor('#eef3f0')),('VALIGN',(0,0),(-1,-1),'TOP'),('LEFTPADDING',(0,0),(-1,-1),7),('RIGHTPADDING',(0,0),(-1,-1),7),('TOPPADDING',(0,0),(-1,-1),7),('BOTTOMPADDING',(0,0),(-1,-1),7)]));story.extend([table,Spacer(1,10)]);continue
text=value[1] if kind=='heading' else value
if kind=='bullet':text='• '+text
story.append(Paragraph(escape(plain(text)),title if first else heading if kind=='heading' else body));first=False
if not story:story=[Paragraph('空白文稿',body)]
def footer(canvas,document):
canvas.saveState();canvas.setFont(font,9);canvas.setFillColor(colors.HexColor('#708478'));canvas.drawCentredString(A4[0]/2,30,f'Work OS · v{artifact["version"]} · {document.page}');canvas.restoreState()
doc.build(story,onFirstPage=footer,onLaterPages=footer);return stream.getvalue()
|