Skip to content

Commit a684c2d

Browse files
committed
Summarization function complete
Finished implementation of the summarization function. It is now configurable and works well with other functions (such as processing highlights) for the book module.
1 parent 21af2e8 commit a684c2d

8 files changed

Lines changed: 150 additions & 14 deletions

File tree

API/TextSummarizer.php

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,28 +10,48 @@
1010
class TextSummarizer
1111
{
1212
private $textRank;
13+
private $level;
1314

14-
function __construct()
15+
public function __construct()
1516
{
1617
$stopWords = new English();
1718
$this->textRank = new TextRankFacade();
1819
$this->textRank->setStopWords($stopWords);
1920
}
2021

21-
function summarizeText($inText){
22-
return preg_replace_callback("|<p>(.*?)</p>|", [&$this, "summarizeTextCallback"], $inText);
22+
public function setSumLevel(int $inLevel, int $maxRank){
23+
$this->level = 5 - $inLevel + 1;
24+
$maxRank = 5 - $maxRank + 1;
25+
//We don't let summarization get below the set config level
26+
if($this->level < $maxRank){
27+
$this->level = $maxRank;
28+
}
29+
if($this->level > 5){
30+
$this->level = 5;
31+
}
32+
}
33+
34+
public function getSumLevel(): int {
35+
return $this->level;
36+
}
37+
38+
public function summarizeText($inText){
39+
if($this->level >= 5){
40+
return $inText;
41+
}
42+
return preg_replace_callback("|<p>(.*?)</p>|s", [&$this, "summarizeTextCallback"], $inText);
2343
}
2444

25-
function summarizeTextCallback($matches)
45+
public function summarizeTextCallback($matches)
2646
{
2747
if (strlen($matches[1]) < 250) {
28-
return $matches[1];
48+
return "<p>" . $matches[1] . "</p>";
2949
}
3050
$textToSummarize = $matches[1];
3151
$sentences = $this->textRank->summarizeTextFreely(
3252
$textToSummarize,
3353
10,
34-
1,
54+
$this->level,
3555
Summarize::GET_ALL_IMPORTANT);
3656
$retText = "<p>";
3757
foreach ($sentences as $sentence) {

Controller/ConfigController.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
1717
use Symfony\Component\HttpFoundation\RedirectResponse;
18+
use Symfony\Component\HttpFoundation\Response;
1819
use Symfony\Component\HttpFoundation\Request;
1920
use Symfony\Component\Routing\Annotation\Route;
2021
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
@@ -32,7 +33,7 @@ class ConfigController extends AbstractController
3233
{
3334
/**
3435
* @Route("/config")
35-
* @Template("@PaustianBookModule//Config/config.html.twig")
36+
* @Template("@PaustianBookModule/Config/config.html.twig")
3637
* @Theme("admin")
3738
*
3839
* @return array|RedirectResponse
@@ -49,7 +50,7 @@ public function config(
4950
$form = $this->createForm(ConfigType::class, $dataValues);
5051
$form->handleRequest($request);
5152
if ($form->isSubmitted() && $form->isValid()) {
52-
if ($form->get('save')->isClicked()) {
53+
if ($form->get('submit')->isClicked()) {
5354
$formData = $form->getData();
5455
// save modvars
5556
$this->setVars($formData);

Controller/UserController.php

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
namespace Paustian\BookModule\Controller;
1717

18+
use Symfony\Component\HttpFoundation\JsonResponse;
1819
use Symfony\Contracts\Translation\TranslatorInterface;
1920
use Zikula\Bundle\CoreBundle\Controller\AbstractController;
2021
use Zikula\Bundle\CoreBundle\RouteUrl;
@@ -58,6 +59,8 @@ public function __construct(
5859
parent::__construct($extension, $permissionApi, $variableApi, $translator);
5960
$this->currentUserApi = $currentUserApi;
6061
$this->textSummarizer = new TextSummarizer();
62+
//initially don't summarize the text at all.
63+
$this->textSummarizer->setSumLevel(1, (int)$this->getVar('sumlevel'));
6164
}
6265

6366
/**
@@ -171,7 +174,10 @@ public function displayarticle(Request $request,
171174
$content = $article->getContents();
172175
//Now add the highlights if necessary
173176
$uid = $this->currentUserApi->get('uid');
174-
if ($uid != "") {
177+
$summarize = $this->getVar('summarize');
178+
$maxLevel = $this->getVar('sumlevel');
179+
//Only process highlights if the text summarizing functions are off or the sumLevel is at 5 sentences (max)
180+
if (($uid != "") && (!$summarize || ($this->textSummarizer->getSumLevel() == 5))) {
175181
//procesing the highlights goes here. This way the figure text won't matter
176182
$content = $this->_process_highlights($content, $article->getAid(), $this->currentUserApi);
177183
}
@@ -191,6 +197,8 @@ public function displayarticle(Request $request,
191197
'chnumber' => $chnumber,
192198
'content' => $content,
193199
'return_url' => $return_url,
200+
'summarize' => $summarize,
201+
'max_level' => $maxLevel,
194202
'show_internals' => $show_internals])->getContent();
195203

196204
$repo = $this->getDoctrine()->getRepository('PaustianBookModule:BookArticlesEntity');
@@ -200,9 +208,7 @@ public function displayarticle(Request $request,
200208
if ($doglossary) {
201209
$return_text = $this->_add_glossary_defs($return_text);
202210
}
203-
//dummy variable for now.
204-
$doSummary = true;
205-
if($doSummary){
211+
if($summarize){
206212
$return_text = $this->textSummarizer->summarizeText($return_text);
207213
}
208214
return new Response($return_text);
@@ -363,6 +369,31 @@ public function displayfigure(Request $request, BookFiguresEntity $figure = null
363369
return new Response($figureText);
364370
}
365371

372+
/**
373+
* @Route("/sumlevelchange", options={"expose"=true})
374+
* @Method("POST")
375+
*
376+
* Grab all comments associated with this module and item ID and return them to the caller
377+
* The caller is a javascript, see the javascripts in Resources/public/js directory
378+
*
379+
* @param Request $request
380+
* @return JsonResponse|AccessDeniedException
381+
*/
382+
public function sumlevelchange(Request $request): JsonResponse{
383+
if (!$this->hasPermission($this->name . '::', '::', ACCESS_READ)) {
384+
return new AccessDeniedException($this->trans('Access forbidden since you cannot read this page.'));
385+
}
386+
//get the summary level and set it
387+
$summaryLevel = (int)$request->get('sumLevel');
388+
$this->textSummarizer->setSumLevel($summaryLevel, (int)$this->getVar('sumlevel'));
389+
390+
//now we have to rerender the text. The $request already has the aid of the article
391+
$response = $this->displayarticle($request);
392+
$jsonReply = ['html' => $response->getContent(),
393+
'sumLevel' => $summaryLevel];
394+
return new JsonResponse($jsonReply);
395+
}
396+
366397
/**
367398
* @Route("/displayglossary")
368399
*

Form/ConfigType.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public function __construct() {
3030
public function buildForm(FormBuilderInterface $builder, array $options)
3131
{
3232
$builder
33-
->add('summarize',CheckboxType::class, ['label' => 'Allow summarization feature', 'required' => true])
33+
->add('summarize',CheckboxType::class, ['label' => 'Allow summarization feature', 'required' => false])
3434
->add('sumlevel', RangeType::class,[
3535
'label' => 'Max level of summarization (1-5, with 1 being less summarization)',
3636
'attr' => [

Resources/public/css/style.css

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,8 @@
4242
.glossary:hover, .glossary {
4343
background-color: lightgoldenrodyellow;
4444
color: black;
45+
}
46+
47+
input.slider{
48+
vertical-align:bottom;
4549
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
(function ($) {
2+
$(document).ready(function () {
3+
summaryModifier.init();
4+
});
5+
6+
var summaryModifier = {
7+
ajaxSettings: {
8+
"dataType": "json",
9+
"error": this.ajaxError,
10+
"timeout": 10000
11+
},
12+
13+
init: function () {
14+
this.cacheDomAndBindEvents();
15+
},
16+
17+
cacheDomAndBindEvents: function(){
18+
this.cacheDom();
19+
this.bindEvents();
20+
},
21+
22+
cacheDom: function () {
23+
this.$summaryLevel = $("input[id=summaryVal]");
24+
this.$contentDiv = $(".panel-body");
25+
this.$aid = $("input[id=aid]");
26+
},
27+
28+
bindEvents: function () {
29+
this.$summaryLevel.on("mouseup", this.changeSummmary.bind(this));
30+
},
31+
32+
changeSummmary: function (evt){
33+
var sumLevel = this.$summaryLevel.val();
34+
var aid = this.$aid.val();
35+
//send a message to preview that item
36+
this.sendAjax(
37+
"paustianbookmodule_user_sumlevelchange",
38+
{"sumLevel" : sumLevel,
39+
"aid": aid},
40+
{"success": this.displayNewText.bind(this), method: "POST"}
41+
);
42+
43+
evt.stopPropagation();
44+
},
45+
46+
displayNewText: function (result, textStatus, jqXHR){
47+
//extract the panel-body content from the returning text
48+
var content = $(".panel-body", result.html);
49+
this.$contentDiv.html(content.html());
50+
//We need to redo this since we just replaced DOMS
51+
this.cacheDomAndBindEvents();
52+
//reset the sumlevel
53+
this.$summaryLevel.val(result.sumLevel);
54+
},
55+
56+
sendAjax: function (url, data, options) {
57+
//push the data object into the options
58+
options.data = data;
59+
$.extend(options, this.ajaxSettings);
60+
var theRoute = Routing.generate(url);
61+
$.ajax(theRoute, options);
62+
},
63+
64+
ajaxError: function(jqXHR, textStatus, errorThrown){
65+
window.alert(textStatus + "\n" +errorThrown);
66+
},
67+
};
68+
})(jQuery);

Resources/views/Config/config.html.twig

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,12 @@
1111
<legend>{{ 'Summarize' | trans }}</legend>
1212
{{ form_row(form.summarize) }}
1313
{{ form_row(form.sumlevel) }}
14+
1415
</fieldset>
1516
<div class="form-group">
1617
<div class="col-lg-offset-3 col-lg-9">
17-
{{ form_widget(form.add, {'attr': {'class': 'btn btn-success'}}) }}
18+
{{ form_widget(form.submit, {'attr': {'class': 'btn btn-success'}}) }}
1819
</div>
1920
</div>
21+
2022
{{ form_end(form) }}

Resources/views/User/book_user_displayarticle.html.twig

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
{{ pageSetVar('title', article.title) }}
22
{{ pageAddAsset('javascript', zasset('@PaustianBookModule:js/book.js')) }}
3+
{{ pageAddAsset('javascript', zasset('@PaustianBookModule:js/summaryModifier.js')) }}
34

45
{% set formScript %}
56
<script type="text/javascript">
@@ -33,6 +34,15 @@
3334
<p>{{ 'Chapter id:' | trans }}{{ article.cid }}</p>
3435
<p>{{ 'Book id:' | trans }}{{ article.bid }}</p>
3536
{% endif %}
37+
<input type="hidden" id="aid" value="{{ article.aid }}" name="aid" />
38+
<input type="hidden" id="cid" value="{{ article.cid }}" name="cid" />
39+
<input type="hidden" id="bid" value="{{ article.bid }}" name="bid" />
40+
{% if summarize %}
41+
<div class="slidecontainer">
42+
<label><b>Level of Text Summarization:</b></label><br />
43+
<p> None <input type="range" min="1" max="{{ max_level }}" value="1" class="slider" id="summaryVal"> Max</p>
44+
</div>
45+
{% endif %}
3646
<p> <a href="{{ path('paustianbookmodule_user_toc', {bid:article.bid}) }}" title="{{ 'Table of Contents' | trans }}" class="fa fa-book"></a>|
3747
<a href="{{ path('paustianbookmodule_user_displaychapter', {cid:article.cid}) }}" title="{{ 'Chapter Article List' | trans }}" class="fa fa-bookmark"></a>|
3848
<a href="{{ path('paustianbookmodule_user_displayarticle', {theme:'Printer', aid:article.aid}) }}" title="{{ 'Printable Version' | trans }}" class="fa fa-print"></a>|

0 commit comments

Comments
 (0)