wbnews 1.45.0__py2.py3-none-any.whl → 1.58.1__py2.py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- wbnews/admin.py +4 -1
- wbnews/factories.py +7 -5
- wbnews/filters/__init__.py +1 -1
- wbnews/filters/news.py +39 -2
- wbnews/import_export/backends/news.py +3 -3
- wbnews/import_export/handlers/news.py +35 -3
- wbnews/import_export/parsers/emails/news.py +0 -9
- wbnews/import_export/parsers/emails/utils.py +16 -12
- wbnews/import_export/parsers/rss/news.py +3 -9
- wbnews/locale/de/LC_MESSAGES/django.mo +0 -0
- wbnews/locale/de/LC_MESSAGES/django.po +93 -39
- wbnews/locale/de/LC_MESSAGES/django.po.translated +173 -0
- wbnews/locale/en/LC_MESSAGES/django.mo +0 -0
- wbnews/locale/en/LC_MESSAGES/django.po +159 -0
- wbnews/locale/fr/LC_MESSAGES/django.mo +0 -0
- wbnews/locale/fr/LC_MESSAGES/django.po +162 -0
- wbnews/migrations/0011_newsrelationship_content_object_repr.py +18 -0
- wbnews/migrations/0012_alter_news_unique_together_news_identifier_and_more.py +91 -0
- wbnews/migrations/0013_alter_news_datetime.py +19 -0
- wbnews/migrations/0014_newsrelationship_unique_news_relationship.py +27 -0
- wbnews/models/llm/cleaned_news.py +26 -23
- wbnews/models/news.py +35 -21
- wbnews/models/relationships.py +25 -1
- wbnews/models/sources.py +35 -5
- wbnews/models/utils.py +15 -0
- wbnews/serializers.py +51 -5
- wbnews/tasks.py +16 -0
- wbnews/tests/parsers/__init__.py +0 -0
- wbnews/tests/parsers/test_emails.py +25 -0
- wbnews/tests/test_models.py +65 -0
- wbnews/tests/test_utils.py +7 -0
- wbnews/urls.py +0 -5
- wbnews/utils.py +57 -0
- wbnews/viewsets/__init__.py +1 -1
- wbnews/viewsets/buttons.py +21 -2
- wbnews/viewsets/display.py +34 -21
- wbnews/viewsets/endpoints.py +22 -6
- wbnews/viewsets/menu.py +6 -0
- wbnews/viewsets/titles.py +5 -1
- wbnews/viewsets/views.py +48 -23
- {wbnews-1.45.0.dist-info → wbnews-1.58.1.dist-info}/METADATA +1 -2
- wbnews-1.58.1.dist-info/RECORD +65 -0
- wbnews-1.45.0.dist-info/RECORD +0 -49
- {wbnews-1.45.0.dist-info → wbnews-1.58.1.dist-info}/WHEEL +0 -0
wbnews/models/relationships.py
CHANGED
|
@@ -1,21 +1,45 @@
|
|
|
1
1
|
from django.contrib.contenttypes.fields import GenericForeignKey
|
|
2
2
|
from django.contrib.contenttypes.models import ContentType
|
|
3
3
|
from django.db import models
|
|
4
|
+
from django.utils.translation import gettext as _
|
|
4
5
|
|
|
5
6
|
|
|
6
7
|
class NewsRelationship(models.Model):
|
|
8
|
+
class SentimentChoices(models.IntegerChoices):
|
|
9
|
+
POSITIVE = 4, _("Positive")
|
|
10
|
+
SLIGHTLY_POSITIVE = 3, _("Slightly Positive")
|
|
11
|
+
SLIGHTLY_NEGATIVE = 2, _("Slightly Negative")
|
|
12
|
+
NEGATIVE = 1, _("Negative")
|
|
13
|
+
|
|
14
|
+
def get_color(self):
|
|
15
|
+
colors = {
|
|
16
|
+
"POSITIVE": "#96DD99",
|
|
17
|
+
"SLIGHTLY_POSITIVE": "#FFEE8C",
|
|
18
|
+
"SLIGHTLY_NEGATIVE": "#FF964F",
|
|
19
|
+
"NEGATIVE": "#FF6961",
|
|
20
|
+
}
|
|
21
|
+
return colors[self.name]
|
|
22
|
+
|
|
7
23
|
news = models.ForeignKey(to="wbnews.News", related_name="relationships", on_delete=models.CASCADE)
|
|
8
24
|
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
|
|
9
25
|
object_id = models.PositiveIntegerField()
|
|
10
26
|
content_object = GenericForeignKey("content_type", "object_id")
|
|
27
|
+
content_object_repr = models.CharField(max_length=512, default="")
|
|
11
28
|
|
|
12
29
|
important = models.BooleanField(null=True, blank=True)
|
|
13
|
-
sentiment = models.PositiveIntegerField(null=True, blank=True)
|
|
30
|
+
sentiment = models.PositiveIntegerField(null=True, blank=True, choices=SentimentChoices.choices)
|
|
14
31
|
analysis = models.TextField(null=True, blank=True)
|
|
15
32
|
|
|
33
|
+
def save(self, *args, **kwargs):
|
|
34
|
+
self.content_object_repr = str(self.content_object)
|
|
35
|
+
super().save(*args, **kwargs)
|
|
36
|
+
|
|
16
37
|
def __str__(self) -> str:
|
|
17
38
|
return f"{self.news.title} -> {self.content_object}"
|
|
18
39
|
|
|
19
40
|
class Meta:
|
|
20
41
|
verbose_name = "News Relationship"
|
|
21
42
|
indexes = [models.Index(fields=["content_type", "object_id"])]
|
|
43
|
+
constraints = [
|
|
44
|
+
models.UniqueConstraint(name="unique_news_relationship", fields=["content_type", "object_id", "news"])
|
|
45
|
+
]
|
wbnews/models/sources.py
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
1
3
|
from django.contrib.postgres.fields import ArrayField
|
|
2
4
|
from django.db import models
|
|
3
5
|
from wbcore.models import WBModel
|
|
4
6
|
|
|
7
|
+
from wbnews.models.utils import endpoint_to_author
|
|
8
|
+
|
|
5
9
|
|
|
6
10
|
class NewsSource(WBModel):
|
|
7
11
|
class Type(models.TextChoices):
|
|
@@ -16,16 +20,17 @@ class NewsSource(WBModel):
|
|
|
16
20
|
description = models.TextField(default="", blank=True)
|
|
17
21
|
author = models.CharField(max_length=255, default="")
|
|
18
22
|
clean_content = models.BooleanField(default=False)
|
|
19
|
-
|
|
20
|
-
blank=True,
|
|
21
|
-
null=True,
|
|
22
|
-
unique=True,
|
|
23
|
-
)
|
|
23
|
+
endpoint = models.CharField(max_length=1024, unique=True)
|
|
24
24
|
is_active = models.BooleanField(default=True)
|
|
25
25
|
|
|
26
26
|
def __str__(self):
|
|
27
27
|
return f"{self.title}"
|
|
28
28
|
|
|
29
|
+
def save(self, *args, **kwargs):
|
|
30
|
+
if not self.author and self.endpoint:
|
|
31
|
+
self.author = endpoint_to_author(self.endpoint)
|
|
32
|
+
super().save(*args, **kwargs)
|
|
33
|
+
|
|
29
34
|
@classmethod
|
|
30
35
|
def get_representation_endpoint(cls) -> str:
|
|
31
36
|
return "wbnews:sourcerepresentation-list"
|
|
@@ -41,3 +46,28 @@ class NewsSource(WBModel):
|
|
|
41
46
|
@classmethod
|
|
42
47
|
def get_endpoint_basename(cls) -> str:
|
|
43
48
|
return "wbnews:source"
|
|
49
|
+
|
|
50
|
+
@classmethod
|
|
51
|
+
def source_dict_to_model(cls, data: dict):
|
|
52
|
+
sources = NewsSource.objects.all()
|
|
53
|
+
endpoint = data.pop("endpoint", None)
|
|
54
|
+
if "id" in data:
|
|
55
|
+
return sources.get(id=data["id"])
|
|
56
|
+
if type := data.get("type"):
|
|
57
|
+
sources = sources.filter(type=type)
|
|
58
|
+
if identifier := data.get("identifier"):
|
|
59
|
+
sources = sources.filter(identifier=identifier)
|
|
60
|
+
elif endpoint:
|
|
61
|
+
for source in sources:
|
|
62
|
+
match = re.search(source.endpoint, endpoint)
|
|
63
|
+
if source.endpoint == endpoint or match:
|
|
64
|
+
return source
|
|
65
|
+
if sources.count() == 1:
|
|
66
|
+
return sources.first()
|
|
67
|
+
else:
|
|
68
|
+
if endpoint:
|
|
69
|
+
# Pattern to capture and replace the local part of an email
|
|
70
|
+
pattern = r"^[^@]+"
|
|
71
|
+
# Replace the local part of an email with a wildcard regex
|
|
72
|
+
endpoint = re.sub(pattern, ".*", re.escape(endpoint))
|
|
73
|
+
return NewsSource.objects.create(**data, endpoint=endpoint)
|
wbnews/models/utils.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from contextlib import suppress
|
|
2
|
+
from urllib.parse import urlparse
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def endpoint_to_author(endpoint: str) -> str:
|
|
6
|
+
author = endpoint
|
|
7
|
+
if "@" in endpoint: # simplist way to check if the endpoint is an email address
|
|
8
|
+
author = author.replace("\\", "").split("@")[-1].split(".")
|
|
9
|
+
if len(author) > 1:
|
|
10
|
+
author = ".".join(author[:-1])
|
|
11
|
+
else: # otherwise we consider it's a valid url and we extract only the domain part
|
|
12
|
+
with suppress(ValueError, IndexError):
|
|
13
|
+
author = urlparse(author).netloc.split(".")[-2]
|
|
14
|
+
|
|
15
|
+
return author.replace("_", " ").title()
|
wbnews/serializers.py
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
from django.utils.translation import gettext_lazy as _
|
|
2
2
|
from rest_framework.reverse import reverse
|
|
3
3
|
from wbcore import serializers as wb_serializers
|
|
4
|
+
from wbcore.content_type.serializers import (
|
|
5
|
+
ContentTypeRepresentationSerializer,
|
|
6
|
+
DynamicObjectIDRepresentationSerializer,
|
|
7
|
+
)
|
|
4
8
|
|
|
5
|
-
from .models import News, NewsSource
|
|
9
|
+
from .models import News, NewsRelationship, NewsSource
|
|
6
10
|
|
|
7
11
|
|
|
8
12
|
class SourceRepresentationSerializer(wb_serializers.RepresentationSerializer):
|
|
@@ -67,15 +71,52 @@ class NewsModelSerializer(wb_serializers.ModelSerializer):
|
|
|
67
71
|
|
|
68
72
|
|
|
69
73
|
class NewsRelationshipModelSerializer(wb_serializers.ModelSerializer):
|
|
74
|
+
source = wb_serializers.PrimaryKeyCharField(read_only=True)
|
|
70
75
|
_source = SourceRepresentationSerializer(source="source")
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
76
|
+
title = wb_serializers.TextField(read_only=True, label=_("Title"))
|
|
77
|
+
description = wb_serializers.TextField(read_only=True, label=_("Description"))
|
|
78
|
+
summary = wb_serializers.TextField(read_only=True, label=_("Summary"))
|
|
79
|
+
datetime = wb_serializers.DateTimeField(read_only=True, label=_("Date"))
|
|
80
|
+
_content_type = ContentTypeRepresentationSerializer(source="content_type")
|
|
81
|
+
object_id = wb_serializers.CharField(label="Linked Object", required=False)
|
|
82
|
+
_object_id = DynamicObjectIDRepresentationSerializer(
|
|
83
|
+
content_type_field_name="content_type",
|
|
84
|
+
source="object_id",
|
|
85
|
+
optional_get_parameters={"content_type": "content_type"},
|
|
86
|
+
depends_on=[{"field": "content_type", "options": {}}],
|
|
87
|
+
filter_params={
|
|
88
|
+
"is_security": True
|
|
89
|
+
}, # TODO needs to find a way to not create a dependency to the wbfdm module here
|
|
90
|
+
)
|
|
91
|
+
news = wb_serializers.PrimaryKeyRelatedField(
|
|
92
|
+
queryset=News.objects.all(), read_only=lambda view: not view.new_mode, label=_("News")
|
|
93
|
+
)
|
|
94
|
+
_news = NewsRepresentationSerializer(source="news")
|
|
95
|
+
|
|
96
|
+
def validate(self, data):
|
|
97
|
+
if view := self.context["view"]:
|
|
98
|
+
if view.object_id:
|
|
99
|
+
data["object_id"] = view.object_id
|
|
100
|
+
if view.content_type:
|
|
101
|
+
data["content_type"] = view.content_type
|
|
102
|
+
return super().validate(data)
|
|
74
103
|
|
|
75
104
|
class Meta:
|
|
76
|
-
model =
|
|
105
|
+
model = NewsRelationship
|
|
106
|
+
read_only_fields = (
|
|
107
|
+
"content_object_repr",
|
|
108
|
+
"datetime",
|
|
109
|
+
"title",
|
|
110
|
+
"description",
|
|
111
|
+
"summary",
|
|
112
|
+
"content_type",
|
|
113
|
+
"_content_type",
|
|
114
|
+
)
|
|
77
115
|
fields = (
|
|
78
116
|
"id",
|
|
117
|
+
"news",
|
|
118
|
+
"_news",
|
|
119
|
+
"content_object_repr",
|
|
79
120
|
"datetime",
|
|
80
121
|
"sentiment",
|
|
81
122
|
"analysis",
|
|
@@ -85,4 +126,9 @@ class NewsRelationshipModelSerializer(wb_serializers.ModelSerializer):
|
|
|
85
126
|
"summary",
|
|
86
127
|
"source",
|
|
87
128
|
"_source",
|
|
129
|
+
"content_type",
|
|
130
|
+
"_content_type",
|
|
131
|
+
"object_id",
|
|
132
|
+
"_object_id",
|
|
133
|
+
"_additional_resources",
|
|
88
134
|
)
|
wbnews/tasks.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from datetime import date, timedelta
|
|
2
|
+
|
|
3
|
+
from celery import shared_task
|
|
4
|
+
|
|
5
|
+
from wbnews.models import News
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@shared_task()
|
|
9
|
+
def handle_daily_news_duplicates(
|
|
10
|
+
task_date: date | None = None,
|
|
11
|
+
day_interval: int = 7,
|
|
12
|
+
):
|
|
13
|
+
if not task_date:
|
|
14
|
+
task_date = date.today()
|
|
15
|
+
|
|
16
|
+
News.handle_duplicates(task_date - timedelta(days=day_interval), task_date + timedelta(days=day_interval))
|
|
File without changes
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from unittest.mock import PropertyMock, patch
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from wbnews.import_export.parsers.emails.utils import EmlContentParser
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TestEmlContentParser:
|
|
9
|
+
@pytest.fixture
|
|
10
|
+
def content_parser(self):
|
|
11
|
+
parser = EmlContentParser(b"")
|
|
12
|
+
parser.message = {"From": "main@acme.com"}
|
|
13
|
+
return parser
|
|
14
|
+
|
|
15
|
+
@patch.object(EmlContentParser, "text", new_callable=PropertyMock)
|
|
16
|
+
def test_source_from_in_text(self, mock_text, content_parser):
|
|
17
|
+
mock_text.return_value = (
|
|
18
|
+
"some random email content with a From field From: source name <email@test.com> and the rest of the email"
|
|
19
|
+
)
|
|
20
|
+
assert content_parser.source == {"title": "Source Name", "endpoint": "email@test.com", "type": "EMAIL"}
|
|
21
|
+
|
|
22
|
+
@patch.object(EmlContentParser, "text", new_callable=PropertyMock)
|
|
23
|
+
def test_source_from_in_text_alt(self, mock_text, content_parser):
|
|
24
|
+
mock_text.return_value = "some random email content without a From field"
|
|
25
|
+
assert content_parser.source == {"title": "Acme.Com", "endpoint": "main@acme.com", "type": "EMAIL"}
|
wbnews/tests/test_models.py
CHANGED
|
@@ -1,4 +1,13 @@
|
|
|
1
|
+
from datetime import timedelta, timezone
|
|
2
|
+
from unittest.mock import patch
|
|
3
|
+
|
|
1
4
|
import pytest
|
|
5
|
+
from django.utils import timezone as django_timezone
|
|
6
|
+
from faker import Faker
|
|
7
|
+
|
|
8
|
+
from wbnews.models import News, NewsSource
|
|
9
|
+
|
|
10
|
+
fake = Faker()
|
|
2
11
|
|
|
3
12
|
|
|
4
13
|
@pytest.mark.django_db
|
|
@@ -7,9 +16,65 @@ class TestSource:
|
|
|
7
16
|
def test_str(self, news_source):
|
|
8
17
|
assert str(news_source) == f"{news_source.title}"
|
|
9
18
|
|
|
19
|
+
def test_source_dict_to_model(self, news_source_factory):
|
|
20
|
+
ns1 = news_source_factory.create()
|
|
21
|
+
ns2 = news_source_factory.create()
|
|
22
|
+
|
|
23
|
+
assert NewsSource.source_dict_to_model({"id": ns1.id, "identifier": ns2.identifier}) == ns1 # priority to "id"
|
|
24
|
+
assert (
|
|
25
|
+
NewsSource.source_dict_to_model({"endpoint": ns1.endpoint, "identifier": ns2.identifier}) == ns2
|
|
26
|
+
) # priority to "identifier"
|
|
27
|
+
assert NewsSource.source_dict_to_model({"endpoint": ns2.endpoint}) == ns2 # exact match on endpoint
|
|
28
|
+
|
|
29
|
+
ns1.endpoint = ".*@test.com"
|
|
30
|
+
ns1.save()
|
|
31
|
+
assert NewsSource.source_dict_to_model({"endpoint": "abc@test.com"}) == ns1 # regex match on endpoint
|
|
32
|
+
|
|
33
|
+
new_source = NewsSource.source_dict_to_model({"endpoint": "abc@main_source.com", "title": "New Source"})
|
|
34
|
+
assert new_source not in [ns1, ns2]
|
|
35
|
+
assert new_source.endpoint == r".*@main_source\.com"
|
|
36
|
+
assert new_source.title == "New Source"
|
|
37
|
+
assert new_source.author == "Main Source"
|
|
38
|
+
|
|
10
39
|
|
|
11
40
|
@pytest.mark.django_db
|
|
12
41
|
class TestNews:
|
|
13
42
|
@pytest.mark.parametrize("news__title", ["new1"])
|
|
14
43
|
def test_str(self, news):
|
|
15
44
|
assert str(news) == f"{news.title} ({news.source.title})"
|
|
45
|
+
|
|
46
|
+
def test_mark_as_deplicates_not_in_default_queryset(self, news):
|
|
47
|
+
assert set(News.objects.all()) == {news}
|
|
48
|
+
|
|
49
|
+
def test_get_default_guid(self):
|
|
50
|
+
assert News.get_default_guid("This is a title", None) == "this-is-a-title"
|
|
51
|
+
assert (
|
|
52
|
+
News.get_default_guid("This is a title", "http://mylink.com") == "http://mylink.com"
|
|
53
|
+
) # link takes precendence
|
|
54
|
+
assert News.get_default_guid("a" * 24, None, max_length=20) == "a" * 20
|
|
55
|
+
|
|
56
|
+
def test_future_news(self, news_factory):
|
|
57
|
+
# ensure a future datetime always default to now
|
|
58
|
+
now = django_timezone.now()
|
|
59
|
+
future_news = news_factory.create(datetime=now + timedelta(days=1))
|
|
60
|
+
assert (future_news.datetime - now).seconds < 1 # we do that to account for clock difference
|
|
61
|
+
|
|
62
|
+
@patch("wbnews.models.news.detect_near_duplicates")
|
|
63
|
+
def test_handle_duplicates(self, mock_fct, news_factory):
|
|
64
|
+
val_date = fake.date_time(tzinfo=timezone.utc)
|
|
65
|
+
n0 = news_factory.create(
|
|
66
|
+
datetime=val_date - timedelta(days=1)
|
|
67
|
+
) # we exclude this news from the duplicate search
|
|
68
|
+
n1 = news_factory.create(datetime=val_date)
|
|
69
|
+
n2 = news_factory.create(datetime=val_date)
|
|
70
|
+
n3 = news_factory.create(datetime=val_date)
|
|
71
|
+
|
|
72
|
+
mock_fct.return_value = [
|
|
73
|
+
n0.id,
|
|
74
|
+
n3.id,
|
|
75
|
+
] # n0 is considered as duplicate but does not fall within the specified daterange so it will not be marked
|
|
76
|
+
News.handle_duplicates(val_date, val_date)
|
|
77
|
+
|
|
78
|
+
n3.refresh_from_db()
|
|
79
|
+
assert n3.mark_as_duplicate is True
|
|
80
|
+
assert set(News.objects.all()) == {n0, n1, n2}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
from wbnews.models.utils import endpoint_to_author
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def test_endpoint_to_author():
|
|
5
|
+
assert endpoint_to_author("test@test_test\\.com") == "Test Test"
|
|
6
|
+
assert endpoint_to_author("http://somesubdomain.domain.com") == "Domain"
|
|
7
|
+
assert endpoint_to_author("test") == "Test"
|
wbnews/urls.py
CHANGED
|
@@ -22,9 +22,4 @@ urlpatterns = [
|
|
|
22
22
|
views.NewsModelViewSet.as_view({"get": "list"}),
|
|
23
23
|
name="news_content_object",
|
|
24
24
|
),
|
|
25
|
-
path(
|
|
26
|
-
"contentnewsrelationship/<int:content_type>/<int:content_id>/",
|
|
27
|
-
views.NewsRelationshipModelViewSet.as_view({"get": "list"}),
|
|
28
|
-
name="news_relationship_content_object",
|
|
29
|
-
),
|
|
30
25
|
]
|
wbnews/utils.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
from django.utils.html import strip_tags
|
|
6
|
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
|
7
|
+
from sklearn.metrics.pairwise import cosine_similarity
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger("news")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _get_similarity_matrix_df(data: dict[int, str]) -> pd.DataFrame:
|
|
13
|
+
# Convert texts to TF-IDF vectors
|
|
14
|
+
ids, texts = zip(*data.items(), strict=False)
|
|
15
|
+
vectorizer = TfidfVectorizer()
|
|
16
|
+
tfidf_matrix = vectorizer.fit_transform(texts)
|
|
17
|
+
# Compute pairwise cosine similarity...
|
|
18
|
+
similarity_matrix = cosine_similarity(tfidf_matrix)
|
|
19
|
+
# convert the matrix into a proper dataframe
|
|
20
|
+
return pd.DataFrame(similarity_matrix, index=ids, columns=ids)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def detect_near_duplicates(data: dict[int, str], threshold: float = 0.9) -> list[int]:
|
|
24
|
+
"""
|
|
25
|
+
Detects near-duplicate articles based on TF-IDF & Cosine Similarity.
|
|
26
|
+
|
|
27
|
+
Parameters:
|
|
28
|
+
- data (dict[int, str]): dictionary of new id with their respective content
|
|
29
|
+
- threshold (float): Similarity threshold (default = 0.9).
|
|
30
|
+
|
|
31
|
+
Returns:
|
|
32
|
+
- List of duplicated ids
|
|
33
|
+
"""
|
|
34
|
+
if len(data.keys()) < 2:
|
|
35
|
+
return []
|
|
36
|
+
logger.info(f"Processing {len(data.keys())} news")
|
|
37
|
+
# Cleanup step
|
|
38
|
+
clean_data = {}
|
|
39
|
+
for _id, text in data.items():
|
|
40
|
+
clean_data[_id] = strip_tags(text)
|
|
41
|
+
|
|
42
|
+
# get similarity matrix
|
|
43
|
+
df = _get_similarity_matrix_df(data)
|
|
44
|
+
|
|
45
|
+
# Replace the lower matrix triangle with NaN
|
|
46
|
+
df = df.where(np.triu(np.ones(df.shape)).astype(bool))
|
|
47
|
+
# melt the symmetrical matrix into a key value store
|
|
48
|
+
df = df.stack().reset_index(name="value")
|
|
49
|
+
# remove duplicate pair with same id (expected to be 1.0)
|
|
50
|
+
df = df[df["level_0"] != df["level_1"]]
|
|
51
|
+
# get duplicates candidates
|
|
52
|
+
df = df[df["value"] > threshold]
|
|
53
|
+
# return only one side of the duplicate pair
|
|
54
|
+
duplicate_ids = df["level_1"].unique().tolist()
|
|
55
|
+
logger.info(f"{len(duplicate_ids)} duplicated news found")
|
|
56
|
+
|
|
57
|
+
return duplicate_ids
|
wbnews/viewsets/__init__.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
from .buttons import NewsButtonConfig
|
|
2
2
|
from .display import NewsDisplayConfig, NewsSourceDisplayConfig, SourceDisplayConfig
|
|
3
|
-
from .endpoints import NewsEndpointConfig, NewsSourceEndpointConfig
|
|
3
|
+
from .endpoints import NewsEndpointConfig, NewsSourceEndpointConfig, NewsRelationshipEndpointConfig
|
|
4
4
|
from .menu import NEWS_MENUITEM, NEWSSOURCE_MENUITEM
|
|
5
5
|
from .titles import NewsSourceModelTitleConfig, NewsTitleConfig, SourceModelTitleConfig
|
|
6
6
|
from .views import (
|
wbnews/viewsets/buttons.py
CHANGED
|
@@ -2,6 +2,7 @@ from django.dispatch import receiver
|
|
|
2
2
|
from django.utils.translation import gettext as _
|
|
3
3
|
from rest_framework.reverse import reverse
|
|
4
4
|
from wbcore.contrib.icons import WBIcon
|
|
5
|
+
from wbcore.enums import RequestType
|
|
5
6
|
from wbcore.metadata.configs import buttons as bt
|
|
6
7
|
from wbcore.metadata.configs.buttons.view_config import ButtonViewConfig
|
|
7
8
|
from wbcore.signals.instance_buttons import add_extra_button
|
|
@@ -9,15 +10,33 @@ from wbcore.signals.instance_buttons import add_extra_button
|
|
|
9
10
|
|
|
10
11
|
class NewsButtonConfig(ButtonViewConfig):
|
|
11
12
|
def get_custom_list_instance_buttons(self):
|
|
12
|
-
|
|
13
|
+
buttons = set()
|
|
14
|
+
buttons.add(bt.HyperlinkButton(key="open_link", label=_("Open News"), icon=WBIcon.LINK.icon))
|
|
15
|
+
if self.request.user.is_superuser and (pk := self.view.kwargs.get("pk")):
|
|
16
|
+
buttons.add(
|
|
17
|
+
bt.ActionButton(
|
|
18
|
+
method=RequestType.PATCH,
|
|
19
|
+
identifiers=("wbnews:newsrelationship",),
|
|
20
|
+
endpoint=reverse("wbnews:news-refreshrelationship", args=[pk]),
|
|
21
|
+
action_label=_("Reset relationships"),
|
|
22
|
+
label=_("Reset relationships"),
|
|
23
|
+
icon=WBIcon.REGENERATE.icon,
|
|
24
|
+
title=_("Reset relationships"),
|
|
25
|
+
)
|
|
26
|
+
)
|
|
27
|
+
return buttons
|
|
13
28
|
|
|
14
29
|
def get_custom_instance_buttons(self):
|
|
15
30
|
return self.get_custom_list_instance_buttons()
|
|
16
31
|
|
|
17
32
|
|
|
33
|
+
class NewsRelationshipButtonConfig(ButtonViewConfig):
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
|
|
18
37
|
@receiver(add_extra_button)
|
|
19
38
|
def add_new_extra_button(sender, instance, request, view, pk=None, **kwargs):
|
|
20
39
|
if instance and pk and view:
|
|
21
40
|
content_type = view.get_content_type()
|
|
22
|
-
endpoint = reverse("wbnews:
|
|
41
|
+
endpoint = f'{reverse("wbnews:newsrelationship-list", args=[], request=request)}?content_type={content_type.id}&object_id={pk}'
|
|
23
42
|
return bt.WidgetButton(endpoint=endpoint, label="News", icon=WBIcon.NEWSPAPER.icon)
|
wbnews/viewsets/display.py
CHANGED
|
@@ -10,6 +10,8 @@ from wbcore.metadata.configs.display.instance_display.shortcuts import (
|
|
|
10
10
|
from wbcore.metadata.configs.display.instance_display.utils import repeat_field
|
|
11
11
|
from wbcore.metadata.configs.display.view_config import DisplayViewConfig
|
|
12
12
|
|
|
13
|
+
from wbnews.models import NewsRelationship
|
|
14
|
+
|
|
13
15
|
|
|
14
16
|
class SourceDisplayConfig(DisplayViewConfig):
|
|
15
17
|
def get_list_display(self) -> Optional[dp.ListDisplay]:
|
|
@@ -63,23 +65,38 @@ class NewsDisplayConfig(DisplayViewConfig):
|
|
|
63
65
|
|
|
64
66
|
class NewsRelationshipDisplayConfig(DisplayViewConfig):
|
|
65
67
|
def get_instance_display(self) -> Display:
|
|
68
|
+
if self.new_mode:
|
|
69
|
+
return create_simple_display(
|
|
70
|
+
[
|
|
71
|
+
["news", "news"],
|
|
72
|
+
["important", "sentiment"],
|
|
73
|
+
["analysis", "analysis"],
|
|
74
|
+
]
|
|
75
|
+
)
|
|
76
|
+
|
|
66
77
|
return create_simple_display(
|
|
67
78
|
[
|
|
68
|
-
["
|
|
69
|
-
["
|
|
70
|
-
[
|
|
71
|
-
|
|
79
|
+
["news", "news"],
|
|
80
|
+
["content_type", "object_id"],
|
|
81
|
+
[
|
|
82
|
+
"important",
|
|
83
|
+
"sentiment",
|
|
84
|
+
],
|
|
85
|
+
["analysis", "analysis"],
|
|
86
|
+
["summary", "summary"],
|
|
87
|
+
["description", "description"],
|
|
72
88
|
]
|
|
73
89
|
)
|
|
74
90
|
|
|
75
91
|
def get_list_display(self) -> Optional[dp.ListDisplay]:
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
92
|
+
fields = (
|
|
93
|
+
[dp.Field(key="content_object_repr", label=_("Linked Object"))]
|
|
94
|
+
if self.view.object_id is None and self.view.content_type is None
|
|
95
|
+
else []
|
|
96
|
+
)
|
|
80
97
|
|
|
81
|
-
|
|
82
|
-
|
|
98
|
+
fields.extend(
|
|
99
|
+
[
|
|
83
100
|
dp.Field(key="datetime", label=_("Datetime")),
|
|
84
101
|
dp.Field(key="analysis", label=_("Analysis")),
|
|
85
102
|
dp.Field(key="title", label=_("Title")),
|
|
@@ -87,26 +104,22 @@ class NewsRelationshipDisplayConfig(DisplayViewConfig):
|
|
|
87
104
|
dp.Field(key="description", label=_("Description")),
|
|
88
105
|
dp.Field(key="important", label=_("Important")),
|
|
89
106
|
dp.Field(key="source", label=_("Source")),
|
|
90
|
-
]
|
|
107
|
+
]
|
|
108
|
+
)
|
|
109
|
+
return dp.ListDisplay(
|
|
110
|
+
fields=fields,
|
|
91
111
|
formatting=[
|
|
92
112
|
dp.Formatting(
|
|
93
113
|
column="sentiment",
|
|
94
114
|
formatting_rules=[
|
|
95
|
-
dp.FormattingRule(condition=("==",
|
|
96
|
-
|
|
97
|
-
dp.FormattingRule(condition=("==", 2), style={"backgroundColor": SLIGHTLY_NEGATIVE}),
|
|
98
|
-
dp.FormattingRule(condition=("==", 1), style={"backgroundColor": NEGATIVE}),
|
|
115
|
+
dp.FormattingRule(condition=("==", s.value), style={"backgroundColor": s.get_color()})
|
|
116
|
+
for s in NewsRelationship.SentimentChoices
|
|
99
117
|
],
|
|
100
118
|
)
|
|
101
119
|
],
|
|
102
120
|
legends=[
|
|
103
121
|
dp.Legend(
|
|
104
|
-
items=[
|
|
105
|
-
dp.LegendItem(icon=POSITIVE, label=_("Positive")),
|
|
106
|
-
dp.LegendItem(icon=SLIGHTLY_POSITIVE, label=_("Slightly Positive")),
|
|
107
|
-
dp.LegendItem(icon=SLIGHTLY_NEGATIVE, label=_("Slightly Negative")),
|
|
108
|
-
dp.LegendItem(icon=NEGATIVE, label=_("Negative")),
|
|
109
|
-
]
|
|
122
|
+
items=[dp.LegendItem(icon=s.get_color(), label=s.label) for s in NewsRelationship.SentimentChoices]
|
|
110
123
|
)
|
|
111
124
|
],
|
|
112
125
|
)
|
wbnews/viewsets/endpoints.py
CHANGED
|
@@ -1,18 +1,34 @@
|
|
|
1
1
|
from rest_framework.reverse import reverse
|
|
2
2
|
from wbcore.metadata.configs.endpoints import EndpointViewConfig
|
|
3
|
+
from wbcore.utils.urls import get_urlencode_endpoint
|
|
3
4
|
|
|
4
5
|
|
|
5
6
|
class NewsEndpointConfig(EndpointViewConfig):
|
|
6
7
|
def get_endpoint(self, **kwargs):
|
|
7
8
|
return None
|
|
8
9
|
|
|
9
|
-
def get_list_endpoint(self, **kwargs):
|
|
10
|
-
return reverse("wbnews:news-list", request=self.request)
|
|
11
|
-
|
|
12
10
|
def get_instance_endpoint(self, **kwargs):
|
|
13
|
-
return self.
|
|
11
|
+
return reverse("wbnews:news-list", request=self.request)
|
|
14
12
|
|
|
15
13
|
|
|
16
14
|
class NewsSourceEndpointConfig(NewsEndpointConfig):
|
|
17
|
-
|
|
18
|
-
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class NewsRelationshipEndpointConfig(EndpointViewConfig):
|
|
19
|
+
def get_endpoint(self, **kwargs):
|
|
20
|
+
return reverse("wbnews:newsrelationship-list", args=[], request=self.request)
|
|
21
|
+
|
|
22
|
+
def get_create_endpoint(self, **kwargs):
|
|
23
|
+
params = {}
|
|
24
|
+
if ct := self.view.content_type:
|
|
25
|
+
params["content_type"] = ct.id
|
|
26
|
+
if object_id := self.view.object_id:
|
|
27
|
+
params["object_id"] = object_id
|
|
28
|
+
return get_urlencode_endpoint(self.get_endpoint(**kwargs), params)
|
|
29
|
+
|
|
30
|
+
# def get_instance_endpoint(self, **kwargs):
|
|
31
|
+
# return reverse("wbnews:news-list", args=[], request=self.request)
|
|
32
|
+
#
|
|
33
|
+
# def get_update_endpoint(self, **kwargs):
|
|
34
|
+
# return self.get_endpoint(**kwargs)
|
wbnews/viewsets/menu.py
CHANGED
|
@@ -7,6 +7,12 @@ NEWS_MENUITEM = MenuItem(
|
|
|
7
7
|
endpoint="wbnews:news-list",
|
|
8
8
|
permission=ItemPermission(permissions=["wbnews.view_news"]),
|
|
9
9
|
)
|
|
10
|
+
NEWSRELATIONSHIP_MENUITEM = MenuItem(
|
|
11
|
+
label=_("News Relationships"),
|
|
12
|
+
endpoint="wbnews:newsrelationship-list",
|
|
13
|
+
permission=ItemPermission(permissions=["wbnews.view_news"]),
|
|
14
|
+
)
|
|
15
|
+
|
|
10
16
|
NEWSSOURCE_MENUITEM = MenuItem(
|
|
11
17
|
label=_("Sources"),
|
|
12
18
|
endpoint="wbnews:source-list",
|
wbnews/viewsets/titles.py
CHANGED
|
@@ -37,4 +37,8 @@ class NewsRelationshipTitleConfig(TitleViewConfig):
|
|
|
37
37
|
return _("News Article")
|
|
38
38
|
|
|
39
39
|
def get_instance_title(self):
|
|
40
|
-
|
|
40
|
+
try:
|
|
41
|
+
instance = self.view.get_object()
|
|
42
|
+
return str(instance)
|
|
43
|
+
except AssertionError:
|
|
44
|
+
return _("News Article")
|