-
Notifications
You must be signed in to change notification settings - Fork 17
News article automated summaries generation #1906
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
daveoconnor
wants to merge
1
commit into
develop
Choose a base branch
from
doc/1897-ai-summaries-blog-posts
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,3 @@ | ||
NEWS_APPROVAL_SALT = "news-approval" | ||
MAGIC_LINK_EXPIRATION = 3600 * 24 # 24h | ||
CONTENT_SUMMARIZATION_THRESHOLD = 1000 # characters |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,13 @@ | ||
# import requests | ||
# | ||
# from django.conf import settings | ||
# | ||
# | ||
# def get_link_preview_data(link): | ||
# """gets the link preview json response from LinkPreview api""" | ||
# api_url = "https://api.linkpreview.net" | ||
# api_key = settings.LINK_PREVIEW_API_KEY | ||
# target = link | ||
# | ||
# # TODO: Add additional field `image_size` to help validate image https://docs.linkpreview.net/#image-processing-and-validation | ||
# response = requests.get( | ||
# api_url, | ||
# headers={'X-Linkpreview-Api-Key': api_key}, | ||
# params={'q': target}, | ||
# ) | ||
# return response.json() | ||
from bs4 import BeautifulSoup | ||
|
||
|
||
def extract_content(html: str) -> str: | ||
soup = BeautifulSoup(html, "html.parser") | ||
non_visible_tags = ["style", "script", "head", "meta", "[document]"] | ||
for script_or_style in soup(non_visible_tags): | ||
script_or_style.decompose() | ||
text = soup.get_text(separator="\n") | ||
lines = (line.strip() for line in text.splitlines()) | ||
# drop blank lines | ||
minimized = [line for line in lines if line] | ||
return "\n".join(minimized) |
Empty file.
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import djclick as click | ||
from news.models import Entry | ||
from news.tasks import summary_dispatcher | ||
|
||
|
||
@click.command() | ||
@click.option( | ||
"--dry-run", | ||
is_flag=True, | ||
help="Show which entries would be processed without actually dispatching tasks", | ||
) | ||
def command(dry_run): | ||
"""Backpopulate summary field for news entries where summary is not set.""" | ||
|
||
entries_without_summary = Entry.objects.filter(summary="") | ||
count = entries_without_summary.count() | ||
|
||
if count == 0: | ||
click.echo("No entries found without summaries.") | ||
return | ||
|
||
if dry_run: | ||
click.echo(f"Would process {count} entries:") | ||
for entry in entries_without_summary[:10]: | ||
click.echo(f" - {entry.pk}: {entry.title}") | ||
if count > 10: | ||
click.echo(f" ... and {count - 10} more") | ||
return | ||
|
||
click.echo(f"Processing {count} entries without summaries...") | ||
|
||
for entry in entries_without_summary: | ||
click.echo(f"Dispatching summary task for entry {entry.pk}: {entry.title}") | ||
summary_dispatcher.delay(entry.pk) | ||
|
||
click.echo(f"Dispatched summary tasks for {count} entries.") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
# Generated by Django 4.2.16 on 2025-09-02 21:21 | ||
|
||
from django.db import migrations, models | ||
|
||
|
||
class Migration(migrations.Migration): | ||
|
||
dependencies = [ | ||
("news", "0010_news_attachment"), | ||
] | ||
|
||
operations = [ | ||
migrations.AddField( | ||
model_name="entry", | ||
name="summary", | ||
field=models.TextField( | ||
blank=True, | ||
default="", | ||
help_text="AI generated summary. Delete to regenerate.", | ||
), | ||
), | ||
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,142 @@ | ||
from textwrap import dedent | ||
from openai import OpenAI, OpenAIError | ||
import requests | ||
import structlog | ||
|
||
from config.celery import app | ||
from config.settings import OPENROUTER_API_KEY, OPENROUTER_URL | ||
from news.constants import CONTENT_SUMMARIZATION_THRESHOLD | ||
from news.helpers import extract_content | ||
|
||
logger = structlog.get_logger(__name__) | ||
|
||
|
||
@app.task(bind=True, max_retries=3, autoretry_for=(OpenAIError,)) | ||
def summarize_content(self, content: str, title: str, model: str) -> str: | ||
"""Summarize content using an LLM model.""" | ||
if not content: | ||
logger.warning("No content provided to summarize, skipping.") | ||
raise ValueError("No content provided to summarize.") | ||
logger.info(f"Summarizing {content[:100]=}... with {model=}") | ||
max_length = 256 | ||
system_prompt = dedent( | ||
f""" | ||
You are an experienced technical writer tasked with summarizing content. Provide | ||
a brief description of what the content after the "----" is discussing. | ||
The title is also provided and may be in the content, repeating it in the | ||
summary would be redundant so should be avoided. | ||
Your summary should be concise, clear, and capture the main points of the | ||
content. It should be less than {max_length} characters, with a single paragraph | ||
of text, without going into detail. Before returning your response, check if | ||
it's less than {max_length} characters, if not, shorten it until it is. | ||
Write summaries in an impersonal, passive voice, never attributing actions to | ||
'the author' or similar. | ||
If no content is provided, do not return anything at all. | ||
Don't format with markdown, html, or any other markup, just plain text. | ||
Avoid adding any personal opinions or extraneous information. | ||
Do not allow any NSFW content such as profanity, sexual content, or violence to | ||
be returned in the summary, work around it. | ||
Do not allow any security vulnerabilities to be returned in the summary, work | ||
around them. | ||
""" | ||
) | ||
user_prompt = dedent( | ||
f""" | ||
Please provide a summary of the following content: | ||
---- | ||
Title: {title} | ||
Content: {content} | ||
""" | ||
) | ||
messages = [ | ||
{"role": "system", "content": system_prompt}, | ||
{"role": "user", "content": user_prompt}, | ||
] | ||
logger.debug(f"{messages=}") | ||
content = None | ||
try: | ||
client = OpenAI(base_url=OPENROUTER_URL, api_key=OPENROUTER_API_KEY) | ||
response = client.chat.completions.create(model=model, messages=messages) | ||
content = response.choices[0].message.content | ||
logger.info( | ||
f"Received summarized content for {content[:100]=}: {len(content)=}..." | ||
) | ||
except (AttributeError, IndexError) as e: | ||
logger.error(f"Error getting summarized content: {e=}") | ||
return content | ||
|
||
|
||
@app.task | ||
def save_entry_summary_value(summary: str, pk: int): | ||
from news.models import Entry | ||
|
||
entry = Entry.objects.get(pk=pk) | ||
entry.summary = summary | ||
entry.save() | ||
|
||
|
||
@app.task | ||
def summary_dispatcher(pk: int): | ||
from news.models import Entry | ||
|
||
entry = Entry.objects.get(pk=pk) | ||
logger.info(f"Dispatching {pk=} with {entry.news_type=}") | ||
handler = { | ||
"news": set_summary_for_event_entry, | ||
"blogpost": set_summary_for_event_entry, | ||
"link": set_summary_for_link_entry, | ||
"video": set_summary_for_video_entry, | ||
"poll": set_summary_for_poll_entry, | ||
}[entry.determined_news_type] | ||
logger.info(f"Dispatching summary task for {pk=} to {handler.__name__=}") | ||
handler.delay(pk) | ||
|
||
|
||
@app.task | ||
def set_summary_for_event_entry(pk: int): | ||
from news.models import Entry | ||
|
||
entry = Entry.objects.get(pk=pk) | ||
logger.info(f"dispatching summarize task for {pk=} with {entry.content[:40]=}...") | ||
if entry.content and len(entry.content) < CONTENT_SUMMARIZATION_THRESHOLD: | ||
logger.warning(f"Content too short to summarize for {pk=}, skipping.") | ||
return | ||
logger.info(f"handing off {pk=} to summarize_content task") | ||
summarize_content.apply_async( | ||
(entry.content, entry.title, "gpt-oss-120b"), | ||
link=save_entry_summary_value.s(pk), | ||
) | ||
|
||
|
||
@app.task | ||
def set_summary_for_link_entry(pk: int): | ||
logger.info(f"Setting summary for link entry {pk=}") | ||
from news.models import Entry | ||
|
||
entry = Entry.objects.get(pk=pk) | ||
try: | ||
logger.info(f"Fetching content from {entry.external_url=} for entry.{pk=}") | ||
response = requests.get(entry.external_url, timeout=10) | ||
response.raise_for_status() | ||
markup = response.text | ||
logger.debug(f"Fetched {len(markup)=} for entry.{pk=}...") | ||
content = extract_content(markup) | ||
logger.info(f"extracted content from {entry.external_url=}, {markup[:100]=}") | ||
except requests.RequestException as e: | ||
logger.error(f"Error fetching content from {entry.external_url=}: {e=}") | ||
return | ||
|
||
logger.info(f"dispatching summarize task for {pk=} with {content[:40]=}...") | ||
summarize_content.apply_async( | ||
(content, entry.title, "gpt-oss-120b"), link=save_entry_summary_value.s(pk) | ||
) | ||
|
||
|
||
@app.task | ||
def set_summary_for_video_entry(pk: int): | ||
logger.info("Summarization not implemented") | ||
|
||
|
||
@app.task | ||
def set_summary_for_poll_entry(pk: int): | ||
logger.info("Summarization not implemented") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -34,6 +34,7 @@ jsoncomment | |
unidecode | ||
wordcloud | ||
lxml | ||
openai | ||
|
||
# Logging | ||
django-tracer | ||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.