Skip to content

Instantly share code, notes, and snippets.

@gangeli
Created April 13, 2014 05:26
Show Gist options
  • Save gangeli/10570471 to your computer and use it in GitHub Desktop.
Save gangeli/10570471 to your computer and use it in GitHub Desktop.
A wrapper around wp2txt with parallelism and extra cleaning
#!/bin/bash
exec scala -J-Xmx4G -J-Xss16m "$0" "$@"
!#
/*
* Convert a Wikipdedia dump to plain-text files, one article per file.
*
* Usage: wikipedia2text <input_dump_file> <output_directory>
*
* NOTES:
* - This script makes use of wp2txt (https://github.com/yohasebe/wp2txt), with some
* custom post-processing and parallelization. Most of the credit should be directed
* there.
* - Input must be an unzipped *.xml dump; output must be a directory to place articles into.
* - This requires a [relatively] new ruby version -- 1.8+, though I [Gabor] ran it with 1.9.
* - Scala is awful at backwards compatibility. The script was created for Scala 2.10.
*
* Released under the MIT license:
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//(scala)
import scala.collection.JavaConversions._
import scala.xml._
import scala.xml.pull._
import scala.xml.transform._
import scala.sys.process._
import scala.util.matching._
import scala.util.matching.Regex._
import scala.concurrent._
import scala.concurrent.duration.Duration
import ExecutionContext.Implicits.global
//(java)
import java.io._
import java.util.concurrent.Semaphore
if (args.length != 2) {
println("USAGE: wiki2txt <INPUT_XML_FILE> <OUTPUT_DIRECTORY> <START>? <COUNT>?")
exit(1)
}
val INPUT = args(0) // e.g., "/scr/nlp/data/tackbp2013/data/2013/wikipedia2013_07_03.xml"
val OUTPUT = args(1) // e.g., "/scr/nlp/data/tackbp2013/data/2013/wikipedia2013_plaintext/"
val START = if (args.length > 2) args(2).toDouble.toInt else 0
val COUNT = if (args.length > 3) args(3).toDouble.toInt else Int.MaxValue
try {
new File(OUTPUT).mkdir
} catch {
case (e:Exception) => throw new RuntimeException(e)
}
print("Loading XML...")
val src = scala.io.Source.fromFile(INPUT)
val reader = new XMLEventReader(src)
println("done.")
val cleans = Seq[Regex](
"""\[tpl\][^\[]*\[/tpl\]""".r, // not sure what these are
"""\[tpl\][^\[]*\[/tpl\]""".r, // repeat to get rid of nesting
"""\[tpl\][^\[]*\[/tpl\]""".r, // repeat x3 (who needs CFGs?)
"""\[\[|\]\]""".r, // strip errant links
"""\{\{|\}\}""".r, // strip errant {{ or }}
"""<ref>[^\<]*</ref>""".r, // strip remaining references
"""\[/?ref\]""".r, // strip these references as well
"""</?ref>""".r, // and these references
"""~~~~~\s*\|[^~]*""".r, // strip lines beginning with |
"""Image:[^\|]*\|""".r // strip image tags
)
val permits = new Semaphore(Runtime.getRuntime.availableProcessors * 5)
var i = 0;
for (page <- slurp(reader, "page").drop(START).take(COUNT)) {
val id = (page \\ "id")(0).text.toInt
val title = (page \\ "title")(0).text
try {
// Write file
val xmlString = transformForPrinting(toXML(page.asInstanceOf[Elem])).toString
if (!xmlString.contains("<redirect ")) {
println("processing [" + i + "] " + title)
i += 1
permits.acquire
future { try {
val xmlFile = File.createTempFile("wikipedia_page_", ".xml");
val writer = new FileWriter(xmlFile)
writer.write(xmlString
.replaceAll("""&lt;ref[^&]*&gt;([^&]|&[^l]|&l[^t])+&lt;/ref&gt;""", " ")
)
writer.close
// Run wiki2text
val exitCode:Int = {List[String](
"wp2txt",
"--list-off",
"--heading-off",
"--title-off",
"--table-off",
"--template-off",
"--redirect-off",
"--strip-marker",
"--category-off",
"--input-file", xmlFile.getPath,
"--output-dir", "/tmp/") ! ProcessLogger(
(in:String) => {},
(out:String) => {} )}
if (exitCode != 0) {
System.err.println("Could not convert " + id + ": " + title)
}
// Post-process file
val unprocessedFile = "/tmp/" + xmlFile.getName.substring(0, xmlFile.getName.length-4) + "-1.txt"
val fileAsText = scala.io.Source.fromFile(unprocessedFile, "UTF-8").getLines.mkString("~~~~~")
new File(OUTPUT + "/" + (id / 10000)).mkdir
val toWrite:String = cleans.foldLeft(fileAsText){ case (soFar:String, regex:Regex) =>
soFar.replaceAll(regex.toString, " ")
}
.replaceAll("""~~~~~[^\.\s]+($|~~~~~)""", "~~~~~") // strip lines (or ends of lines) without punctuation
.replaceAll("""\.[^\.]+($| )""", ".~~~~~") // strip lines (or ends of lines) without punctuation
.replaceAll("~~~~~", "\n")
.trim
// Actually write (if file is >100 bytes)
// This filters things like disambiguation pages or redirects, or pages
// which are entirely lists, etc (these should really not be
// textified to begin with)
if (toWrite.length > 100) {
val writer2 = new FileWriter(OUTPUT + "/" + (id / 10000) + "/" + id + ".txt")
writer2.write(toWrite)
writer2.close
}
// Clean up
new File(unprocessedFile).delete
xmlFile.delete
} catch {
case (e:Exception) => e.printStackTrace
} finally {
permits.release
} }
}
} catch {
case (e:Exception) => e.printStackTrace
}
}
println("Loop done.")
print("Awaiting futures (wait 10 min)...")
Thread.sleep(600000)
println("done.")
def toXML(page:Elem) =
<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.8/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.8/ http://www.mediawiki.org/xml/export-0.8.xsd" version="0.8" xml:lang="en">
<siteinfo>
<sitename>Wikipedia</sitename>
<base>http://en.wikipedia.org/wiki/Main_Page</base>
<generator>MediaWiki 1.22wmf5</generator>
<case>first-letter</case>
<namespaces>
<namespace key="-2" case="first-letter">Media</namespace>
<namespace key="-1" case="first-letter">Special</namespace>
<namespace key="0" case="first-letter" />
<namespace key="1" case="first-letter">Talk</namespace>
<namespace key="2" case="first-letter">User</namespace>
<namespace key="3" case="first-letter">User talk</namespace>
<namespace key="4" case="first-letter">Wikipedia</namespace>
<namespace key="5" case="first-letter">Wikipedia talk</namespace>
<namespace key="6" case="first-letter">File</namespace>
<namespace key="7" case="first-letter">File talk</namespace>
<namespace key="8" case="first-letter">MediaWiki</namespace>
<namespace key="9" case="first-letter">MediaWiki talk</namespace>
<namespace key="10" case="first-letter">Template</namespace>
<namespace key="11" case="first-letter">Template talk</namespace>
<namespace key="12" case="first-letter">Help</namespace>
<namespace key="13" case="first-letter">Help talk</namespace>
<namespace key="14" case="first-letter">Category</namespace>
<namespace key="15" case="first-letter">Category talk</namespace>
<namespace key="100" case="first-letter">Portal</namespace>
<namespace key="101" case="first-letter">Portal talk</namespace>
<namespace key="108" case="first-letter">Book</namespace>
<namespace key="109" case="first-letter">Book talk</namespace>
<namespace key="446" case="first-letter">Education Program</namespace>
<namespace key="447" case="first-letter">Education Program talk</namespace>
<namespace key="710" case="first-letter">TimedText</namespace>
<namespace key="711" case="first-letter">TimedText talk</namespace>
<namespace key="828" case="first-letter">Module</namespace>
<namespace key="829" case="first-letter">Module talk</namespace>
</namespaces>
</siteinfo>
{page}
</mediawiki>
def transformForPrinting(doc : Elem) : Elem = {
def stripNamespaces(node : Node) : Node = {
node match {
case e : Elem =>
e.copy(scope = TopScope, child = e.child map (stripNamespaces))
case _ => node;
}
}
doc.copy( child = doc.child map (stripNamespaces) )
}
def slurp(it:Iterator[XMLEvent], tag: String): Iterator[Node] = {
for ( event <- it;
tree <- getTree(it, event, tag) ) yield tree
}
def getTree(it:Iterator[XMLEvent], event:XMLEvent, tag:String):Option[Node] = {
event match {
case EvElemStart(pre, `tag`, attrs, _) =>
return subTree(it, tag, attrs)
case _ =>
}
return None
}
def subTree(it:Iterator[XMLEvent], tag: String, attrs: MetaData): Option[Node] = {
var children = List[Node]()
while (it.hasNext) {
it.next match {
case EvElemStart(_, t, a, _) => {
children = children :+ subTree(it, t, a).get
}
case EvText(t) => {
children = children :+ Text(t)
}
case EvElemEnd(_, t) => {
return Some(new Elem(null, tag, attrs, xml.TopScope, children: _*))
}
case EvEntityRef(t) =>
t match {
case "lt" =>
children = children :+ Text("<")
case "gt" =>
children = children :+ Text(">")
case "amp" =>
children = children :+ Text("&")
case "quot" =>
children = children :+ Text("\"")
case "apos" =>
children = children :+ Text("'")
case _ =>
throw new IllegalStateException(t)
}
case _ =>
}
}
return None // this shouldn't happen with good XML
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment