All files / app/mods/tools markitdown.ts

100% Statements 4/4
100% Branches 0/0
100% Functions 0/0
100% Lines 4/4

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318117x       117x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         117x                                           117x            
import { DateTime } from 'luxon';
import { Plugin } from '../../model/plugin';
import { Mod } from '../../model/tag';
 
export const markitdownPlugin: Plugin = {
  tag: 'plugin/delta/md',
  name: $localize`⬇️ MarkItDown Query`,
  config: {
    mod: $localize`⬇️ MarkItDown`,
    version: 1,
    type: 'tool',
    default: false,
    add: true,
    generated: $localize`Generated by jasper-ui ${DateTime.now().toISO()}`,
    description: $localize`Convert documents to Markdown using Microsoft MarkItDown.
Supports PDF, Word, Excel, PowerPoint, images (with OCR), audio (transcription), HTML, and more.
Creates one response per supported format found.`,
    aiInstructions: `# plugin/delta/md
The MarkItDown plugin converts various file formats to Markdown text.
It uses the Microsoft markitdown Python library to process documents.
 
Supported formats (detected by plugin tags):
- plugin/pdf: PDF files
- plugin/image: Images (extracts text via OCR)
- plugin/audio: Audio files (transcribes to text)
- plugin/video: Video files (extracts audio and transcribes)
- plugin/file: Generic files (Word, Excel, PowerPoint, HTML, etc.)
 
The plugin creates one response Ref per supported format found on the source Ref.
Each response contains the converted Markdown in its comment field.
Resources are fetched through the Jasper proxy API.`,
    icons: [{ label: $localize`⬇️💭️`, order: -1 }],
    filters: [
      { query: 'plugin/delta/md', label: $localize`⬇️💭️ markdown query`, title: $localize`Convert to Markdown`, group: $localize`Notifications ✉️` },
    ],
    actions: [
      { tag: 'plugin/delta/md', labelOn: $localize`cancel`, title: $localize`Cancel MarkItDown conversion.` },
    ],
    advancedActions: [
      { tag: 'plugin/delta/md', labelOff: $localize`markdown`, title: $localize`Convert document to Markdown using MarkItDown`, global: true },
    ],
    timeoutMs: 600_000,
    requirements: `
      markitdown[all]
      pytesseract
      requests
    `,
    language: 'python',
    // language=python
    script: `
import json
import os
import sys
import tempfile
import uuid
import shutil
import requests
from markitdown import MarkItDown, StreamInfo
 
ref = json.load(sys.stdin)
origin = ref.get('origin', '')
tags = ref.get('tags', [])
 
# Helper function to check for tags
def has_tag(tag, tags):
    return tag in tags or any(t.startswith(tag + '/') for t in tags)
 
# Collect debug logs if +plugin/debug tag is present
debug_logs = []
debug_mode = has_tag('+plugin/debug', tags)
 
def log_debug(message):
    if debug_mode:
        debug_logs.append(message)
 
# Supported format plugins and their default file extensions
SUPPORTED_FORMATS = {
    'plugin/pdf': '.pdf',
    'plugin/image': '',  # Extension determined by URL or content-type
    'plugin/audio': '',  # Extension determined by URL or content-type
    'plugin/video': '',  # Extension determined by URL or content-type
    'plugin/file': '',   # Extension determined by URL or content-type
}
 
def get_extension_from_url(url):
    """Extract file extension from URL."""
    url_path = url.split('?')[0]
    if '.' in url_path.split('/')[-1]:
        return '.' + url_path.rsplit('.', 1)[-1].lower()
    return ''
 
def fetch_resource(url, resource_origin, ext=''):
    """Fetch resource through the Jasper proxy API using streaming to avoid memory issues."""
    # Normalize extension to ensure it starts with a dot
    if ext and not ext.startswith('.'):
        ext = '.' + ext
 
    proxy_url = f"{os.environ['JASPER_API']}/api/v1/proxy"
 
    # Use context manager to ensure response is properly closed
    with requests.get(
        proxy_url,
        headers={
            'Local-Origin': origin or 'default',
            'User-Role': 'ROLE_ADMIN',
        },
        params={
            'url': url,
            'origin': resource_origin or '',
        },
        timeout=120,
        stream=True  # Enable streaming to avoid loading entire file into memory
    ) as response:
        response.raise_for_status()
 
        # Stream download to temporary file in chunks
        temp_file = None
        try:
            temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=ext if ext else '')
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:  # Filter out keep-alive chunks
                    temp_file.write(chunk)
            temp_file.flush()  # Ensure all buffered data is written to disk
            temp_file.close()
            return temp_file.name, response.headers.get('content-type', '')
        except Exception as e:
            # Clean up temp file if download fails
            log_debug(f"Error downloading resource from {url}: {e}")
            if temp_file:
                temp_file.close()
                if os.path.exists(temp_file.name):
                    os.remove(temp_file.name)
            raise
 
def convert_to_markdown(file_path, ext, content_type=''):
    """Convert file to markdown using MarkItDown."""
    # Extract mimetype from content-type (remove charset and other parameters)
    mimetype = None
    if content_type:
        mimetype = content_type.split(';')[0].strip()
        # Validate mimetype format
        if not mimetype or mimetype.count('/') != 1:
            mimetype = None
 
    # Create StreamInfo with mimetype and extension hints
    # MarkItDown uses these hints to identify the file format
    stream_info = None
    if mimetype or ext:
        stream_info = StreamInfo(
            mimetype=mimetype,
            extension=ext
        )
 
    log_debug(f"Converting file: {file_path}, ext: {ext}, mimetype: {mimetype}")
 
    try:
        md = MarkItDown()
        result = md.convert(file_path, stream_info=stream_info)
        log_debug(f"Conversion completed, text length: {len(result.text_content)}")
        return result.text_content
    finally:
        # Clean up the temporary file created by fetch_resource
        if os.path.exists(file_path):
            os.remove(file_path)
 
# Find all supported formats in the ref
formats_to_convert = []
 
for plugin_tag, default_ext in SUPPORTED_FORMATS.items():
    if has_tag(plugin_tag, tags):
        plugin_data = ref.get('plugins', {}).get(plugin_tag, {})
        url = plugin_data.get('url') if isinstance(plugin_data, dict) else None
        if not url:
            url = ref.get('url', '')
        if url:
            ext = default_ext or get_extension_from_url(url)
            formats_to_convert.append({
                'plugin': plugin_tag,
                'url': url,
                'ext': ext,
            })
 
# If no supported format tags found, check if ref URL has an extension
if not formats_to_convert:
    url = ref.get('url', '')
    if url:
        ext = get_extension_from_url(url)
        # Allow MarkItDown to attempt conversion of any file with an extension
        # Error handling in the conversion loop will catch unsupported formats
        if ext:
            formats_to_convert.append({
                'plugin': 'url',
                'url': url,
                'ext': ext,
            })
 
if not formats_to_convert:
    log_debug("No supported formats found to convert")
    sys.exit(0)
 
bundle = {'ref': []}
 
for fmt in formats_to_convert:
    try:
        url = fmt['url']
        ext = fmt['ext']
        plugin = fmt['plugin']
 
        # Fetch the resource through proxy with streaming
        file_path, content_type = fetch_resource(url, ref.get('origin', ''), ext)
 
        # Convert to markdown
        markdown_content = convert_to_markdown(file_path, ext, content_type)
 
        if not markdown_content or not markdown_content.strip():
            log_debug(f"Warning: No content extracted from {plugin}")
            markdown_content = f"(No text content could be extracted from {plugin})"
 
        # Create response ref with propagated tags (similar to dalle.ts pattern)
        response_ref_tags = ['+plugin/delta/md']
 
        # Propagate visibility/context tags from source ref
        if 'public' in tags:
            response_ref_tags.append('public')
        if 'internal' in tags:
            response_ref_tags.append('internal')
        if 'dm' in tags:
            response_ref_tags.extend(['dm', 'internal', 'plugin/thread'])
        if 'plugin/comment' in tags:
            response_ref_tags.extend(['plugin/comment', 'internal'])
        if 'plugin/thread' in tags:
            response_ref_tags.extend(['plugin/thread', 'internal'])
 
        # Propagate user tags (+user, _user, +user/*, _user/*)
        user_tags = [t[1:] for t in tags if t in ('+user', '_user') or t.startswith('+user/') or t.startswith('_user/')]
 
        # Propagate mailbox tags and create inbox tags for users
        mailbox_tags = [t for t in tags if t.startswith('plugin/inbox') or t.startswith('plugin/outbox')]
        response_ref_tags.extend(mailbox_tags)
        # Create inbox tags by removing the leading + or _ from user tags
        response_ref_tags.extend(['plugin/inbox/' + t for t in user_tags])
        if 'public' not in tags:
            response_ref_tags.extend(user_tags)
            response_ref_tags.extend([t for t in tags if t.startswith('user/')])
 
        # Remove duplicates while preserving order
        seen = set()
        unique_tags = []
        for t in response_ref_tags:
            if t not in seen:
                seen.add(t)
                unique_tags.append(t)
        response_ref_tags = unique_tags
 
        response_ref = {
            'origin': origin,
            'url': 'internal:' + str(uuid.uuid4()),
            'title': f"Markdown: {ref.get('title', 'Untitled')} ({plugin})",
            'comment': markdown_content,
            'tags': response_ref_tags,
            'sources': [ref.get('url')],
        }
 
        bundle['ref'].append(response_ref)
 
    except requests.exceptions.RequestException as e:
        log_debug(f"Error fetching {fmt['plugin']}: {e}")
    except Exception as e:
        log_debug(f"Error converting {fmt['plugin']}: {e}")
 
# Add debug log ref if +plugin/debug tag is present
if debug_mode and debug_logs:
    bundle['ref'].append({
        'url': 'log:' + str(uuid.uuid4()),
        'sources': [ref.get('url')],
        'title': 'MarkItDown Debug Logs',
        'comment': '\\n'.join(debug_logs),
        'tags': ['internal', '+plugin/log'],
    })
 
if bundle['ref']:
    print(json.dumps(bundle))
else:
    log_debug("No content could be converted")
    sys.exit(1)
    `,
  },
};
 
export const markitdownSignaturePlugin: Plugin = {
  tag: '+plugin/delta/md',
  name: $localize`⬇️ MarkItDown Result`,
  config: {
    mod: $localize`⬇️ MarkItDown`,
    version: 1,
    type: 'tool',
    default: false,
    generated: $localize`Generated by jasper-ui ${DateTime.now().toISO()}`,
    description: $localize`Signature tag for documents converted to Markdown using Microsoft MarkItDown.
Each response contains the converted Markdown from a specific source format.`,
    icons: [{ label: $localize`⬇️`, order: 1 }],
    filters: [
      { query: '+plugin/delta/md', label: $localize`⬇️ markdown`, title: $localize`Converted to Markdown`, group: $localize`Delta Δ` },
    ],
    advancedActions: [
      { tag: '+plugin/delta/md', labelOn: $localize`reconvert`, title: $localize`Reconvert document to Markdown` },
      { tag: 'plugin/alias/plugin/delta/md', labelOff: $localize`reconvert`, title: $localize`Reconvert document to Markdown` },
    ],
  },
};
 
export const markitdownMod: Mod = {
  plugin: [
    markitdownPlugin,
    markitdownSignaturePlugin,
  ],
};