Spaces:
Sleeping
Sleeping
Audio/video: decode with ffmpeg to float32 before faster-whisper (fixes PyAV metadata_errors clash)
95c2676 verified Download intake.py from Basementup/Seamstressesstitching: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/spaces/Basementup/Seamstressesstitching/resolve/main/intake.py
- Command line
-
hf download hf://spaces/Basementup/Seamstressesstitching/intake.py
-
curl -L -o intake.py https://huggingface.co/spaces/Basementup/Seamstressesstitching/resolve/main/intake.py
13.1 kB
| """Intake: turn any supported upload into paragraphs for the merge engine, plus a page/time map | |
| so every sentence can be traced back to "document, page (or time), paragraph". | |
| Supported: PDF (text layer; scanned pages are OCR'd with Tesseract), images (OCR), Word .docx, | |
| .txt/.md, email .eml (attachments become their own documents), .html, .rtf, .odt, .csv, .xlsx, | |
| audio/video (MP3, M4A, WAV, MP4, MOV ... transcribed on CPU with faster-whisper, timestamped), | |
| and Google Docs/Sheets/Slides or Drive links shared as "Anyone with the link". | |
| No paid APIs. Everything runs on the Space's CPU.""" | |
| import csv, email, email.policy, email.utils, hashlib, io, os, re, subprocess, tempfile | |
| import stitch | |
| AUDIO_EXT = {'.mp3', '.wav', '.m4a', '.aac', '.ogg', '.oga', '.opus', '.flac', '.wma', '.amr'} | |
| VIDEO_EXT = {'.mp4', '.mov', '.mkv', '.webm', '.avi', '.m4v', '.3gp', '.wmv'} | |
| IMAGE_EXT = {'.png', '.jpg', '.jpeg', '.tif', '.tiff', '.bmp', '.webp', '.gif'} | |
| TEXT_EXT = {'.txt', '.md', '.markdown', '.text', '.log'} | |
| OTHER_EXT = {'.pdf', '.docx', '.eml', '.html', '.htm', '.rtf', '.csv', '.xlsx', '.xlsm', '.odt', '.json'} | |
| SUPPORTED = sorted(AUDIO_EXT | VIDEO_EXT | IMAGE_EXT | TEXT_EXT | OTHER_EXT) | |
| OCR_MIN_CHARS = 40 | |
| PARA_END = 0.85 # a wrapped line shorter than 85% of the usual width that ends a sentence ends the paragraph | |
| _CACHE = {} # sha256 of bytes -> parsed result (OCR/transcription is slow; never do it twice) | |
| _WHISPER = {} | |
| def flat(s): | |
| return re.sub(r'\s+', ' ', (s or '').replace('**', '')).strip() | |
| def key(s): | |
| """Alphanumeric-only lower-case form used to find a sentence inside a page.""" | |
| return re.sub(r'[^0-9a-z\u00a3]+', '', stitch.normalise(s) if hasattr(stitch, 'normalise') else s.lower()) | |
| def fmt_ts(sec): | |
| sec = int(round(sec)); h, r = divmod(sec, 3600); m, s = divmod(r, 60) | |
| return f'{h}:{m:02d}:{s:02d}' if h else f'{m:02d}:{s:02d}' | |
| # ---------------------------------------------------------------- OCR / media helpers | |
| def _ocr(img): | |
| import pytesseract | |
| return pytesseract.image_to_string(img, config='--psm 3') | |
| def _pdf(path, meta): | |
| from pypdf import PdfReader | |
| reader = PdfReader(path) | |
| texts = [] | |
| for p in reader.pages: | |
| try: | |
| texts.append(p.extract_text() or '') | |
| except Exception: | |
| texts.append('') | |
| need = [i for i, t in enumerate(texts) if len(t.strip()) < OCR_MIN_CHARS] | |
| meta['pages'] = len(texts) | |
| if not need: | |
| meta['extractor'] = 'PDF text layer' | |
| return stitch.extract_lines(stitch._pdf_lines(path), PARA_END), [(f'p{i + 1}', t) for i, t in enumerate(texts)] | |
| from pdf2image import convert_from_path | |
| for i in need: | |
| try: | |
| img = convert_from_path(path, dpi=300, first_page=i + 1, last_page=i + 1)[0] | |
| texts[i] = _ocr(img) | |
| except Exception as e: # noqa | |
| meta.setdefault('warnings', []).append(f'page {i + 1}: OCR failed ({e})') | |
| meta['extractor'] = f'PDF text layer + OCR on {len(need)} scanned page(s) (check OCR text against the original)' | |
| meta['ocr'] = True | |
| lines = [] | |
| for t in texts: | |
| pl = t.replace('\r', '\n').strip('\n ').split('\n') | |
| lines.extend(pl); lines.append('\x0c') | |
| return stitch.extract_lines(lines, PARA_END), [(f'p{i + 1}', t) for i, t in enumerate(texts)] | |
| def _image(path, meta): | |
| from PIL import Image | |
| img = Image.open(path) | |
| pages = [] | |
| for i in range(getattr(img, 'n_frames', 1)): | |
| img.seek(i) | |
| pages.append((f'p{i + 1}', _ocr(img.convert('RGB')))) | |
| meta['extractor'] = 'OCR (Tesseract, English) - check OCR text against the original' | |
| meta['ocr'] = True | |
| return stitch.extract_text('\n\n'.join(t for _, t in pages)), pages | |
| def _media(path, meta): | |
| # decode with ffmpeg to 16 kHz mono float32 ourselves (avoids PyAV version clashes inside faster-whisper) | |
| r = subprocess.run(['ffmpeg', '-nostdin', '-i', path, '-vn', '-ac', '1', '-ar', '16000', '-f', 'f32le', '-'], | |
| capture_output=True, timeout=1800) | |
| if r.returncode != 0 or not r.stdout: | |
| raise RuntimeError('could not decode the audio track') | |
| import numpy as np | |
| audio = np.frombuffer(r.stdout, dtype=np.float32).copy() | |
| try: | |
| if 'base' not in _WHISPER: | |
| from faster_whisper import WhisperModel | |
| _WHISPER['base'] = WhisperModel('base', device='cpu', compute_type='int8', cpu_threads=2) | |
| segs, info = _WHISPER['base'].transcribe(audio, beam_size=5, vad_filter=True, temperature=0.0, | |
| condition_on_previous_text=False) | |
| pages, paras = [], [] | |
| for s in segs: | |
| t = (s.text or '').strip() | |
| if t: | |
| pages.append((f'@{fmt_ts(s.start)}', t)) | |
| paras.append(t) | |
| finally: | |
| del audio | |
| meta['extractor'] = f'transcribed with faster-whisper (base, CPU), language {info.language} - listen to check quotes' | |
| meta['audio'] = True | |
| # group transcript segments into paragraphs of ~5 segments so sentences stay whole | |
| text = '\n\n'.join(' '.join(paras[i:i + 5]) for i in range(0, len(paras), 5)) | |
| return stitch.extract_text(text), pages | |
| def _html_to_text(html): | |
| from bs4 import BeautifulSoup | |
| soup = BeautifulSoup(html, 'html.parser') | |
| for t in soup(['script', 'style', 'head']): | |
| t.decompose() | |
| for br in soup.find_all('br'): | |
| br.replace_with('\n') | |
| for blk in soup.find_all(['p', 'div', 'li', 'tr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'table']): | |
| blk.insert_after('\n\n') | |
| txt = re.sub(r'[ \t\u00a0]+', ' ', soup.get_text()) | |
| return re.sub(r'\n\s*\n\s*(\n\s*)+', '\n\n', txt).strip() | |
| def _eml(path, meta): | |
| msg = email.message_from_bytes(open(path, 'rb').read(), policy=email.policy.default) | |
| head = [f"{k}: {msg.get(k)}" for k in ('From', 'To', 'Date', 'Subject') if msg.get(k)] | |
| body = msg.get_body(preferencelist=('plain', 'html')) | |
| text = '' | |
| if body is not None: | |
| text = body.get_content() | |
| if body.get_content_type() == 'text/html': | |
| text = _html_to_text(text) | |
| atts = [] | |
| for part in msg.iter_attachments(): | |
| fn = part.get_filename() | |
| if fn and os.path.splitext(fn.lower())[1] in SUPPORTED: | |
| d = tempfile.mkdtemp(); p = os.path.join(d, os.path.basename(fn)) | |
| open(p, 'wb').write(part.get_payload(decode=True) or b'') | |
| atts.append(p) | |
| meta['extractor'] = 'email (headers + body)' + (f'; {len(atts)} attachment(s) read as separate documents' if atts else '') | |
| full = '\n'.join(head) + '\n\n' + text | |
| return stitch.extract_text(full), [('p1', full)], atts | |
| def _rows(rows): | |
| rows = [[('' if c is None else str(c)).strip() for c in r] for r in rows] | |
| rows = [r for r in rows if any(r)] | |
| if not rows: | |
| return [] | |
| hdr = rows[0] | |
| has_hdr = len([h for h in hdr if h]) >= 2 and all(not re.fullmatch(r'[\d.,\u00a3$\-/ ]+', h) for h in hdr if h) | |
| out = [] | |
| for i, r in enumerate(rows): | |
| if has_hdr and not i: | |
| continue | |
| if has_hdr: | |
| out.append('; '.join(f'{h or "col" + str(j + 1)}: {v}' for j, (h, v) in enumerate(zip(hdr + [''] * len(r), r)) if v)) | |
| else: | |
| out.append(' | '.join(v for v in r if v)) | |
| return out | |
| def _sheet(path, ext, meta): | |
| pages = [] | |
| if ext == '.csv': | |
| txt = open(path, encoding='utf-8-sig', errors='replace').read() | |
| try: | |
| dia = csv.Sniffer().sniff(txt[:4096]) | |
| except Exception: | |
| dia = csv.excel | |
| pages.append(('csv', '\n\n'.join(_rows(list(csv.reader(io.StringIO(txt), dia)))))) | |
| else: | |
| import openpyxl | |
| wb = openpyxl.load_workbook(path, read_only=True, data_only=True) | |
| for ws in wb.worksheets: | |
| pages.append((ws.title, '\n\n'.join(_rows(list(ws.iter_rows(values_only=True)))))) | |
| meta['extractor'] = 'spreadsheet (one paragraph per row, labelled with the column headings)' | |
| paras = [] | |
| for _, t in pages: | |
| paras += [p for p in t.split('\n\n') if p.strip()] | |
| return paras, pages | |
| def _rtf(path, meta): | |
| from striprtf.striprtf import rtf_to_text | |
| t = rtf_to_text(open(path, encoding='latin-1', errors='replace').read()) | |
| meta['extractor'] = 'rtf' | |
| return stitch.extract_text(t), [('p1', t)] | |
| def _odt(path, meta): | |
| import zipfile, html as _h | |
| with zipfile.ZipFile(path) as z: | |
| xml = z.read('content.xml').decode('utf-8', 'replace') | |
| xml = re.sub(r'<text:(p|h)[^>]*>', '\n\n', xml) | |
| xml = re.sub(r'<text:line-break/>', '\n', xml) | |
| t = _h.unescape(re.sub(r'<[^>]+>', '', xml)) | |
| meta['extractor'] = 'odt' | |
| return stitch.extract_text(t), [('p1', t)] | |
| # ---------------------------------------------------------------- public | |
| def load(path, name=None): | |
| """-> list of docs (an email with attachments gives several). Each doc: | |
| {name, paras, pages:[(label, text)], sha256, size, kind, extractor, warnings}""" | |
| name = name or os.path.basename(path) | |
| data = open(path, 'rb').read() | |
| h = hashlib.sha256(data).hexdigest() | |
| if h in _CACHE: | |
| return [dict(d, name=name if i == 0 else d['name']) for i, d in enumerate(_CACHE[h])] | |
| ext = os.path.splitext(name.lower())[1] | |
| meta, atts = {}, [] | |
| if ext == '.pdf': | |
| paras, pages = _pdf(path, meta) | |
| elif ext == '.docx': | |
| paras = stitch.extract(path); pages = [] | |
| meta['extractor'] = 'Word .docx (page numbers are not stored in .docx, so paragraph numbers are used)' | |
| elif ext in ('.doc', '.msg'): | |
| raise RuntimeError(f'{ext} is an old Outlook/Word format - save it as .docx, .eml or PDF') | |
| elif ext == '.eml': | |
| paras, pages, atts = _eml(path, meta) | |
| elif ext in ('.html', '.htm'): | |
| t = _html_to_text(open(path, encoding='utf-8', errors='replace').read()) | |
| paras, pages = stitch.extract_text(t), [('p1', t)]; meta['extractor'] = 'web page (html)' | |
| elif ext == '.rtf': | |
| paras, pages = _rtf(path, meta) | |
| elif ext == '.odt': | |
| paras, pages = _odt(path, meta) | |
| elif ext in ('.csv', '.xlsx', '.xlsm'): | |
| paras, pages = _sheet(path, ext, meta) | |
| elif ext in IMAGE_EXT: | |
| paras, pages = _image(path, meta) | |
| elif ext in AUDIO_EXT or ext in VIDEO_EXT: | |
| paras, pages = _media(path, meta) | |
| else: | |
| paras = stitch.extract(path); pages = [] | |
| meta['extractor'] = 'text' | |
| kind = 'audio' if meta.get('audio') else 'ocr' if meta.get('ocr') else 'text' | |
| docs = [{'name': name, 'paras': paras, 'pages': pages, 'sha256': h, 'size': len(data), 'kind': kind, | |
| 'extractor': meta.get('extractor', ''), 'warnings': meta.get('warnings', [])}] | |
| for a in atts: | |
| try: | |
| for d in load(a, f'{name} > {os.path.basename(a)}'): | |
| docs.append(d) | |
| except Exception as e: # noqa | |
| docs[0]['warnings'].append(f'attachment {os.path.basename(a)} could not be read ({e})') | |
| _CACHE[h] = docs | |
| if len(_CACHE) > 64: | |
| _CACHE.pop(next(iter(_CACHE))) | |
| return docs | |
| def google_export_url(link): | |
| link = (link or '').strip() | |
| for pat, url, fn in [(r'docs\.google\.com/document/d/([\w-]+)', 'https://docs.google.com/document/d/{}/export?format=docx', 'gdoc-{}.docx'), | |
| (r'docs\.google\.com/spreadsheets/d/([\w-]+)', 'https://docs.google.com/spreadsheets/d/{}/export?format=xlsx', 'gsheet-{}.xlsx'), | |
| (r'docs\.google\.com/presentation/d/([\w-]+)', 'https://docs.google.com/presentation/d/{}/export/pdf', 'gslides-{}.pdf')]: | |
| m = re.search(pat, link) | |
| if m: | |
| return url.format(m[1]), fn.format(m[1][:10]) | |
| m = re.search(r'drive\.google\.com/(?:file/d/|open\?id=|uc\?(?:export=download&)?id=)([\w-]+)', link) | |
| if m: | |
| return f'https://drive.google.com/uc?export=download&id={m[1]}', None | |
| return None | |
| def fetch_link(link): | |
| """Download a shared Google Docs/Drive (or any public) link to a temp file -> path.""" | |
| import requests | |
| g = google_export_url(link) | |
| url, fname = g if g else (link.strip(), None) | |
| r = requests.get(url, timeout=60, allow_redirects=True, headers={'User-Agent': 'seamstresses/1.0'}) | |
| r.raise_for_status() | |
| ctype = r.headers.get('content-type', '') | |
| if 'accounts.google.com' in r.url or (g and 'text/html' in ctype and b'ServiceLogin' in r.content[:20000]): | |
| raise RuntimeError('Google asked for a sign-in: share it as "Anyone with the link" or download and upload it') | |
| if not fname: | |
| m = re.search(r'filename\*?=(?:UTF-8\'\')?"?([^";]+)', r.headers.get('content-disposition', '')) | |
| fname = m[1] if m else None | |
| if not fname: | |
| ext = {'application/pdf': '.pdf', 'text/html': '.html', 'text/plain': '.txt', | |
| 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx'}.get(ctype.split(';')[0], '.txt') | |
| fname = re.sub(r'[^\w.-]', '_', url.split('/')[-1].split('?')[0] or 'link')[:60] + ext | |
| d = tempfile.mkdtemp(); p = os.path.join(d, os.path.basename(fname)) | |
| open(p, 'wb').write(r.content) | |
| return p | |