#
SWISH::Filter - Perl extension for filtering documents with Swish-e

[ TOC ]

# SYNOPSIS

      use SWISH::Filter;

      # load available filters into memory
      my $filter = SWISH::Filter->new;

      # convert a document

      my $doc = $filter->convert(
            document     => \$scalar_ref,  # path or ref to a doc
            content_type => $content_type, # content type if doc reference
            name         => $real_path,    # optional name for this file (useful for debugging)
            user_data    => $whatever,     # optional data to make available to filters
       );

      return unless $doc;  # empty doc, zero size, or no filters installed

      # Was the document converted by a filter?
      my $was_filtered = $doc->was_filtered;

      # Skip if the file is not text
      return if $doc->is_binary;

      # Print out the doc
      my $doc_ref = $doc->fetch_doc;
      print $$doc_ref;

      # Fetch the final content type of the document
      my $content_type = $doc->content_type;

      # Fetch swish-e parser type (TXT*, XML*, HTML*, or undefined)
      my $doc_type = $doc->swish_parser_type;

[ TOC ]

# DESCRIPTION

SWISH::Filter provides a unified way to convert documents into a type that swish-e can index. Individual filters are installed as separate perl modules. For example, there might be a filter that converts from PDF format to HTML format.

Note that this is just a framework for filtering documents. Additional helper programs or Perl module may need to be installed to use SWISH::Filter to filter documents. For example, to filter PDF documents you must install the Xpdf package.

The filters are automatically loaded when `SWISH::Filters->new()` is called. Filters define a type and priority that determines the processing order of the filter. Filters are processed in this sort order until a filter accepts the document for filtering. The filter uses the document's content type to determine if the filter should handle the current document.

The individual filters are not designed to be used as separate modules. All access to the filters is through this SWISH::Filter module.

Normally, once a document is filtered processing stops. Some filters can filter the document yet set a flag saying that filtering should continue (for example a filter that uncompresses a MS Word document before passing on to the filter that converts from MS Word to text). All this should be transparent to the end user.

The idea of SWISH::Filter is that new filters can be created, and then downloaded and installed to provide new filtering capabilities. For example, if you needed to index MS Excel documents you might be able to download a filter from the Swish-e site and magically next time you run indexing MS Excel docs would be indexed.

The SWISH::Filter setup can be used with -S prog or -S http. It works best with the -S prog method because the filter modules only need to be loaded and compiled one time. The -S prog program spider.pl will automatically use SWISH::Filter when spidering with default settings (using ``default'' as the first parameter to spider.pl).

The -S http indexing method uses a Perl helper script called swishspider. swishspider has been updated to work with SWISH::Filter, but (unlike spider.pl) does not contain a ``use lib'' line to point to the location of SWISH::Filter. This means that by default swishspider will not use SWISH::Filter for filtering. The reason for this is because swishspider runs for every URL fetched, and loading the Filters for each document can be slow. The recommended way of spidering is using -S prog with spider.pl, but if -S http is desired the way to enable SWISH::Filter is to set PERL5LIB before running swish so that swishspider will be able to locate the SWISH::Filter module. Here's one way to set the PERL5LIB with the bash shell:

      $ export PERL5LIB=`swish-filter-test -path`

[ TOC ]

# METHODS

$filter = SWISH::Filter->new()

  This creates a SWISH::Filter object. You may pass in options as a list or a hash reference.

[ TOC ]

## SWISH::Filter->new Options

There is currently only one option that can be passed in to `new():`

ignore_filters

  Pass in a reference to a list of filter names to ignore. For example, if you have two filters installed ``Pdf2HTML'' and ``Pdf2XML'' and want to avoid using ``Pdf2XML'':

          my $filter = SWISH::Filter->new( ignore_filters => ['Pdf2XML'];

$filtered = $filter->filter();

  Depreciated: Use the `convert()` method instead.

  See $swish->convert for options.

  Returns true if the document was converted.

$doc_object = $filter->convert();

  This method filters a document. Returns an object of the class SWISH::Filter::Document or undefined if passed in an empty document, a filename that cannot be read off disk, or if no filters have been loaded.

  Methods in SWISH below can be called on the object to, for example, check if the document was filtered and to fetch the document content (filtered or not).

  You must pass in a hash (or hash reference) of parameters to the `convert()` method. The possible parameters are:

  document

    This can be either a path to a file, or a scalar reference to a document in memory. This is required.

  content_type

    The MIME type of the document. This is only required when passing in a scalar reference to a document is passed. The content type string is what the filters use to match a document type.

    When passing in a file name and content_type is not set, then the content type will be determined from the file's extension by using the MIME::Types Perl module (available on CPAN).

  name

    Optional name to pass in to filters that will be used in error and warning messages.

  user_data

    Optional data structure that all filters may access. This can be fetched in a filter by:

            my $user_data = $doc_object->user_data;

    And used in the filter as:

            if ( ref $user_data && $user_data->{pdf2html}{title} ) {
               ...
            }

    It's up to the filter author to use a unique first-level hash key for a given filter.

  Example of using the `convert()` method:

          $doc_object = $filter->convert(
              document     => $doc_ref,
              content-type => 'application/pdf',
          );

$doc_ref = $filter->fetch_doc;

  Depreciated: Use $doc->fetch_doc instead.

  Returns a reference to a scalar that contains the document passed in. If the file is on disk it will be read from disk into memory.

  Depreciated example: (don't use)

          $filtered = $filter->filter( $doc_ref, 'application/pdf' );
          if ( $filtered ) {
              $doc_ref = $filter->fetch_doc;
              print $$doc_ref;
          }

$type = $filter->content_type

  Depreciated

  Returns the content type of the document after filtering. Use $doc->content_type instead.

$type = $filter->swish_parser_type

  Depreciated use $doc->swish_parser_type instead.

  Returns the swish parser type for the document, or undefined.

  For example, in a -S prog program you can set the parser that swish-e will use:

          if ( my $type = $filter->swish_parser_type ) {
              print "Document-Type: $type\n";
          }

$self->mywarn()

  Internal function used for writing warning messages to STDERR if $ENV{FILTER_DEBUG} is set. Set the environment variable FILTER_DEBUG before running to see the verbose warning messages.

$path = $self->find_binary( $prog );

  Use in a filter's `new()` method to test for a necesary program located in $PATH. Returns the path to the program or undefined if not found or does not pass the -x file test.

$bool = $self->use_modules( @module_list );

  Attempts to load each of the module listed and calls its `import()` method.

  Use to test and load required modules within a filter without aborting.

          return unless $self->use_modules( qw/ Spreadsheet::ParseExcel  HTML::Entities / );

  A warning message is displayed if the FILTER_DEBUG environment variable is true.

[ TOC ]

# SWISH::Filter::Document Methods

These methods are available to Filter authors, and also provide access to the document after calling the `convert()` method to end-users of SWISH::Filter.

End users of SWISH::Filter will use a subset of these methods. Mostly:

       $doc_object->fetch_doc      # and alias for fetch_document_reference()
       $doc_object->was_filtered   # true the document was filtered
       $doc_object->content_type   # document's current content type (mime type)
       $doc_object->swish_parser_type # returns a parser type to use with swish-e -S prog method
       $doc_object->is_binary      # returns $content_type !~ m[^text/];

These methods are also available to the individual filter modules. The filter's ``filter'' function is also passed a SWISH::Filter::Document object. Method calls may be made on this object to check the document's current content type, or to fetch the document as either a file name or a reference to a scalar containing the document content.

[ TOC ]

## Methods used by end-users and filter authors

$doc_ref = $doc_object->fetch_doc_reference;

  Returns a scalar reference to the document. This can be used when the filter can operate on the document in memory (or if an external program expects the input to be from standard input).

  If the file is currently on disk then it will be read into memory. If the file was stored in a temporary file on disk the file will be deleted once read into memory. The file will be read in binmode if $doc->is_binary is true.

  Note that $doc_object->fetch_doc is an alias.

$was_filtered = $doc_object->was_filtered

  Returns true if some filter processed the document

$content_type = $doc_object->content_type;

  Fetches the current content type for the document.

  Example:

          return unless $filter->content_type =~ m!application/pdf!;

$doc_object->is_binary

  Returns true if the document's content-type does not match ``text/''.

[ TOC ]

## Methods used by filter authors

$file_name = $doc_object->fetch_filename;

  Returns a path to the document as stored on disk. This name can be passed to external programs (e.g. catdoc) that expect input as a file name.

  If the document is currently in memory then a temporary file will be created. Do not expect the file name passed to be the real path of the document.

  The file will be written in binmode if $doc->is_binary is true.

  This method is not normally used by end-users of SWISH::Filter.

$doc_object->set_continue;

  Processing will continue to the next filter if this is set to a true value. This should be set for filters that change encodings or uncompress documents.

$doc_object->set_content_type( $type );

  Sets the content type for a document.

$doc_object->name

  Fetches the name of the current file. This is useful for printing out the name of the file in an error message. This is the name passed in to the SWISH::Filter->convert method. It is optional and thus may not always be set.

          my $name = $doc_object->name || 'Unknown name';
          warn "File '$name': failed to convert -- file may be corrupt\n";

$doc_object->user_data

  Fetches the the user_data passed in to the filter. This can be any data or data structure passed into SWISH::Filter->new.

  This is an easy way to pass special parameters into your filters.

  Example:

          my $data = $doc_object->user_data;
          # see if a choice for the <title> was passed in
          if ( ref $data eq 'HASH' && $data->{pdf2html}{title_field}  {
             ...
             ...
          }

$doc_ref = $filter->run_program( $program, @args );

  Runs `$program` with @args. Must pass in @args.

  Under Windows calls IPC::Open2, which may pass data through the shell. Double-quotes are escaped (backslashed) and each parameter is wrapped in double-quotes.

  On other platforms a fork and exec is used to avoid passing any data through the shell. Returns a reference to a scalar containing the output from your program, or dies.

  This method is intended to read output from a program that converts one format into text. The output is read back in text mode -- on systems like Windows this means \r\n (CRLF) will be convertet to \n.

[ TOC ]

# WRITING FILTERS

Filters are standard perl modules that are installed into the SWISH::Filters name space. Filters are not complicated -- see the existing filters for examples.

Filters are linked together in a chain, and have a type and priority that set the order of the filter in the chain. Filters check the content type of the document to see if they should process the document. If the filter processes the document it returns either a file name or a reference to a scalar. Normally a reference to a scalar of the converted document should be returned. If the filter does not process the document then it returns undef and the next filter in the chain has a chance to process the document.

If a filter calls die then the filter is removed from the chain and will not be called again during the same run. Calling die when running with -S http or -S fs has no effect since the program is run once per document.

Once a filter returns something other than undef no more filters will be called. If the filter calls $filter->set_continue then processing will continue as if the file was not filtered. For example, a filter can uncompress data and then set $filter->set_continue and let other filters process the document.

This is the list of methods the filter should or may define (as specificed):

new() * required *

  This method returns either an object which provides access to the filter, or undefined if the filter is not to be used.

  The `new()` method is a good place to check for required modules or helper programs. Returning undefined prevents the filter from being included in the filter chain.

filter() * required *

  This is the function that does the work of converting a document from one content type to another.

type()

  Returns a number from 1 to 10. Filters are sorted (for processing in a specific order) and this number is simply the primary key used in sorting. If not specified the filter's type used for sorting is 2.

priority()

  Returns a number from 1 to 10. Filters are sorted (for processing in a specific order) and this number is simply the primary key used in sorting. If not specified the filter's priority is 50.

Again, the point of the `type()` and `priority()` methods is to allow setting the sort order of the filters. Useful if you have two filters that for filtering similar content-types, but prefer to use one over the other.

Here's a module to index MS Word documents using the program ``catdoc'':

        package SWISH::Filters::Doc2txt;
        use vars qw/ @ISA $VERSION /;

        $VERSION = '0.01';
        @ISA = ('SWISH::Filter');

        sub new {
            my ( $pack, %params ) = @_;

            my $self = bless {
                name => $params{name} || $pack,
            }, $pack;

            # check for helpers
            for my $prog ( qw/ catdoc / ) {
                my $path = $self->find_binary( $prog );
                unless ( $path ) {
                    $self->mywarn("Can not use Filter $pack -- need to install $prog");
                    return;
                }
                $self->{$prog} = $path;
            }

            return $self;

        }

        sub filter {
        my ( $self, $document ) = @_;

            # Do we care about this document?
            return unless $document->content_type =~ m!application/msword!;

            # We need a file name to pass to the catdoc program
            my $file = $document->fetch_filename;

            # Grab output from running program
            my $content = $document->run_program( $self->{catdoc}, $file );

            return unless $content;

            # update the document's content type
            $document->set_content_type( 'text/plain' );

            # return the document
            return \$content;
        }
        1;

[ TOC ]

# TESTING

Filters can be tested with the swish-filter-test program. Run:

       swish-filter-test -man

for documentation.

[ TOC ]

# SUPPORT

Please contact the Swish-e discussion list. http://swish-e.org

[ TOC ]

# Bugs, todo items, and other notes

I wonder if the filters shouldn't just register the content types they handle instead of checking the content type. Would want to be able to register regular expressions.

[ TOC ]

# AUTHOR

Bill Moseley

[ TOC ]

# COPYRIGHT

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. [ TOC ]