Difference between revisions of "Import CSV data into a wiki"

From Organic Design wiki
(wikiPageAppend -->wikiAppend)
m (Installation)
 
(21 intermediate revisions by 2 users not shown)
Line 1: Line 1:
#!/usr/bin/perl
+
{{procedure}}
# {{perl}}{{Category:Robots}}{{lowercase}}
 
# - Licenced under LGPL (http://www.gnu.org/copyleft/lesser.html)
 
# - Authors:  [http://www.organicdesign.co.nz/Nad Nad] [http://www.organicdesign.co.nz/Sven Sven]
 
# - Source:  http://www.organicdesign.co.nz/scraper.pl
 
# - Started: 2008-03-21
 
# - API:    http://en.wikipedia.org/w/api.php
 
 
# Todo
 
# Make it so that if there is no title then it increments
 
# $hashref = { $wikitext =~ /\{{3}(.+?)(\|.*?)?\}{3}/g }
 
require('wiki.pl');
 
 
# Job, log and error files
 
$ARGV[0] or die "No job file specified!";
 
$ARGV[0] =~ /^(.+?)(\..+?)?$/;
 
  
# Set a debug conditional
+
[{{repo|tools|csv2wiki.pl}} csv2wiki.pl] is a simple perl script to import data from a CSV file into a MediaWiki.
$::debug = 0;
 
  
$::log = "$1.log";
+
== Installation ==
$::err = "$1.err";
+
The script depends on a Perl module called [{{repo|tools|MediaWiki.pm}} MediaWiki.pm] which needs to be saved in the same location, or in one of your Perl include paths.
$::sep = ',';
 
$::title = 0;
 
$::template = 'Record';
 
$::prefix = "";
 
$::append = 0;
 
 
# Parse the job file
 
if (open JOB,'<',$ARGV[0]) {
 
for (<JOB>) {
 
if (/^\*?\s*csv\s*:\s*(.+?)\s*$/i)        { $::csv = $1 }
 
if (/^\*?\s*wiki\s*:\s*(.+?)\s*$/i)        { $::wiki = $1 }
 
if (/^\*?\s*user\s*:\s*(.+?)\s*$/i)        { $::user = $1 }
 
if (/^\*?\s*pass\s*:\s*(.+?)\s*$/i)        { $::pass = $1 }
 
if (/^\*?\s*separator\s*:\s*"(.+?)"\s*$/i) { $::sep = $1 }
 
if (/^\*?\s*title\s*:\s*(.+?)\s*$/i)      { $::title = $1 }
 
if (/^\*?\s*template\s*:\s*(.+?)\s*$/i)    { $::template = $1 }
 
if (/^\*?\s*prefix\s*:\s*(.+?)\s*$/i)      { $::prefix = $1 }
 
if (/^\*?\s*append\s*:\s*(.+?)\s*$/i)      { $::append = $1 }
 
}
 
close JOB;
 
} else { die "Couldn't parse job file!" }
 
 
  
# Open CSV file and read in headings line
+
It also depends on ''LWP'' and ''XML::Simple''. If these dependencies are not present, Perl will raise an error specifying which one is not available and you can then install it with CPAN, e.g.
if (open CSV, '<', $::csv) {
+
<source lang="bash">
$_ = <CSV>;
+
cpan XML::Simple
/^\s*(.+?)\s*$/;
+
</source>
@headings = split /$::sep/i, $1;
 
} else { die "Could not open CSV file!" }
 
 
# Log in to the wiki
 
wikiLogin($::wiki,$::user,$::pass) or exit;
 
 
# fetch the template if it exists
 
$response = $client->get("$wiki?title=Template:$template&action=raw");
 
if ($response->is_success) {
 
$wikitext = $response->content;
 
  
# Remove noinclude areas
+
On Debian-like systems there are also packages for the dependencies:
$wikitext =~ s/<noinclude>.+?<\/noinclude>//gs;
+
<source lang="bash">
 +
apt install libwww-perl libxml-simple-perl
 +
</source>
  
# Find all unique {{{parameters}}}
+
== Usage ==
# http://en.wikipedia.org/wiki/Help:Templates#Parameters
+
The program is run from the shell and requires one parameter which is the filename of a configuration file describing the parameters for the job.
 +
<source lang="bash">
 +
./csv2wiki.pl /home/myJob.conf
 +
</source>
  
$params{$1} = undef while $wikitext =~ /\{{3}(.+?)(\|.*?)?\}{3}/g;
 
  
# Create %{param=index} hash
+
Here is an example the content of a configuration file:
foreach ($i = 0; $i <= $#headings; $i++) {
+
<source lang="js">
$params{$headings[$i]} = $i if exists $params{$headings[$i]};
+
wiki    = "http://foo.bar/wiki/index.php"
}
+
user    = "Foo"
 +
pass    = "Bar"
 +
csv      = "/home/foo/projects/bar.csv"
 +
title    = "$1 $2 $3"
 +
template = "Customer"
 +
</source>
  
if ($::debug) {
 
print "\@headings: @headings\n";
 
print "%params: @{[%params]}\n";
 
}
 
}
 
 
 
# Get batch size and current number (also later account for n-bots)
 
  
# todo: log batch start
+
Each line of the input CSV file will be imported into an article in the wiki, and the first line of the input file specifies the column header names, for example:
+
<source>
# Process the records
+
Title, Firstname, Surname
$n = 1;
+
Mr, Bob, McFoo
while (<CSV>) {
+
Miss, Mary, Barson
/^\s*(.+?)\s*$/;
+
</source>
@record = split /$::sep/, $1;
 
$tmpl  = "{{$template\n";
 
$tmpl .= "|$_ = $record[$params{$_}]\n" foreach keys %params;
 
$tmpl .= "}}";
 
print "Processing record ".$n++."\n";
 
if ($::debug) {
 
    print "\$tmpl = $tmpl\n";
 
    die  "[\$::debug set exiting]\n" ;
 
}
 
  
# Update the record
 
$text  = wikiRawPage($::wiki,$record[$::title],0);
 
$text .= "\n$tmpl" unless $text =~ s/\{\{$template.+?\}\}/$tmpl/is;
 
if ($append) {
 
$done = wikiAppend(
 
$::wiki,
 
$::prefix . $record[$::title],
 
$text,
 
"[[Template:$::template|$::template]] appended using csv2wiki.pl"
 
);
 
} else {
 
$done = wikiEdit(
 
$::wiki,
 
$::prefix . $record[$::title],
 
$text,
 
"[[Template:$::template|$::template]] replacement using csv2wiki.pl"
 
);
 
}
 
  
# log a row error if any
+
In this example the first row of data will be imported into an article called "Mr Bob McFoo" with the following content. The column header names are used as the template parameter names, with the values from that row of the CSV file being used as the values for the template parameters.
}
+
<source>
+
{{Customer
close CSV;
+
| Title = Mr
 +
| Firstname = Bob
 +
| Surname = McFoo
 +
}}
 +
</source>
 +
 
 +
 
 +
If the page already existed, then the new template would be inserted at the top of the page (or the bottom if "append" is set). Or if the template already exists in the page, then it's values will be updated.
 +
 
 +
'''Note''' that pages that already have templates on them must only use a single value on each line in their syntax.
 +
 
 +
== Configuration options ==
 +
Here is a description of the possible parameters in the job file and their meaning:
 +
{| class=od-info
 +
!Name!!Meaning!!Default value
 +
|-
 +
|csv||The source file to import relative to the location of the script||-
 +
|-
 +
|wiki||the full long-form URL of the wiki including index.php||-
 +
|-
 +
|user||Username of a user on the wiki with permission to create the necessary articles||-
 +
|-
 +
|pass||The users password||-
 +
|-
 +
|separator||Also just "sep" is allowed, specifies the separator character used in the CSV file||''comma''
 +
|-
 +
|title||The format of the title using '''$n''' to specify the column numbers, default is ''$1'' which means to use just the first column as the page title||$1
 +
|-
 +
|template||The template that the parameters should be wrapped by in the created wiki articles||Record
 +
|-
 +
|append||Set this to 1 to place the template at the end of the text if the template doesn't already exist in the article||0
 +
|-
 +
|include||A comma-separated list of the columns that should be included from the CSV, by default all columns are used||''not set''
 +
|-
 +
|}
 +
[[Category:Tools]][[Category:PERL]]

Latest revision as of 20:52, 7 May 2020

Procedure.svg Import CSV data into a wiki
Organic Design procedure

csv2wiki.pl is a simple perl script to import data from a CSV file into a MediaWiki.

Installation

The script depends on a Perl module called MediaWiki.pm which needs to be saved in the same location, or in one of your Perl include paths.

It also depends on LWP and XML::Simple. If these dependencies are not present, Perl will raise an error specifying which one is not available and you can then install it with CPAN, e.g.

cpan XML::Simple

On Debian-like systems there are also packages for the dependencies:

apt install libwww-perl libxml-simple-perl

Usage

The program is run from the shell and requires one parameter which is the filename of a configuration file describing the parameters for the job.

./csv2wiki.pl /home/myJob.conf


Here is an example the content of a configuration file:

wiki     = "http://foo.bar/wiki/index.php"
user     = "Foo"
pass     = "Bar"
csv      = "/home/foo/projects/bar.csv"
title    = "$1 $2 $3"
template = "Customer"


Each line of the input CSV file will be imported into an article in the wiki, and the first line of the input file specifies the column header names, for example:

Title, Firstname, Surname
Mr, Bob, McFoo
Miss, Mary, Barson


In this example the first row of data will be imported into an article called "Mr Bob McFoo" with the following content. The column header names are used as the template parameter names, with the values from that row of the CSV file being used as the values for the template parameters.

{{Customer
 | Title = Mr
 | Firstname = Bob
 | Surname = McFoo
}}


If the page already existed, then the new template would be inserted at the top of the page (or the bottom if "append" is set). Or if the template already exists in the page, then it's values will be updated.

Note that pages that already have templates on them must only use a single value on each line in their syntax.

Configuration options

Here is a description of the possible parameters in the job file and their meaning:

Name Meaning Default value
csv The source file to import relative to the location of the script -
wiki the full long-form URL of the wiki including index.php -
user Username of a user on the wiki with permission to create the necessary articles -
pass The users password -
separator Also just "sep" is allowed, specifies the separator character used in the CSV file comma
title The format of the title using $n to specify the column numbers, default is $1 which means to use just the first column as the page title $1
template The template that the parameters should be wrapped by in the created wiki articles Record
append Set this to 1 to place the template at the end of the text if the template doesn't already exist in the article 0
include A comma-separated list of the columns that should be included from the CSV, by default all columns are used not set