🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: news.software.readers
Article #42777

Re: Scoring with S-Lang function (Was: Re: Why reinvent slrn? (was: Re: [slrn] Preventing an S-Lang macro from aborting.))

#42777
From: Lloyd Zusman
Date: Tue, 18 Aug 1998 00:00
813 lines
22285 bytes
I'm sorry, but I posted a buggy version of "scorgen" earlier tonight.

The one I'm posting here has been fixed.  It seems to work OK under
slrn 0.9.5.2.

 Lloyd Zusman
 l...@asfast.com

--------------------------- "scoregen" script ---------------------------

#!/usr/bin/perl
# -*- perl -*-

# This routine generates some S-Lang routines which do the same thing
# as specified in an Slrn score file.
#
# This routine must be run under Perl version 5.000 or later.
#
# Here's how to invoke it:
#
#    scoregen [ Slrn-score-file [ S-Lang-output-file ] ]
#
# If  S-Lang-output-file  is missing, output goes to STDOUT.
# If  Slrn-score-file     is missing, input comes from STDIN.
#
#
# Version  0.05 -- August 18, 1998, Lloyd Zusman <l...@asfast.com>
#    Fixed "opposite sense" bug in Lines comparison.
#    Replaced final argument of extract_element() with an integer.
#    Default to case insensitivity in string matches.
#
# Version  0.04 -- August 12, 1998, Lloyd Zusman <l...@asfast.com>
#    Fixed a bug in handling tabs in the input file.
#    Now works properly when specified groups have no scoring rules.
#
# Version  0.03 -- October 19, 1997, Lloyd Zusman <l...@asfast.com>
#    Changed format of these revision comments.
#    Got rid of string_match_nocase(); now using \\C in pattern_match().
#    Added call to do_scoring() governed by doScoring variable.
#    Propagate comments from score file into generated code.
#
# Version  0.02 -- October 17, 1997, Lloyd Zusman <l...@asfast.com>
#    Fixed bug in keyword matching.
#    Treats initial missing newsgroups as all newsgroups.
#    Put andelse/orelse processing in newsgroup matches.
#
# Version  0.01 -- October 17, 1997, Lloyd Zusman <l...@asfast.com>
#    Initial version.


# This sets '$program' to the base name of argv0.

($program = $0) =~ s|^.*/||;


# Get the command-line arguments and process them.

$infile  = shift(@ARGV);
$outfile = shift(@ARGV);

unless (defined($infile)) {
  
  $inName  = 'STDIN';
  $outName = '';
  $originalScoreFile = "that was piped in via $inName";
  
  open(IN,  "<&STDIN");
  open(OUT, ">&STDOUT");
}
else {
  unless (open(IN, "<$infile")) {
    die "$program: unable to open input file: $infile\n";
  }
  
  $inName = $infile;
  $originalScoreFile = "'$inName'";
  
  if (defined($outfile)) {
    unless (open(OUT, ">$outfile")) {
      close(IN);
      die "$program: unable to open output file: $outfile\n";
    }
    $outName = $outfile;
  }
  else {
    open(OUT, ">&STDOUT");
    undef($finalMessage);
    $outName = '';
  }
}

# Read all the input into the @inputLines array (change this to
# one-line-at-a-time-processing if you're short on virtual memory
# and are processing a very large score file).

@inputLines = <IN>;

close(IN);

# Initialize some variables.

undef($currentGroups);
undef(@currentGroupList);
undef($inGroup);
undef($currentScore);
undef($currentExpires);
undef(@currentComments);
undef(@groupComments);
undef(@expiresComments);
undef(@scoreComments);
undef($out);
undef($orType);
undef(@headerInfo);
undef(%headerVar);

# Process the input.

$allGroupsFlag = '][';   # special code for all groups
$currentGroups = $allGroupsFlag;
@currentGroupList = ( $currentGroups );

foreach $inLine (@inputLines) {

   ($line = $inLine) =~ s|\s+$||;

   # Skip comment lines as per (almost) the same rule in score.c.
   # I say "almost" because I don't trash tabs.

   if ($line =~ m|^\s*[%#\000-\010\012-\037]|) {
       push(@currentComments, $line);
       next;
   }

   # A newsgroup line?

   if ($line =~ m|^\s*\[(\s*~)?\s*([^\[\]]*)\]\s*$|) {

      # We found a [ group ... ] line.

      $negation = $1;
      $groups = $2;

      @groupComments = @currentComments;
      undef(@currentComments);

      scoreProcessing();

      ($currentGroups = $groups) =~ s|\s||g;
      @currentGroupList = split(/,/, $currentGroups);

      # Start processing this new set of group information.

      undef($currentScore);
      undef($currentExpires);
      undef($orType);
      undef(@headerInfo);
   }
   else {

      # We found a potential score set.

      if ($line =~ m|^(.+?):(:)?([^:].*)$|) {

         $item = $1;
         $extraColon = $2;
         $value = $3;

         $item =~ s|\s||g;
         $value =~ s|^\s*(.*$)\s*$|$1|;
         
         if ($item =~ m|^score$|i) {

            # This is a Score: or a Score:: line

            scoreProcessing();

            undef($currentExpires);
            undef(@headerInfo);

            $orType = ($extraColon eq ':');
            $currentScore = $value;

            @scoreComments = @currentComments;
            undef(@currentComments);
         }
         elsif ($item =~ m|^expires$|i) {

            # This is an Expires: line

            $currentExpires = $value;

            @expiresComments = @currentComments;
            undef(@currentComments);
         }
         else {

            # This is a header matching line.

            if ($item =~ m|^(~)(.*)$|) {
               $separator = $1;
               $itemToken = $2;
            }
            else {
               $separator = ':';   # use ':' as a flag when no negation
               $itemToken = $item;
            }

            # Store the header info.

            my $itemToken = ucfirst(lc($itemToken));

            my $commentString = join("\n", @currentComments);
            undef(@currentComments);

            my $headerStuff = 
               "\001$commentString\001$itemToken$separator$value";
            push(@headerInfo, $headerStuff);

            $headerVar{$itemToken} = $itemToken;
         }
      }
   }
}

# We've processed all the lines from the original score file.  Now,
# process the final score set and finish processing the final group
# information.

scoreProcessing();

if ($inGroup) {
   endGroupProcessing();
}

# The '$out' variable now contains the generated S-Lang logic.  Write
# it out after some initialization stuff, and then finish off with
# some termination code.

print OUT initialization();

print OUT $out;

print OUT termination();

close(OUT);

# OK.  We're done.

if ($outName ne '') {
   print "Success: $inName -> $outName\n";
}

exit(0);

# This routine outputs the stuff that goes at the head of the set
# of generated S-Lang routines.

sub initialization {

   my $key = '';
   my $result = '';
   my $first = "\n";
   my $now = dateTime();

   $result .= <<EOD;
% -*- mode: slang; mode: fold -*-
%
% Automatically generated on $now.
%
% This file consists of S-Lang code that was generated from
% the Slrn score file $originalScoreFile.
%
% The original score file contents now appear at the bottom
% of this generated file, commented out.
%
% Routines:  convenience functions -- See below.
%            score_article()       -- Scores each individual article.
%                                     Called repeatedly by do_scoring().
%            do_scoring()          -- Scores all your articles.


EOD

   # This retrieves the convenience functions which are defined after
   # the __END__ line, below.

   $result .= join('', <DATA>);

   $result .= <<EOD;


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%    This routine was generated from the original score file.   %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% This routine is meant to be called once for each article, and
% it does the actual scoring.  This is the routine that was
% generated from your original score file, and it's what you
% should be modifying if you want to alter your scoring algorithm.

define score_article ( newsgroup, today )
{
   % Note that this routine makes use of 'andelse', 'orelse',
   % and other constructs that might be confusing if you aren't
   % familiar with S-Lang.  I did this for two reasons: (1) to
   % ensure that this routine runs as efficiently as possible,
   % and (2) to make it comparatively easy for me to write the
   % Perl program which automatically generates this code.
   %
   % Feel free to replace these constructs with those of your
   % choosing when you begin to manually alter the scoring
   % algorithms that have been generated for you in this routine.

   variable score            = get_header_score();
   variable originalScore    = score;
EOD

   foreach $key (sort keys %headerVar) {

      my $firstPart = sprintf("$first   variable header%-10s", $key);

      if ($key =~ m|^lines$|i) {
         $result .= "$firstPart = " .
                    "integer( extract_article_header( \"$key\" ) );\n";
      }
      else {
         $result .= "$firstPart = " .
                    "extract_article_header( \"$key\" );\n";
      }

      $first = '';
   }

   unless ($first) {
      $result .= "\n";
   }

   return ($result);
}


# This routine outputs the stuff that needs to be written after
# all the S-Lang code has been generated.

sub termination {

   my $result = '';
   my $comment;

   if (scalar(@currentComments) > 0) {
      foreach $comment (@currentComments) {
         $comment =~ s|^[^%#\000-\010\012-\037]+||;
         $result .= "   $comment\n";
      }
      $result .= "\n";
      undef(@currentComments);
   }

   $result .= "   if ( score != originalScore )\n";
   $result .= "   {\n";
   $result .= "      set_header_score( score );\n";
   $result .= "   }\n";
   $result .= "}\n";

   $result .= <<EOD;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%                  End of generated routine.                    %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%             Routine for invoking score_article().             %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Either ...
%
% (1) ... invoke this routine from within article_mode_hook, or
% (2) ... insert this routine's logic into article_mode_hook, or
% (3) ... rename this routine as 'article_mode_hook'.

% define article_mode_hook ()
define do_scoring ()
{
   call( "header_bob" );
   uncollapse_threads();

   % Initialize these variables here and repeatedly pass them into
   % score_article().  This ensures that current_newsgroup() and
   % get_today() will each be called only once per newsgroup.

   variable newsgroup = current_newsgroup();
   variable today     = get_today();

   do
   {
      score_article( newsgroup, today );

   } while ( header_down( 1 ) );

   collapse_threads();
   call( "header_bob" );
}

% If 'doScoring' is set as a global variable, automatically invoke
% the do_scoring() routine.  This allows you to conditionally use
% evalfile() on this generated score file to do your scoring.

if (doScoring) {
   do_scoring();
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%          End of routine for invoking score_article().         %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%          Original contents of score file begin here.          %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
EOD

   foreach $line (@inputLines) {
      $result .= "%%  $line";
   }

   $result .= <<EOD;
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%            End of original contents of score file.            %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
EOD

   return ($result);
}


# This routine begins the processing of a new group line.

sub startGroupProcessing {

   if ($inGroup) {
      endGroupProcessing();
   }
   
   if ($currentGroups =~ m|^\s*$|) {
      return;
   }

   my $negation = shift;
   my $if = 'if';
   my $group;
   my $operator;
   my $separator;
   my $comment;

   if (scalar(@groupComments) > 0) {
      foreach $comment (@groupComments) {
         $comment =~ s|^[^%#\000-\010\012-\037]+||;
         $out .= "   $comment\n";
      }
      undef(@groupComments);
   }

   $out .= "\n   ";

   if ($negation) {
      $out .= '!';
   }

   $out .= 'if ( ';

   if ($currentGroups eq $allGroupsFlag) {

      $out .= "1";
      $comment = ' % special case for all newsgroups';
   }
   else {

      $out .= "orelse";

      foreach $group (@currentGroupList) {
         $out .= "\n      { pattern_match( newsgroup, \"$group\" ) }";
      }

      $comment = '';
   }

   $out .= " )$comment\n";

   $out .= "   {\n";
   $out .= "      % The following 'loop' construct makes it easier to\n";
   $out .= "      % automatically generate the code for managing the\n";
   $out .= "      % \"Expires:\" tag and for handling the case for\n";
   $out .= "      % score = 9999 and -9999.  Feel free to modify this\n";
   $out .= "      % somewhat awkward syntax.\n\n";
   $out .= "      loop ( 1 )\n";
   $out .= "      {";

   $inGroup = 1;
   undef($currentGroups);
   undef(@currentGroupList);
}


# This routine ends the processing of group information.

sub endGroupProcessing {

   $out .= "\n         break;\n";
   $out .= "      }\n";
   $out .= "   }\n\n";

   undef($inGroup);
}


# This routine generates all the scoring logic.

sub scoreProcessing {

   unless ($currentGroups =~ m|^\s*$|) {
      startGroupProcessing();
   }

   my ($first, $key, $thing, $value, $sep, $op, $neg, $boolean,
       $comment);

   $first = "\n";

   unless ($currentExpires =~ m|^\s*$|) {

      if (scalar(@expiresComments) > 0) {
         my $comment;
         foreach $comment (@expiresComments) {
            $comment =~ s|^[^%#\000-\010\012-\037]+||;
            $out .= "$first         $comment\n";
            $first = '';
         }
         undef(@expiresComments);
      }

      $out .= "$first         if ( today >= date_value( \"$currentExpires\" ) )\n";
      $out .= "         {\n";
      $out .= "            break;\n";
      $out .= "         }\n";
   }

   if ($currentScore =~ m|^\s*$|) {
      return;
   }

   if (scalar(@scoreComments) > 0) {
      foreach $comment (@scoreComments) {
         $comment =~ s|^[^%#\000-\010\012-\037]+||;
         $out .= "\n         $comment";
      }
      undef(@scoreComments);
   }

   if (scalar(@headerInfo) < 1) {
      $sep = "\n";
   }
   else {

      $sep = '   ';

      if ($orType) {
         $boolean = 'orelse';
      }
      else {
         $boolean = 'andelse';
      }

      $out .= "\n         if ( $boolean";

      foreach $thing (@headerInfo) {

         unless ($thing =~ m#^\001(.*?)\001(.*?)([~:])(.*)$#s) {
            next;
         }

         $comment = $1;
         $key = $2;
         $neg = $3;
         $value = $4;

         unless ($comment =~ m|^\s*$|) {
            my $c;
            foreach $c (split(/\n/, $comment)) {
               $c =~ s|^[^%#\000-\010\012-\037]+||;
               $out .= "\n            $c";
            }
         }

         if ($neg eq '~') {
            $op = '<';
            $neg = ' not (';
            $end = ') ';
         }
         else {
            $op = '>=';
            $neg = '';
            $end = '';
         }

         $out .= "\n            {";

         if ($key =~ m|^lines$|i) {
            $out .= " ( header$key $op $value ) }";
         }
         else {
            $value =~ s|\\|\\\\|g;
	    if ($value =~ m/^\^(.*)$/) {
	      $value = "^\\\\C$1";
	    }
	    else {
	      $value = "\\\\C$value";
	    }
            $out .= "$neg string_match( header$key, \"$value\", 1 ) $end}";
         }
      }

      $out .= " )\n         {\n";
   }

   $currentScore =~ m|^\s*(=)?\s*(\S.*)\s*?$|;
   my $operator = $1;
   my $score = $2;

   $score =~ s|[\+\s]||g;

   if ($score <= -9999 || $score >= 9999) {
      $out .= "$sep         score = $score;\n";
      $out .= "$sep         break;\n";
   }
   else {
      if ($operator eq '') {

         if ($score < 0) {
            $score = -$score;
            $operator = '-=';
         }
         else {
            $operator = '+=';
         }
      }

      $out .= "$sep         score $operator $score;\n";
   }

   unless ($sep =~ m|^\n|) {
      $out .= "         }\n";
   }
}

sub dateTime {
   my ($now) = shift;
   $now += 0;
   if ($now < 1) {
      $now = time();
   }
   my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($now);
   return (sprintf("%04d/%02d/%02d at %02d:%02d:%02d",
           $year + 1900, $mon + 1, $mday, $hour, $min, $sec));
}


# In Perl, everything after an __END__ line is ignored by the
# interpreter, and it's readable as data via the DATA file handle.
# I make use of this to store the S-Lang code for the convenience
# functions that I'm including with the code that gets generated.
# Look in the 'initialization' routine, above, to see how I access
# this information.

__END__

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%    These are the convenience functions that are used below.   %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% This function converts a newsgroup pattern into a proper regexp.
% It does this in the same manner as the slrn_fix_regexp()
% function in util.c.  Therefore, this routine is a good candidate
% for replacement by a new intrinsic.

define fix_regexp ( pattern )
{
   variable len = strlen( pattern );
   variable regexp = "^";
   variable i;

   for ( i = 0; i < len; i++ )
   {
      if ( pattern[i] == '.' )
      {
         regexp = strcat( regexp, "\\" );
      }
      else if ( pattern[i] == '*' )
      {
         regexp = strcat(regexp, ".");
      }

      regexp = strcat( regexp, substr( pattern, i + 1, 1 ) );
   }

   regexp = strcat( regexp, "$" );

   return ( regexp );
}

% Return today's date in a form usable in date comparisons.  The
% value returned is in the same form as that which is returned by
% the get_today() function in score.c, and therefore, this routine
% is another good candidate for replacement by a new intrinsic.

define get_today ()
{
   variable now = time();

   variable month = extract_element( now, 1, ' ' );
   variable day   = extract_element( now, 2, ' ' );
   variable year  = extract_element( now, 4, ' ' );

   if ( orelse
      { strlen( month ) < 1 }
      { strlen( day )   < 1 }
      { strlen( year )  < 1 } )
   {
      % Error!
      return ( -1 );
   }

   variable match =
      string_match( "JanFebMarAprMayJunJulAugSepOctNovDec", month, 1 );

   if ( match < 1 )
   {
      % Error!
      return (-1);
   }

   year  = integer( year );
   month = ( match - 1 ) / 3;
   day   = integer( day );

   return ( ( year * 10000 ) + ( month * 100 ) + day );
}

% Convert a date into an integer form that is useful for comparisons
% (but not useful for date arithmetic).  The value returned will be
% in the same form as that which is used by the get_today() and the
% has_score_expired() functions in score.c.

define date_value ( date )
{
   variable month = extract_element( date, 0, '/' );
   variable day   = extract_element( date, 1, '/' );
   variable year  = extract_element( date, 2, '/' );

   if ( orelse
      { strlen( month ) < 1 }
      { strlen( day )   < 1 }
      { strlen( year )  < 1 } )
   {
      month = extract_element( date, 0, '-' );
      day   = extract_element( date, 1, '-' );
      year  = extract_element( date, 2, '-' );

      if ( orelse
         { strlen( month ) < 1 }
         { strlen( day )   < 1 }
         { strlen( year )  < 1 } )
      {
         % Error!
         return ( -1 );
      }
   }

   year  = integer( year );
   month = integer( month );
   day   = integer( day );

   if ( orelse
      { year  < 1900 }
      { month < 1    }
      { month > 12   }
      { day   < 1    }
      { day   > 31   } )
   {
      % Error!
      return ( -1 );
   }

   return ( ( year * 10000 ) + ( ( month - 1 ) * 100 ) + day );
}

% This routine does a newsgroup pattern match.  It's used
% within score_article() to match newsgroups.  It also could
% be used there to do this same kind of pattern matching on
% the "Newsgroups:" line during scoring.

define pattern_match ( group, pattern )
{
   return ( string_match( group, fix_regexp( strcat( "\\C", pattern ) ), 1 ) );
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%                 End of convenience functions.                 %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Technical Details
Message-ID: <ltsoit7ltu.fsf@asfast.com>
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!illumos!news.pugleaf.net!.TX!i2pn2.pugleaf.net!archive.newsdeef.eu!mbox2nntp!not-for-mail
References: <lt7m09d7sr.fsf@asfast.com> <slrn6tcib1.gg3.bluemoon@ux6.cso.uiuc.edu> <slrn6tcjq7.ke5.ljz@sunspot.tiac.net> <slrn6td1jb.c8k.bluemoon@ux6.cso.uiuc.edu> <ltlnopatls.fsf@asfast.com> <slrn6teh0j.bl.bluemoon@ux6.cso.uiuc.edu> <lt3eawbhq2.fsf@asfast.com> <Aug-17-03.42.27-1998.obs@burnout.demon.co.uk> <slrn6tgukj.n8d.bluemoon@ux6.cso.uiuc.edu> <Aug-18-01.07.07-1998.obs@burnout.demon.co.uk> <slrn6ti0da.m7a.lahvak@math.mps.ohio-state.edu>

Show Full Headers
Complete Article Headers
Message-ID: <ltsoit7ltu.fsf@asfast.com>
Subject: Re: Scoring with S-Lang function (Was: Re: Why reinvent slrn? (was: Re: [slrn] Preventing an S-Lang macro from aborting.))
Date: Tue, 18 Aug 1998 00:00:00 +0000
From: Lloyd Zusman <l...@asfast.com>
References: <lt7m09d7sr.fsf@asfast.com> <slrn6tcib1.gg3.bluemoon@ux6.cso.uiuc.edu> <slrn6tcjq7.ke5.ljz@sunspot.tiac.net> <slrn6td1jb.c8k.bluemoon@ux6.cso.uiuc.edu> <ltlnopatls.fsf@asfast.com> <slrn6teh0j.bl.bluemoon@ux6.cso.uiuc.edu> <lt3eawbhq2.fsf@asfast.com> <Aug-17-03.42.27-1998.obs@burnout.demon.co.uk> <slrn6tgukj.n8d.bluemoon@ux6.cso.uiuc.edu> <Aug-18-01.07.07-1998.obs@burnout.demon.co.uk> <slrn6ti0da.m7a.lahvak@math.mps.ohio-state.edu>
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!illumos!news.pugleaf.net!.TX!i2pn2.pugleaf.net!archive.newsdeef.eu!mbox2nntp!not-for-mail
X-Deja-AN: 382498492
X-Complaints-To: news...@supernews.com
X-Trace: 903493323 NHG18.M.GE264CCFD usenet44.supernews.com
Organization: http://www.supernews.com, The World's Usenet: Discussions Start Here
Newsgroups: alt.lang.s-lang,news.software.readers