Files
FileBow/engine/filebow_engine.py
T

365 lines
20 KiB
Python

"""FileBow local file worker. JSON lines on stdout; no network access."""
from __future__ import annotations
import argparse
import base64
import io
import json
import math
import os
from pathlib import Path
import re
import subprocess
import sys
import tempfile
import zipfile
from PIL import Image, ImageOps
import pillow_heif
from pypdf import PdfReader, PdfWriter
pillow_heif.register_heif_opener()
IMAGE = set('png jpg jpeg jfif webp bmp tif tiff gif avif heic heif ico'.split())
VIDEO = set('mp4 mov avi mkv webm wmv m4v flv mpg mpeg'.split())
AUDIO = set('mp3 wav flac ogg m4a aac wma opus'.split())
FORMATS = {'jpg':'JPEG','jpeg':'JPEG','png':'PNG','webp':'WEBP','bmp':'BMP',
'tif':'TIFF','tiff':'TIFF','gif':'GIF','avif':'AVIF','ico':'ICO','heic':'HEIF','heif':'HEIF'}
def emit(data):
print(json.dumps(data, ensure_ascii=False), flush=True)
def bounded(value, default, low, high):
try: result = float(value)
except (TypeError, ValueError): result = default
if not math.isfinite(result): raise ValueError('Invalid numeric value.')
return max(low, min(high, result))
def ext(file): return Path(file).suffix.lower().lstrip('.')
def ffmpeg():
return Path(os.environ.get('FILEBOW_FFMPEG', str(Path(sys.executable).parent / '../ffmpeg/ffmpeg.exe'))).resolve()
def execute(args):
result = subprocess.run([str(x) for x in args], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
encoding='utf-8', errors='replace', creationflags=0x08000000 if os.name == 'nt' else 0)
if result.returncode:
detail = result.stderr.strip().splitlines()
raise RuntimeError('\n'.join(detail[-4:]) or 'The file could not be processed.')
return result.stdout
def media(args):
execute([ffmpeg(), '-hide_banner','-loglevel','error','-nostdin','-protocol_whitelist','file,pipe,data,crypto','-y', *args])
def probe(file):
if ext(file) in IMAGE:
with Image.open(file) as image:
return {'width':image.width,'height':image.height,'size':Path(file).stat().st_size,'kind':'image'}
if ext(file) == 'pdf': return {'pages':len(reader(file).pages),'size':Path(file).stat().st_size,'kind':'pdf'}
data = json.loads(execute([ffmpeg().with_name('ffprobe.exe'),'-v','error','-protocol_whitelist','file,pipe,data,crypto','-show_format','-show_streams','-of','json',file]))
stream = next((x for x in data['streams'] if x['codec_type']=='video'), {})
return {'width':stream.get('width',0),'height':stream.get('height',0),
'duration':float(data.get('format',{}).get('duration',0)), 'size':Path(file).stat().st_size,
'audio':any(x['codec_type']=='audio' for x in data['streams']), 'kind':'video' if stream else 'audio'}
def reader(file, password=None):
pdf = PdfReader(file)
if pdf.is_encrypted and not pdf.decrypt(password or ''):
raise ValueError('This PDF is encrypted. Remove its password first.')
return pdf
def save_output(source, suffix, writer, name=None):
"""Stage privately beside the original and publish without overwriting any file."""
source = Path(source)
stem = str(name or f'{source.stem} - FileBow').strip()
if not stem or stem in {'.','..'} or re.search(r'[<>:"/\\|?*\x00-\x1f]',stem) or stem.endswith(('.', ' ')):
raise ValueError('The filename contains invalid characters.')
if re.match(r'^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)',stem,re.I): raise ValueError('This filename is reserved by Windows.')
with tempfile.TemporaryDirectory(prefix='.filebow-'+os.environ.get('FILEBOW_JOB_ID','local')+'-',dir=source.parent) as folder:
emit({'type':'stage','directory':folder})
staged = Path(folder) / ('result.'+suffix)
extra = writer(staged) or {}
if not staged.is_file() or not staged.stat().st_size: raise RuntimeError('No output file was created.')
for index in range(100000):
target = source.parent / f'{stem}{f" ({index})" if index else ""}.{suffix}'
try:
# Windows rename is atomic and refuses an existing destination.
if os.name == 'nt': staged.rename(target)
else: os.link(staged,target); staged.unlink()
return {'ok':True,'input':str(source),'output':str(target),'size':target.stat().st_size,**extra}
except FileExistsError: continue
raise RuntimeError('No available output filename.')
def image_load(file):
with Image.open(file) as image:
image=ImageOps.exif_transpose(image)
if image.mode=='LA' or 'transparency' in image.info: image=image.convert('RGBA')
return image.copy()
def image_write(image, out, target, quality=85):
image.info.clear()
fmt = FORMATS[target]
if fmt in {'JPEG','BMP','HEIF'}:
if image.mode in {'RGBA','LA'}:
background=Image.new('RGB',image.size,'white'); background.paste(image,mask=image.getchannel('A')); image=background
else: image=image.convert('RGB')
if fmt == 'GIF': image=image.convert('P',palette=Image.Palette.ADAPTIVE)
options = {'quality':quality} if fmt in {'JPEG','WEBP','AVIF','HEIF'} else {}
if fmt == 'JPEG': options.update(optimize=True)
if fmt == 'PNG': options.update(optimize=True)
if fmt == 'ICO':
image.thumbnail((256,256)); options['sizes']=[(16,16),(32,32),(48,48),(64,64),(128,128),(256,256)]
# Explicit empty EXIF for formats that accept it. Other source metadata is not passed through.
if fmt in {'JPEG','WEBP','PNG'}: options['exif']=b''
image.save(out,fmt,**options)
def text_read(file):
kind = ext(file)
if kind == 'pdf': return '\n\n'.join(page.extract_text() or '' for page in reader(file).pages)
if kind == 'docx':
from docx import Document
doc=Document(file)
return '\n'.join([p.text for p in doc.paragraphs]+['\t'.join(c.text for c in row.cells) for t in doc.tables for row in t.rows])
if kind == 'xlsx':
from openpyxl import load_workbook
workbook=load_workbook(file,read_only=True,data_only=True)
try: return '\n\n'.join(sheet.title+'\n'+'\n'.join('\t'.join(str(v) if v is not None else '' for v in row) for row in sheet.values) for sheet in workbook)
finally: workbook.close()
if kind == 'xls':
import xlrd
workbook=xlrd.open_workbook(file)
return '\n\n'.join(sheet.name+'\n'+'\n'.join('\t'.join(str(v) for v in sheet.row_values(row)) for row in range(sheet.nrows)) for sheet in workbook.sheets())
if kind == 'pptx':
from pptx import Presentation
return '\n\n'.join('\n'.join(shape.text for shape in slide.shapes if shape.has_text_frame) for slide in Presentation(file).slides)
if kind == 'rtf':
from striprtf.striprtf import rtf_to_text
return rtf_to_text(Path(file).read_text(encoding='utf-8',errors='replace'))
if kind == 'epub':
from bs4 import BeautifulSoup
from xml.etree import ElementTree as ET
with zipfile.ZipFile(file) as archive:
container=ET.fromstring(archive.read('META-INF/container.xml'))
opf=next(x.attrib['full-path'] for x in container.iter() if x.tag.endswith('rootfile'))
package=ET.fromstring(archive.read(opf)); manifest={x.attrib['id']:x.attrib['href'] for x in package.iter() if x.tag.endswith('}item')}
from posixpath import normpath,join,dirname
pages=[normpath(join(dirname(opf),manifest[x.attrib['idref']])) for x in package.iter() if x.tag.endswith('itemref')]
return '\n\n'.join(BeautifulSoup(archive.read(page),'html.parser').get_text('\n') for page in pages)
if kind in {'doc','ppt'}: raise ValueError('Save this document as DOCX or PPTX first.')
raw=Path(file).read_bytes()
if raw.startswith((b'\xff\xfe',b'\xfe\xff')): return raw.decode('utf-16')
try: text=raw.decode('utf-8-sig')
except UnicodeDecodeError: text=raw.decode('cp1252')
if kind in {'html','htm'}:
from bs4 import BeautifulSoup
return BeautifulSoup(text,'html.parser').get_text('\n')
return text
def text_write(text,out,target):
if target in {'txt','md'}: out.write_text(text,encoding='utf-8'); return
if target == 'docx':
from docx import Document
doc=Document()
for line in text.splitlines(): doc.add_paragraph(line)
doc.save(out); return
if target == 'pdf':
from fpdf import FPDF
pdf=FPDF(); pdf.set_auto_page_break(True,margin=16)
font=Path(os.environ.get('WINDIR','C:/Windows'))/'Fonts/segoeui.ttf'
if font.exists(): pdf.add_font('System',fname=str(font)); pdf.set_font('System',size=10)
else: pdf.set_font('Helvetica',size=10); text=text.encode('latin1',errors='replace').decode('latin1')
pdf.add_page()
pdf.multi_cell(0,5,text.replace('\t',' '),new_x='LMARGIN',new_y='NEXT')
pdf.output(str(out)); return
raise ValueError('Unsupported document format.')
def video_args(target, options=None, bitrate=None):
options=options or {}
if target == 'webm': return ['-c:v','libvpx-vp9','-b:v',str(bitrate or 0),'-crf',str(int(bounded(options.get('crf'),32,10,50))),'-c:a','libopus','-b:a','128k']
if target == 'mp4': return ['-c:v','libopenh264','-b:v',str(bitrate or 2500000),'-pix_fmt','yuv420p','-c:a','aac','-b:a','128k','-movflags','+faststart']
if target == 'gif': return ['-an','-vf','fps=12,scale=640:-1:flags=lanczos,split[a][b];[a]palettegen[p];[b][p]paletteuse']
raise ValueError('Unsupported video format.')
def audio_args(target, bitrate='192k'):
choices={'mp3':['-c:a','libmp3lame','-b:a',bitrate],'wav':['-c:a','pcm_s16le'],
'm4a':['-c:a','aac','-b:a',bitrate],'flac':['-c:a','flac'],
'ogg':['-c:a','libvorbis','-b:a',bitrate]}
if target not in choices: raise ValueError('Unsupported audio format.')
return ['-vn',*choices[target]]
def convert(file,target,options):
kind=ext(file)
def writer(out):
if kind in IMAGE:
image=image_load(file)
if target=='pdf': image.convert('RGB').save(out,'PDF',resolution=150)
elif target in FORMATS: image_write(image,out,target,int(bounded(options.get('quality'),85,1,100)))
else: raise ValueError('Unsupported image format.')
elif kind in VIDEO:
args=['-i',file]
if target=='mp4': args += ['-vf','pad=ceil(iw/2)*2:ceil(ih/2)*2']
media([*args,*video_args(target),out])
elif kind in AUDIO: media(['-i',file,*audio_args(target),out])
else: text_write(text_read(file),out,target)
return save_output(file,target,writer,options.get('outputName'))
def compression_format(file):
kind=ext(file)
if kind in IMAGE:
if kind in {'png','webp','avif'}: return kind
with Image.open(file) as image:
if 'A' in image.getbands() or 'transparency' in image.info: return 'png'
return 'jpg'
return 'mp4' if kind in VIDEO else 'mp3' if kind in AUDIO else 'pdf'
def compress(file,options,estimate=False):
kind=ext(file); quality=int(bounded(options.get('quality'),75,5,95))
limit=int(bounded(options.get('maxSizeMB'),0,0,100000)*1024*1024)
suffix = compression_format(file)
def writer(out):
if kind in IMAGE:
image=image_load(file)
suffix_format=suffix
for q in range(quality,4,-5):
image_write(image,out,suffix_format,q)
if not limit or out.stat().st_size <= limit or suffix=='png': break
for _ in range(8):
if not limit or out.stat().st_size <= limit: break
image.thumbnail((max(1,int(image.width*.8)),max(1,int(image.height*.8))))
image_write(image,out,suffix_format,30)
elif kind in VIDEO:
info=probe(file); duration=max(info['duration'],.1)
bitrate=max(32000,int(limit*8/duration*.88-128000)) if limit else int(300000+quality*40000)
media(['-i',file,'-vf','pad=ceil(iw/2)*2:ceil(ih/2)*2',*video_args('mp4',bitrate=bitrate),out])
elif kind in AUDIO:
duration=max(probe(file)['duration'],.1)
bitrate=max(32,min(320,int(limit*8/duration/1000*.95))) if limit else max(32,int(quality*2.56))
media(['-i',file,*audio_args('mp3',f'{bitrate}k'),out])
elif kind=='pdf':
pdf=PdfWriter(clone_from=reader(file))
for page in pdf.pages: page.compress_content_streams()
pdf.compress_identical_objects(remove_duplicates=True,remove_unreferenced=True)
pdf.write(out)
else: raise ValueError('This file cannot be compressed.')
return {'targetMet':not limit or out.stat().st_size<=limit}
if estimate:
original=Path(file).stat().st_size
if kind in VIDEO|AUDIO:
info=probe(file); duration=max(info['duration'],.1)
if kind in VIDEO:
bitrate=max(32000,int(limit*8/duration*.88-128000)) if limit else int(300000+quality*40000)
size=int(duration*(bitrate+(128000 if info['audio'] else 0))/8*1.03)
else:
bitrate=max(32,min(320,int(limit*8/duration/1000*.95))) if limit else max(32,int(quality*2.56))
size=int(duration*bitrate*1000/8*1.03)
exact=False
else:
with tempfile.TemporaryDirectory(prefix='.filebow-'+os.environ.get('FILEBOW_JOB_ID','local')+'-',dir=Path(file).parent) as folder:
emit({'type':'stage','directory':folder})
out=Path(folder)/('estimate.'+suffix); writer(out); size=out.stat().st_size
exact=True
return {'ok':True,'input':str(file),'size':size,'originalSize':original,'format':suffix,'exact':exact,'targetMet':not limit or size<=limit}
return save_output(file,suffix,writer,options.get('outputName'))
def edit(file,options):
kind=ext(file); suffix=kind if kind in FORMATS else 'mp4'
width=int(bounded(options.get('width'),0,0,30000)); height=int(bounded(options.get('height'),0,0,30000))
angle=int(bounded(options.get('rotate'),0,-360,360))
def writer(out):
if kind in IMAGE:
image=image_load(file)
crop=options.get('crop')
if crop:
x=int(bounded(crop.get('x'),0,0,image.width-1)); y=int(bounded(crop.get('y'),0,0,image.height-1))
w=int(bounded(crop.get('width'),image.width,1,image.width-x)); h=int(bounded(crop.get('height'),image.height,1,image.height-y))
image=image.crop((x,y,x+w,y+h))
if width or height:
w=width or max(1,round(image.width*height/image.height)); h=height or max(1,round(image.height*width/image.width))
if w*h > 100000000: raise ValueError('The output image cannot exceed 100 megapixels.')
image=image.resize((w,h),Image.Resampling.LANCZOS)
if angle: image=image.rotate(-angle,expand=True)
if options.get('flipH'): image=ImageOps.mirror(image)
if options.get('flipV'): image=ImageOps.flip(image)
image_write(image,out,suffix)
else:
if not width and not height: raise ValueError('Enter a width or height.')
media(['-i',file,'-vf',f'scale={width or -2}:{height or -2},pad=ceil(iw/2)*2:ceil(ih/2)*2',*video_args('mp4'),out])
return save_output(file,suffix,writer,options.get('outputName'))
def metadata(file,options):
kind=ext(file)
def writer(out):
if kind in IMAGE: image_write(image_load(file),out,kind,95)
elif kind=='pdf':
pdf=PdfWriter(clone_from=reader(file)); pdf.metadata=None
if '/Metadata' in pdf._root_object: del pdf._root_object['/Metadata']
pdf.write(out)
elif kind in VIDEO|AUDIO: media(['-i',file,'-map','0','-map_metadata','-1','-map_chapters','-1','-c','copy',out])
else: raise ValueError('This format is not supported.')
return save_output(file,kind,writer,options.get('outputName'))
def combined(files,target,options):
def writer(out):
if target=='pdf' and all(ext(f)=='pdf' for f in files):
pdf=PdfWriter()
for file in files: pdf.append(reader(file))
pdf.write(out)
elif target=='pdf' and all(ext(f) in IMAGE for f in files):
images=[image_load(f).convert('RGB') for f in files]
images[0].save(out,'PDF',save_all=True,append_images=images[1:],resolution=150)
for image in images: image.close()
else: text_write('\n\n'.join(text_read(f) for f in files),out,target)
return save_output(files[0],target,writer,options.get('outputName') or 'Combined')
def dispatch(file,op,target,options):
if op=='convert': return convert(file,target,options)
if op=='compress': return compress(file,options)
if op=='estimate-compression': return compress(file,options,estimate=True)
if op=='edit': return edit(file,options)
if op=='strip-metadata': return metadata(file,options)
if op=='pdf-password':
password=options.get('password')
if not isinstance(password,str) or not password: raise ValueError('Enter a password.')
def write(out):
pdf=PdfWriter(clone_from=reader(file,password))
if options.get('mode')=='add': pdf.encrypt(password,algorithm='AES-256')
pdf.write(out)
return save_output(file,'pdf',write,options.get('outputName'))
if op=='frame':
timestamp=bounded(options.get('time'),0,0,1e9)
return save_output(file,'png',lambda out: media(['-ss',timestamp,'-i',file,'-frames:v','1',out]),options.get('outputName'))
if op=='extract-audio': return save_output(file,target or 'mp3',lambda out: media(['-i',file,*audio_args(target or 'mp3'),out]),options.get('outputName'))
if op=='probe': return {'ok':True,'input':file,**probe(file)}
if op=='preview':
if ext(file) in IMAGE:
image=image_load(file); original=image.size; image.thumbnail((1000,700))
buffer=io.BytesIO(); image.save(buffer,'PNG')
return {'ok':True,'input':file,'width':original[0],'height':original[1],
'dataUrl':'data:image/png;base64,'+base64.b64encode(buffer.getvalue()).decode('ascii')}
return {'ok':True,'input':file,**probe(file)}
raise ValueError('Unknown operation.')
def run_job(job):
files=job.get('files'); op=job.get('op'); target=str(job.get('target') or '').lower(); options=job.get('options') or {}
if not isinstance(files,list) or not files or len(files)>1000: raise ValueError('Select between 1 and 1,000 files.')
files=[str(Path(f).resolve(strict=True)) for f in files]
if not all(Path(f).is_file() for f in files): raise ValueError('Folders are not supported.')
results=[]
if op in {'zip','combine','merge','image-to-pdf'}:
if op=='zip':
def archive(out):
names=set()
with zipfile.ZipFile(out,'w',compression=zipfile.ZIP_DEFLATED) as z:
for file in files:
name=Path(file).name; counter=1
while name.casefold() in names:
name=f'{Path(file).stem} ({counter}){Path(file).suffix}'; counter+=1
names.add(name.casefold()); z.write(file,name)
results=[save_output(files[0],'zip',archive,options.get('outputName') or 'Archive')]
else: results=[combined(files,'pdf' if op in {'merge','image-to-pdf'} else target,options)]
emit({'type':'progress','done':len(files),'total':len(files),'file':files[-1]})
else:
for index,file in enumerate(files):
try: results.append(dispatch(file,op,target,options))
except Exception as exc: results.append({'ok':False,'input':file,'error':str(exc)})
emit({'type':'progress','done':index+1,'total':len(files),'file':file})
return results
def main():
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
parser=argparse.ArgumentParser(); parser.add_argument('--job',required=True); args=parser.parse_args()
try:
job=json.loads(Path(args.job).read_text(encoding='utf-8-sig'))
emit({'type':'result','results':run_job(job)})
except Exception as exc: emit({'type':'error','message':str(exc)}); sys.exit(1)
if __name__=='__main__': main()