Skip to content

Commit

Permalink
version 3.0.0 issues #8 #9 #10 #12 #13 #14
Browse files Browse the repository at this point in the history
  • Loading branch information
heitorbarbieri committed Apr 3, 2020
1 parent 2c15da5 commit 726efc9
Show file tree
Hide file tree
Showing 24 changed files with 869 additions and 160 deletions.
Empty file modified AntesDoAssembly.txt
100644 → 100755
Empty file.
Empty file modified COPYRIGHT.md
100644 → 100755
Empty file.
Empty file modified DeCSHighlighter.html
100644 → 100755
Empty file.
Empty file modified README.md
100644 → 100755
Empty file.
21 changes: 15 additions & 6 deletions build.sbt
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,25 @@ name := "DeCSHighlighter"

version := "0.1"

scalaVersion := "2.13.1" // "2.12.9"
scalaVersion := "2.13.1"

val circeVersion = "0.13.0-M2" //"0.12.0-M4" //"0.11.1" //"0.10.0"
val playJsonVersion = "2.8.1"
val scalajVersion = "2.4.2" //"2.4.1"
val servletApiVersion = "4.0.1" //"3.0.1"
//val hairyfotrVersion = "0.1.17"
val scalaTestVersion = "3.2.0-M2" //"3.1.0-SNAP13" //"3.0.8" //"3.0.7"
val scalaTestVersion = "3.3.0-SNAP2" //"3.2.0-M2"
val supersafeVersion = "1.1.7"
val luceneVersion = "8.5.0" //"8.4.1"

libraryDependencies ++= Seq(
"io.circe" %% "circe-core" % circeVersion,
"io.circe" %% "circe-generic" % circeVersion,
"io.circe" %% "circe-parser" % circeVersion,
"com.typesafe.play" %% "play-json" % playJsonVersion,
"org.scalaj" %% "scalaj-http" % scalajVersion,
"javax.servlet" % "javax.servlet-api" % servletApiVersion % "provided",
"org.apache.lucene" % "lucene-core" % luceneVersion,
"org.apache.lucene" % "lucene-analyzers-common" % luceneVersion,
"org.scalactic" %% "scalactic" % scalaTestVersion,
"org.scalatest" %% "scalatest" % scalaTestVersion % "test"

//"com.artima.supersafe" %% "supersafe" % supersafeVersion
)

Expand All @@ -38,3 +40,10 @@ javaOptions in Jetty ++= Seq(
)

containerPort := 7171

assemblyMergeStrategy in assembly := {
case "module-info.class" => MergeStrategy.discard
case x =>
val oldStrategy = (assemblyMergeStrategy in assembly).value
oldStrategy(x)
}
Empty file modified dicas.txt
100644 → 100755
Empty file.
1 change: 0 additions & 1 deletion project/assembly.sbt

This file was deleted.

2 changes: 1 addition & 1 deletion project/build.properties
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1 +1 @@
sbt.version = 1.3.3
sbt.version=1.3.8
Empty file modified project/build.sbt
100644 → 100755
Empty file.
Empty file modified project/license.sbt
100644 → 100755
Empty file.
4 changes: 4 additions & 0 deletions project/metals.sbt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// DO NOT EDIT! This file is auto-generated.
// This file enables sbt-bloop to create bloop config files.

addSbtPlugin("ch.epfl.scala" % "sbt-bloop" % "1.4.0-RC1")
4 changes: 3 additions & 1 deletion project/plugins.sbt
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "4.0.2")
addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "4.2.0")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.10")

2 changes: 1 addition & 1 deletion src/main/scala/org/bireme/dh/CharSeq.scala
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,5 @@ case class CharSeq(ch: Char,
other: mutable.Buffer[CharSeq], // Changed from Set because Memory overflow error
id: StringBuilder)
object CharSeq {
def apply(ch: Char): CharSeq = new CharSeq(ch, mutable.Buffer[CharSeq](), new mutable.StringBuilder())
def apply(ch: Char): CharSeq = new CharSeq(ch, mutable.ListBuffer[CharSeq](), new mutable.StringBuilder(0))
}
186 changes: 186 additions & 0 deletions src/main/scala/org/bireme/dh/DeCS2Lucene.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
package org.bireme.dh

import java.io.File
import java.nio.file.Path

import bruma.master.{Master, MasterFactory, Record}
import org.apache.lucene.analysis.core.KeywordAnalyzer
import org.apache.lucene.document.{Document, Field, StringField}
import org.apache.lucene.index.{IndexWriter, IndexWriterConfig, IndexableField}
import org.apache.lucene.store.{Directory, FSDirectory}
import org.bireme.dh.Tools.uniformString

import scala.jdk.CollectionConverters._

object DeCS2Lucene extends App {
private def usage(): Unit = {
System.err.println("usage: DeCS2Lucene <options> ")
System.err.println("options:")
System.err.println("-isis=<isisPath> : path to DeCS Isis master")
System.err.println("-lucene=<lucenePath> : path to Lucene DeCS index to be created")
}
if (args.length < 2) usage()

val parameters = args.foldLeft[Map[String,String]](Map()) {
case (map, par) =>
val split = par.split(" *= *", 2)
split.length match {
case 1 => map + ((split(0).substring(2), ""))
case _ => map + ((split(0).substring(1), split(1)))
}
}

create(parameters("isis"), parameters("lucene"))

val stopwords = Set("la", "foram", "amp", "www") // are common words and have other meanings in other languages


def create(isisPath: String,
lucenePath: String): Unit = {
val mst: Master = MasterFactory.getInstance(isisPath).open()

val analyzer: KeywordAnalyzer = new KeywordAnalyzer()
val indexPath: Path = new File(lucenePath).toPath
val directory: Directory = FSDirectory.open(indexPath)
val config: IndexWriterConfig = new IndexWriterConfig(analyzer).setOpenMode(IndexWriterConfig.OpenMode.CREATE)
val iwriter: IndexWriter = new IndexWriter(directory, config)

mst.iterator().asScala.foreach(createDocuments(_, iwriter))
mst.close()
iwriter.forceMerge(1)
iwriter.close()
directory.close()
}

def createDocuments(rec: Record,
writer: IndexWriter): Unit = {
if (rec.getStatus == Record.Status.ACTIVE) {
val id: String = getField(rec, 99).head._2
val uid: String = getField(rec, 480).headOption.getOrElse(("",""))._2
val publType: String = getField(rec, 105) match {
case set if set.isEmpty => ""
case set => set.head._2
}
val preCod: Boolean = isPreCod(rec)
val ptDoc: Seq[Document] = getPtDocument(id, uid, publType, preCod, rec)
val esDoc: Seq[Document] = getEsDocument(id, uid, publType, preCod, rec)
val enDoc: Seq[Document] = getEnDocument(id, uid, publType, preCod, rec)
val frDoc: Seq[Document] = getFrDocument(id, uid, publType, preCod, rec)

ptDoc.foreach(writer.addDocument)
esDoc.foreach(writer.addDocument)
enDoc.foreach(writer.addDocument)
frDoc.foreach(writer.addDocument)
}
}

private def isPreCod(rec: Record): Boolean = getField(rec, fldTag=106).exists(x => x._2.trim.head.equals('c'))

private def getEnDocument(id: String,
uid: String,
publType: String,
preCod: Boolean,
rec: Record): Seq[Document] = {
getDocument(id, uid, 1, 'i', "en", publType, preCod, rec)
}

private def getEsDocument(id: String,
uid: String,
publType: String,
preCod: Boolean,
rec: Record): Seq[Document] = {
getDocument(id, uid, 2, 'e', "es", publType, preCod, rec)
}

private def getPtDocument(id: String,
uid: String,
publType: String,
preCod: Boolean,
rec: Record): Seq[Document] = {
getDocument(id, uid, 3, 'p', "pt", publType, preCod, rec)
}

private def getFrDocument(id: String,
uid: String,
publType: String,
preCod: Boolean,
rec: Record): Seq[Document] = {
getDocument(id, uid, 16, 'f', "fr", publType, preCod, rec)
}

private def getDocument(id: String,
uid: String,
field: Int,
subFld: Char,
lang: String,
publType: String,
preCod: Boolean,
rec: Record): Seq[Document] = {
val descr: Seq[(IndexableField, IndexableField)] = getDescriptors(field, rec)
val synonyms: Seq[(IndexableField, IndexableField)] = getSynonyms(subFld, rec)

descr.map {
fld =>
val doc = new Document()
doc.add(new StringField("id", id, Field.Store.YES))
doc.add(new StringField("uniqueId", uid, Field.Store.YES))
doc.add(new StringField("publicationType", publType, Field.Store.YES))
doc.add(new StringField("preCod", if (preCod) "t" else "f", Field.Store.YES))
doc.add(new StringField("lang", lang, Field.Store.YES))
doc.add(new StringField("termType", "descriptor", Field.Store.YES))
doc.add(fld._1)
doc.add(fld._2)
doc
} ++
synonyms.map {
fld =>
val doc = new Document()
doc.add(new StringField("id", id, Field.Store.YES))
doc.add(new StringField("uniqueId", uid, Field.Store.YES))
doc.add(new StringField("publicationType", publType, Field.Store.YES))
doc.add(new StringField("preCod", if (preCod) "t" else "f", Field.Store.YES))
doc.add(new StringField("lang", lang, Field.Store.YES))
doc.add(new StringField("termType", "synonym", Field.Store.YES))
doc.add(fld._1)
doc.add(fld._2)
doc
}
}

private def getDescriptors(field: Int,
rec: Record): Seq[(IndexableField, IndexableField)] = {
getField(rec, field).map {
x => (
new StringField("term", x._1, Field.Store.YES),
new StringField("term_normalized", x._2, Field.Store.YES)
)
}
}

private def getSynonyms(subFld: Char,
rec: Record): Seq[(IndexableField, IndexableField)] = {
rec.getFieldList(50).asScala.flatMap(_.getTagSubfields(subFld).asScala.map {
fld =>
val content: String = fld.getContent
(
new StringField("term", content, Field.Store.YES),
new StringField("term_normalized", uniformString(content), Field.Store.YES)
)
}).toSeq
}

/**
* Retrieve a record field content from an Isis database
* @param rec the Isis database record object
* @param fldTag the tag of the field to be retrieved
* @return a sequence of (field content,field content normalized)
*/
private def getField(rec: Record,
fldTag: Int): Seq[(String, String)] = {
rec.getFieldList(fldTag).asScala.foldLeft(Seq[(String, String)]()) {
case (seq, fld) =>
val content: String = fld.getContent
seq :+ (content, uniformString(content))
}
}
}
81 changes: 54 additions & 27 deletions src/main/scala/org/bireme/dh/HighlightServlet.scala
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ package org.bireme.dh

import java.io.PrintWriter

import io.circe.Json
import play.api.libs.json._

import javax.servlet.ServletConfig
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}

Expand All @@ -22,7 +23,7 @@ import scala.collection.mutable
* date: September - 2018
*/
class HighlightServlet extends HttpServlet {
var tree: Map[Char, CharSeq] = _
var highlighter: Highlighter = _

/**
* Do initial web app configuration
Expand All @@ -32,13 +33,10 @@ class HighlightServlet extends HttpServlet {
super.init(config)

val decsPath: String = config.getServletContext.getInitParameter("DECS_PATH")
if ((decsPath == null) || decsPath.isEmpty )
if ((decsPath == null) || decsPath.isEmpty)
throw new NullPointerException(s"DECS_PATH = $decsPath")

val terms: Predef.Map[String, String] = Tools.decs2Set(decsPath)

tree = Highlighter.createTermTree(terms)

highlighter = new Highlighter(decsPath)
println("HighlightServlet is listening ...")
}

Expand Down Expand Up @@ -70,39 +68,68 @@ class HighlightServlet extends HttpServlet {
if ((doc == null) || doc.isEmpty ) response.sendError(400, "Missing document parameter")
else {
// Parse parameters
val prefix0 = request.getParameter("prefix")
val suffix0 = request.getParameter("suffix")
val prefix0: String = request.getParameter("prefix")
val suffix0: String = request.getParameter("suffix")

val scanLang: Option[String] = Option(request.getParameter("scanLang")).flatMap {
opt => opt match {
case "en" | "es" | "pt" | "fr" => Some(opt)
case _ => None
}
}
val outLang: Option[String] = Option(request.getParameter("outLang")).flatMap {
opt => opt match {
case "en" | "es" | "pt" | "fr" => Some(opt)
case _ => None
}
}
val pubType: Option[Char] = Option(request.getParameter("pubType")).map(_.trim.toLowerCase.charAt(0)).flatMap {
opt => opt match {
case 'h' | 'q' | 't' => Some(opt)
case _ => None
}
}
val scanDescriptors: Boolean = true
val scanSynonyms: Boolean = Option(request.getParameter("scanSynonyms"))
.map(x => x.isEmpty || (x.toLowerCase.head == 't')).getOrElse(true)
val onlyPreCod: Boolean = Option(request.getParameter("onlyPreCod"))
.map(x => x.isEmpty || (x.toLowerCase.head == 't')).getOrElse(false)
val conf: Config = Config(scanLang, outLang, pubType, scanDescriptors, scanSynonyms, onlyPreCod)

val prefix = if ((prefix0 == null) || prefix0.isEmpty ) "<em>" else prefix0
val suffix = if ((suffix0 == null) || suffix0.isEmpty ) "</em>" else suffix0
val sText: String = request.getParameter("showText")
val sPositions: String = request.getParameter("showPositions")
val sDescriptors: String = request.getParameter("showDescriptors")
val showText: Boolean = (sText != null) && (sText.isEmpty || sText.toBoolean)
val showPositions: Boolean = (sPositions != null) && (sPositions.isEmpty || sPositions.toBoolean)
val showDescriptors: Boolean = (sDescriptors != null) && (sDescriptors.isEmpty || sDescriptors.toBoolean)
val showText: Boolean = Option(request.getParameter("showText"))
.map(x => x.isEmpty || (x.toLowerCase.head == 't')).getOrElse(true)
val showPositions: Boolean = Option(request.getParameter("showPositions"))
.map(x => x.isEmpty || (x.toLowerCase.head == 't')).getOrElse(true)
val showDescriptors: Boolean = Option(request.getParameter("showDescriptors"))
.map(x => x.isEmpty || (x.toLowerCase.head == 't')).getOrElse(true)

println(s"scanSynonyms=$scanSynonyms showText=$showText showPositions=$showPositions showDescriptors=$showDescriptors")

// Highlight the input text
val (marked: String, seq: Seq[(Int, Int, String, String)], set: Seq[String]) = Highlighter.highlight(prefix, suffix, doc, tree)
val result: mutable.Buffer[(String, Json)] = mutable.Buffer[(String, Json)]()
val (marked: String, seq: Seq[(Int, Int, String, String)], set: Seq[String]) =
highlighter.highlight(prefix, suffix, doc, conf)
val result: mutable.Map[String, JsValue] = mutable.Map[String, JsValue]()

// Show all output (text, positions and descriptors) if the showText, showPositions and showDescriptors parameters
// are absent.
if (!showText && !showPositions && !showDescriptors) {
result += "text" -> Json.fromString(marked)
result += ("positions" -> Json.fromValues(seq.map(
elem => Json.obj("begin" -> Json.fromInt(elem._1), "end" -> Json.fromInt(elem._2),
"id" -> Json.fromString(elem._3), "descriptor" -> Json.fromString(elem._4)))))
result += ("descriptors" -> Json.fromValues(set.map(d => Json.fromString(d))))
result += "text" -> JsString(marked)
result += "positions" -> JsArray(seq.map(
elem => JsObject(Map("begin" -> JsNumber(elem._1), "end" -> JsNumber(elem._2), "id" -> JsString(elem._3),
"descriptor" -> JsString(elem._4)))))
result += ("descriptors" -> JsArray(set.map(d => JsString(d))))
} else {
if (showText) result += "text" -> Json.fromString(marked)
if (showPositions) result += ("positions" -> Json.fromValues(seq.map(
elem => Json.obj("begin" -> Json.fromInt(elem._1), "end" -> Json.fromInt(elem._2), "id" -> Json.fromString(elem._3)))))
if (showDescriptors) result += ("descriptors" -> Json.fromValues(set.map(d => Json.fromString(d))))
if (showText) result += "text" -> JsString(marked)
if (showPositions) result += "positions" -> JsArray(seq.map(
elem => JsObject(Map("begin" -> JsNumber(elem._1), "end" -> JsNumber(elem._2), "id" -> JsString(elem._3)))))
if (showDescriptors) result += "descriptors" -> JsArray(set.map(d => JsString(d)))
}
response.setContentType("application/json")

// Transform the json object into a String and print it
val resultStr = Json.obj(result.toSeq: _*).spaces2
val resultStr = Json.stringify(JsObject(result))
val writer: PrintWriter = response.getWriter
writer.write(resultStr)
writer.close()
Expand Down
Loading

0 comments on commit 726efc9

Please sign in to comment.