| Title: | Early Detection of Public Health Threats from Social Media Data |
| Version: | 4.2.2 |
| Description: | It allows you to automatically monitor trends of social media messages by time, place and topic aiming at detecting public health threats early through the detection of signals (i.e., an unusual increase in the number of messages per time, topic and location). It was designed to focus on infectious diseases, and it can be extended to all hazards or other fields of study by modifying the topics and keywords. More information on the original package 'epitweetr' is available in the peer-review publication Espinosa et al. (2022) <doi:10.2807/1560-7917.ES.2022.27.39.2200177>. |
| License: | EUPL version 1.1 | EUPL version 1.2 [expanded from: EUPL] |
| URL: | https://github.com/EU-ECDC/episomer |
| BugReports: | https://github.com/EU-ECDC/episomer/issues |
| Encoding: | UTF-8 |
| Imports: | dplyr, curl, crayon, DT, emayili, future, httr, htmltools, urltools, jsonlite, keyring, ggplot2, janitor, magrittr, parallel, plotly, processx, readxl, rlang, rmarkdown, rnaturalearthdata, openxlsx, shiny, stringr, stats, tibble, tools, utils, xtable, httr2, lubridate, sf, cli, askpass, bit64, shinyjs, zip |
| Suggests: | knitr, taskscheduleR, testthat (≥ 3.0.0), withr |
| VignetteBuilder: | knitr |
| Config/testthat/edition: | 3 |
| Config/roxygen2/version: | 8.0.0 |
| RoxygenNote: | 7.3.3 |
| NeedsCompilation: | no |
| Packaged: | 2026-11-26 12:30:55 UTC; yohann_mansiaux |
| Author: | Laura Espinosa |
| Maintainer: | Laura Espinosa <laura.espinosa@ecdc.europa.eu> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-26 14:50:02 UTC |
Pipe operator
Description
See magrittr::%>% for details.
Usage
lhs %>% rhs
Arguments
lhs |
A value or the magrittr placeholder. |
rhs |
A function call using the magrittr semantics. |
Value
The result of calling 'rhs(lhs)'.
Create new social media template files, so a developer can extend episomer and support a new social media. this function has to be called within episomer subfolder containing thr R subfolder after executing devtools::load_all()
Description
Create new social media template files, so a developer can extend episomer and support a new social media. this function has to be called within episomer subfolder containing thr R subfolder after executing devtools::load_all()
Usage
add_new_social_media(social_media, social_media_ref = "bluesky")
Arguments
social_media |
Name of the new social media |
social_media_ref |
Name of the reference social media |
Value
TRUE, called for side effects (creation of new social media files).
check the current bluesky token validity
Description
check the current bluesky token validity
Usage
bluesky_check_token_validity(
access_jwt,
search_url = "https://bsky.social/xrpc/app.bsky.feed.searchPosts"
)
Arguments
access_jwt |
char, the jwt token provided by the bluesky api |
search_url |
char, the url to test if the current token is still valid |
Get bearer token
Description
Get bearer token
Usage
bluesky_create_session(handle = NULL, password = NULL)
Arguments
handle |
bluesky handle |
password |
bluesky password |
Details
You can find more information about the bluesky API here: https://docs.bsky.app/docs/api/com-atproto-server-create-session
Value
List with access_jwt and did
Examples
## Not run:
bluesky_create_session()
## End(Not run)
formats a date in the expected bluesky format
Description
formats a date in the expected bluesky format
Usage
bluesky_format_date(datetime)
Arguments
datetime |
the datetime to format |
parse a date as provided by bluesky into a date_time object
Description
parse a date as provided by bluesky into a date_time object
Usage
bluesky_parse_date(date_input)
Arguments
date_input |
char, the text of a date |
extracts features from the post structure returned by the bluesky api
Description
extracts features from the post structure returned by the bluesky api
Usage
bluesky_parse_features(post)
Arguments
post |
list, the post to extract features from in bluesky format |
extracts the quotes information from a post in one of the many possible locations found in bluesky format
Description
extracts the quotes information from a post in one of the many possible locations found in bluesky format
Usage
bluesky_parse_quoted(post)
Arguments
post |
list, the post to to extract data from in bluesky format |
parses the response of bluesky API into the standardised episomer format. For more details see the vignette.
Description
parses the response of bluesky API into the standardised episomer format. For more details see the vignette.
Usage
bluesky_parse_response(response, current_min_date)
Arguments
response |
list, the standardised response |
current_min_date |
datetime, the current min date obtained on the plan to detect if there are messages after this limit and discard them |
function to check if there has been a rate limit error returned by the bluesky API
Description
function to check if there has been a rate limit error returned by the bluesky API
Usage
bluesky_rate_limited_check(resp)
Arguments
resp |
the httr2 response object |
function to extract the number of seconds to wait after a rate limit has been reached
Description
function to extract the number of seconds to wait after a rate limit has been reached
Usage
bluesky_rerun_after_rate_limit(resp)
Arguments
resp |
the httr2 response object |
calculate alerts for for a particular region
Description
calculate alerts for a region and topic using provided parameters to the episomer signal detection function
Usage
calculate_region_alerts(
sms,
topic,
country_codes = list(),
country_code_cols = "geo_country_code",
start = NA,
end = NA,
with_quotes = FALSE,
alpha = 0.025,
alpha_outlier = 0.05,
k_decay = 4,
no_historic = 7,
bonferroni_m = 1,
same_weekday_baseline = FALSE,
logenv = NULL
)
calculate_regions_alerts(
sms,
topic,
regions = c(1),
date_type = c("created_date"),
date_min = as.Date("1900-01-01"),
date_max = as.Date("2100-01-01"),
with_quotes = FALSE,
alpha = 0.025,
alpha_outlier = 0.05,
k_decay = 4,
no_historic = 7,
bonferroni_correction = FALSE,
same_weekday_baseline = FALSE,
logenv = NULL
)
Arguments
sms |
A given social media for which aggregations have been calculated |
topic |
Limit the alert detection to the given topic |
country_codes |
List with the codes of countries to be aggregated for this alerts |
country_code_cols |
the name of the column containing the country codes |
start |
the start date for the period in consideration |
end |
the end date for the period in consideration |
with_quotes |
wether to consider quotes in the time series to evaluate |
alpha |
The alpha is used to compute the upper limit of the prediction interval: (1-alpha) * 100%, default: 0.025 |
alpha_outlier |
Residuals beyond 1-alpha_outlier quantile of the the t(n-k-1) distribution are downweighted, default: 0.05 |
k_decay |
Power k in the expression (r_star/r_threshold)^k determining the weight, default: 4 |
no_historic |
Number of previous values i.e -1, -2, ..., no_historic to include when computing baseline parameters, default: 7 |
bonferroni_m |
Number the value to apply the Bonferroni correction; it specifies the global number of timeseries being observed |
same_weekday_baseline |
whether to calculate baseline using same weekdays or any day, default: FALSE |
logenv |
an environment variable to store the total number of posts concerned including all country_cols |
regions |
List with the codes of regions to be aggregated for this alerts |
date_type |
the type of date to be used for the period in consideration |
date_min |
the start date for the period in consideration |
date_max |
the end date for the period in consideration |
bonferroni_correction |
whether to apply the bonferroni correction to the alerts, default: FALSE |
Details
for algorithm details see package vignette.
Value
A dataframe containing the monitored time point for the given countries and topic, the upper limit and whether a signal is detected or not.
A dataframe containing the monitored time point for the given regions and topic, the upper limit and whether a signal is detected or not.
Examples
## Not run:
library(episomer)
#Running the alerts for France in topic covid-19
df <-calculate_region_alerts(sms="bluesky",
topic="covid-19",
country_codes = "FR",
start=as.Date("2025-09-20"),
end=as.Date("2025-09-30"))
show(df)
## End(Not run)
## Not run:
library(episomer)
#Running the alerts for World in topic covid-19
df <-calculate_regions_alerts(
sms="bluesky",
topic="covid-19",
date_min=as.Date("2025-09-20"),
date_max=as.Date("2025-09-30")
)
show(df)
## End(Not run)
Episomer can run
Description
check whether conditions are met for episomer app to run
check whether conditions are met for episomer setup to run
Usage
can_run()
setup_can_run()
Details
Perform configuration checks concerning, Java, bitness, task status, dependencies and social media authentication to determine whether episomer can run.
Perform configuration checks concerning, Java, bitness whether episomer setup can run.
Value
logical, whether episomer can run or not
logical, whether episomer can run or not
Examples
## Not run:
#importing episomer
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
#check if episomer can run
can_run()
## End(Not run)
## Not run:
#importing episomer
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
#check if episomer can run
can_run()
## End(Not run)
Run automatic sanity checks
Description
It runs a set of automated sanity checks for helping the user to troubleshot issues
Usage
check_all()
Details
This function executes a series of sanity checks, concerning, Java, bitness, task status, dependencies and social media authentication.
Value
Data frame containing the statuses of all realized checks
Examples
## Not run:
#importing episomer
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
#running all tests
check_all()
## End(Not run)
internal function for producing the code template for a new social media
Description
internal function for producing the code template for a new social media
Usage
create_api_and_plan_files_for_new_social_media(
new_media,
ref_media = "bluesky"
)
Arguments
new_media |
char, name of the social media to add |
ref_media |
char, name of the social media to use as a reference to produce template |
Plot the map report on the episomer dashboard
Description
Generates a bubble map plot of number of posts by country for a single topic
Usage
create_map(
sms,
topic = c(),
countries = c(1),
date_min = "1900-01-01",
date_max = "2100-01-01",
with_quotes = FALSE,
caption = "",
proj = NULL,
forplotly = FALSE
)
Arguments
sms |
Social media |
topic |
Character(1) containing the topic to use for the report |
countries |
Character vector containing the name of the countries and regions to plot or their respective indexes on the Shiny app, default: c(1) |
date_min |
Date indicating start of the reporting period, default: "1900-01-01" |
date_max |
Date indicating end of the reporting period, default: "2100-01-01" |
with_quotes |
Logical value indicating whether to include reposts in the time series, default: FALSE |
caption |
Character(1) vector indicating a caption to print at the bottom of the chart, default: "" |
proj |
Parameter indicating the CRS (Coordinate Reference System) to use on PROJ4 format, default NULL If null and all countries are selected +proj=robin is used (Robinson projection) otherwise the Lambert azimuthal equal-area projection will be chosen, default: NULL |
forplotly |
Logical(1) parameter indicating whether some hacks are activated to improve plotly rendering, default: FALSE |
Details
Produces a bubble chart map for a particular topic on number of posts collected based on the provided parameters. The map will display information at country level if more than one country is selected, otherwise it will display bubbles at the smallest possible location identified for each post within the period which could be any administrative level or city level.
Posts associated with a country but with no finer granularity are omitted when displaying a single country.
When an aggregated zone is requested, all countries in that zone are included.
This functions requires that search_loop and detect_loop have already been run successfully to show results.
Value
A named list containing two elements: 'chart' with the ggplot2 figure and 'data' containing the dataframe that was used to build the map.
See Also
trend_line
create_topwords
detect_loop
search_loop
spTransform,coordinates,is.projected,CRS-class
fortify,geom_polygon,geom_point
Examples
## Not run:
#Getting bubble chart for dengue for South America for last 30 days
message('Please choose the episomer data directory')
setup_config(file.choose())
create_map(
topic = "dengue",
countries = "South America",
date_min = as.Date(Sys.time())-30,
date_max=as.Date(Sys.time())
)
## End(Not run)
Snapshot of your episomer installation
Description
Creates a snapshot file of your episomer installation folder. This can include all or a subset of the data files.
Usage
create_snapshot(
destination_dir,
types = c("settings", "dependencies", "machine-learning", "aggregations", "posts",
"logs"),
posts_period = get_aggregated_period(),
aggregated_period = get_aggregated_period(),
compress = TRUE,
progress = function(v, m) message(paste(round(v * 100, 2), m))
)
Arguments
destination_dir |
character(1) vector with the path of the destination folder to produce the snapshot |
types |
character vector indicating the types of data to include on a snapshot. Some of: "settings", "dependencies", "machine-learning", "aggregations", "posts", "logs" |
posts_period |
date(2) start and end dates to filter posts to include on snapshot (if selected) |
aggregated_period |
date(2) start and end dates to filter time series to include on snapshot (if selected) |
compress |
logical(1) whether to compress or not the output file |
progress |
function to report progress during execution. |
Details
This function can be used to create a a portable file to move your episomer installation in a single file, to backup your data, to archive your old data or to send information to technical team in order to reproduce an observed issue. Different kinds of data can be included on the snapshot depending on the type of parameter. Possible values are: - 'settings': Including all setting files of your installation (excluding passwords) - 'dependencies': All jars and winutils.exe on windows installations - 'machine-learning': All trained models and vectors and training data (this can include post text which is personal data) - 'aggregations': Episomer aggregated time series - 'posts': Posts collected by episomer - 'logs': Log files produced automatically on windows task scheduler tasks.
Value
Nothing
Examples
## Not run:
#importing episomer
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
message('Please choose a destination directory')
dest <- file.choose()
#creating a compressed snapshot for settings and logs
create_snapshot(dest, c("settings","dependencies"), compress = TRUE)
## End(Not run)
Plot the top elements for a specific series on the episomer dashboard
Description
Generates a bar plot of most popular elements in posts, for one topic. Top elements among ("topwords", "hashtags", "entities", "contexts", "urls")
Usage
create_topchart(
sms,
topic,
serie,
country_codes = c(),
date_min = "1900-01-01",
date_max = "2100-01-01",
with_quotes = FALSE,
top = 25
)
Arguments
sms |
Social media |
topic |
Character(1) containing the topic to use for the report |
serie |
Character(1) name of the series to be used for the report. It should be one of ("topwords", "hashtags", "entities", "contexts", "urls") |
country_codes |
Character vector containing the ISO 3166-1 alpha-2 countries to plot, default: c() |
date_min |
Date indicating start of the reporting period, default: "1900-01-01" |
date_max |
Date indicating end of the reporting period, default: "2100-01-01" |
with_quotes |
Logical value indicating whether to include reposts in the time series, default: FALSE |
top |
numeric(1) Parameter indicating the number of words to show, default: 25 |
Details
Produces a bar chart showing the occurrences of the most popular words in the collected posts based on the provided parameters.
This functions requires that search_loop and detect_loop have already been run successfully to show results.
Value
A named list containing two elements: 'chart' with the ggplot2 figure and 'data' containing the data frame that was used to build the map.
See Also
trend_line
create_map
detect_loop
search_loop
Examples
## Not run:
message('Please choose the episomer data directory')
setup_config(file.choose())
#Getting topword chart for dengue for France, Chile, Australia for last 30 days
create_topchart(
topic = "dengue",
serie = "topwords",
country_codes = c("FR", "CL", "AU"),
date_min = as.Date(Sys.time())-30,
date_max=as.Date(Sys.time())
)
## End(Not run)
Plot the top words report on the episomer dashboard
Description
Generates a bar plot of most popular words in posts, for one topic
Usage
create_topwords(
sms,
topic,
country_codes = c(),
date_min = "1900-01-01",
date_max = "2100-01-01",
with_quotes = FALSE,
top = 25
)
Arguments
sms |
Social media |
topic |
Character(1) containing the topic to use for the report |
country_codes |
Character vector containing the ISO 3166-1 alpha-2 countries to plot, default: c() |
date_min |
Date indicating start of the reporting period, default: "1900-01-01" |
date_max |
Date indicating end of the reporting period, default: "2100-01-01" |
with_quotes |
Logical value indicating whether to include reposts in the time series, default: FALSE |
top |
numeric(1) Parameter indicating the number of words to show, default: 25 |
Details
Produces a bar chart showing the occurrences of the most popular words in the collected posts based on the provided parameters.
This report may be empty for combinations of countries and topics with very few posts since for performance reasons, the calculation of top words is an approximation using chunks of 10.000 posts.
This function requires that search_loop and detect_loop have already been run successfully to show results.
Value
A named list containing two elements: 'chart' with the ggplot2 figure and 'data' containing the data frame that was used to build the map.
See Also
trend_line
create_map
detect_loop
search_loop
Examples
## Not run:
message('Please choose the episomer data directory')
setup_config(file.choose())
#Getting topword chart for dengue for France, Chile, Australia for last 30 days
create_topwords(
topic = "dengue",
country_codes = c("FR", "CL", "AU"),
date_min = as.Date(Sys.time())-30,
date_max=as.Date(Sys.time())
)
## End(Not run)
Runs the detect loop
Description
Infinite loop ensuring the daily signal detection and email alerts
Usage
detect_loop(data_dir = NA)
Arguments
data_dir |
Path to the 'data directory' containing application settings, models and collected posts.
If not provided the system will try to reuse the existing one from last session call of |
Details
The detect loop run the recurrent tasks generate_alerts
The loop report progress on the 'tasks.json' file which is read or created by this function.
The recurrent tasks are scheduled to be executed each 'detect span' minutes, which is a parameter set on the Shiny app.
If any of these tasks fails it will be retried three times before going to abort status. Aborted tasks can be relaunched from the Shiny app.
Value
nothing
See Also
Examples
## Not run:
#Running the detect loop
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
detect_loop()
## End(Not run)
Updates Java dependencies
Description
Download Java dependencies of the application mainly related to Apache SPARK, Apache Lucene, and Apache Pekko
Usage
download_dependencies(jars = TRUE, winutils = TRUE)
Arguments
jars |
whether to download maven jars default: TRUE |
winutils |
whether to download winutils binary default: TRUE |
Details
Run a one-shot task consisting of downloading Java and Scala dependencies, this is separated by the following subtasks
Download jar dependencies from configuration maven repo to project data folder. This includes, scala, spark, lucene. Packages to be downloaded are defined in package file 'sbt-deps.txt'
Download winutils from configuration URL to project data folder. For more details on winutils please see https://issues.apache.org/jira/browse/HADOOP-13223 and https://issues.apache.org/jira/browse/HADOOP-16816
The URLs to download the JAR dependencies (maven package manager) and Winutils are on the configuration tab of the Shiny app.
Normally this function is not called directly by the user but from the detect_loop function.
Value
The list of tasks updated with produced messages
See Also
Examples
## Not run:
library(episomer)
# setting up the data folder
message('Please choose the episomer data directory')
setup_config(file.choose())
# geolocating last posts
tasks <- download_dependencies()
## End(Not run)
algorithm for outbreak detection, extends the EARS algorithm
Description
The simple 7 day running mean version of the Early Aberration Reporting System (EARS) algorithm is extended as follows:
proper computation of the prediction interval
downweighting of previous signals, similar to the approach by Farrington (1996)
Usage
ears_t_reweighted(
ts,
alpha = 0.025,
alpha_outlier = 0.05,
k_decay = 4,
no_historic = 7L,
same_weekday_baseline = FALSE
)
Arguments
ts |
A numeric vector containing the counts of the univariate time series to monitor. The last time point in ts is investigated |
alpha |
The alpha is used to compute the upper limit of the prediction interval: (1-alpha) * 100%, default: 0.025 |
alpha_outlier |
Residuals beyond 1-alpha_outlier quantile of the the t(n-k-1) distribution are downweighted, default: 0.05 |
k_decay |
Power k in the expression (r_star/r_threshold)^k determining the weight, default: 4 |
no_historic |
Number of previous values i.e -1, -2, ..., no_historic to include when computing baseline parameters, default: 7 |
same_weekday_baseline |
whether to calculate baseline using same weekdays or any day, default: FALSE |
Details
for algorithm details see package vignette.
Value
A dataframe containing the monitored time point, the upper limit and whether a signal is detected or not.
Author(s)
Michael Hoehle <https://www.math.su.se/~hoehle>
Examples
## Not run:
library(episomer)
#Running the modifies version of the ears algorithm for a particular data series
ts <- c(150, 130, 122, 160, 155, 128, 144, 125, 300, 319, 289, 277, 500)
show(ears_t_reweighted(ts))
## End(Not run)
Run the episomer Shiny app
Description
Open the episomer Shiny app, to visualise the outputs of episomer and change settings.
Usage
episomer_app(
data_dir = NA,
profile = c("dashboard", "admin"),
host = NULL,
port = NULL,
fs_remote = NULL
)
dashboard_app(data_dir = NA, host = NULL, port = NULL, fs_remote = NULL)
admin_app(data_dir = NA, host = NULL, port = NULL, fs_remote = NULL)
Arguments
data_dir |
Path to the configuration file to extract the localisation of the central episomer instance. The preferred way to call this function is using the fs_remote parameter.
If not provided the system will try to reuse the existing one from last session call of |
profile |
The profile is to run the Shiny app on, default: "dashboard" (can be "dashboard" or "admin") |
host |
The IP if the network interface to run the Shiny app on, default: NULL (will run on 127.0.0.1) |
port |
The port to run the Shiny app on, default: NULL (will run on a random port) |
fs_remote |
address of the central instance of episomer for accessing. When not provided it is resolved for this machine, in this order: the EPI_HOST environment variable, then conf$fs_url:conf$fs_port if that host resolves here, then http://localhost:conf$fs_port. conf$fs_url is the address the database *binds* to and is shared through properties.json, so on a containerised deployment it names a Docker-internal host, default: NULL |
Details
The episomer app is the user entry point to the episomer package. This application will help the user to setup the post collection process, manage all settings, see the interactive dashboard visualisations, export them to Markdown or PDF, and setup the alert emails.
All its functionality is described on the episomer vignette.
The dashboard app is the user entry point to the episomer package for regular users. This application shows the interactive dashboard with visualisations, allow export them to Markdown or PDF.
All its functionality is described on the episomer vignette.
The admin app is contain all functionality for an administrator. It help the user to setup the post collection process, manage all settings, and setup the alert emails.
All its functionality is described on the episomer vignette.
Value
The Shiny server object containing the launched application
The Shiny server object containing the launched application
The Shiny server object containing the launched application
See Also
Examples
## Not run:
#Running the episomer app
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
episomer_app()
## End(Not run)
Runs the episomer embedded database loop
Description
Infinite loop ensuring that the episomer embedded database is running (Lucene + akka-http)
Usage
fs_loop(data_dir = NA, bind_host = NULL, bind_port = NULL)
Arguments
data_dir |
Path to the 'data directory' containing application settings, models and collected posts.
If not provided, the system will try to reuse the existing one from last session call of |
bind_host |
Character, the interface the database has to bind instead of |
bind_port |
Numeric, the port the database has to bind instead of |
Details
Launches the episomer embedded database which is accessed via a REST API located on localhost at port 8080. You can test that the database is running by accesssing the local URL and adding "/ping".
the REST API provide episomer a way to send and retrieve data related with posts and time series and to trigger geolocation or aggregation
The database is implemented using Apache Lucene indexes allowing episomer to access its data as a search engine but also as a tabular database.
health_check called each 60 seconds on a background process to send alerts to the administrator if some episomer components fail.
Value
nothing
See Also
Examples
## Not run:
#Running the detect loop
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
fs_loop()
## End(Not run)
Execute the alert task
Description
Evaluate alerts for the last collected day for all topics and regions and send email alerts to subscribers
Usage
generate_alerts(tasks = get_tasks())
Arguments
tasks |
Current tasks for reporting purposes, default: get_tasks() |
Details
This function calculates alerts for the last aggregated day and then sends emails to subscribers.
The alert calculation is based on the country_counts time series which stores alerts by country, hour and topics.
For each country and region, the process starts by aggregating the last N days. A day is defined as a block of consecutive 24 hours ending before the hour of the last collected post. N is defined by the alert baseline parameter on the configuration tab of the Shiny application (the default is N=7).
An alert will be produced when the number of posts observed is above the threshold calculated by the modified version of the EARS algorithm (for more details see the package vignette). The behaviour of the alert detection algorithm is modified by the signal false positive rate (alpha), by downweighting previous alerts and by weekly or daily baseline parameters, as defined in the configuration tab of the Shiny application and the topics file.
A prerequisite for this function is that the search_loop must already have stored posts in the search folder and that the geotagging and aggregation tasks have been completed.
Normally, this function is not called directly by the user, but from the detect_loop function.
Value
The list of tasks updated with produced messages
See Also
Examples
## Not run:
library(episomer)
# setting up the data folder
message('Please choose the episomer data directory')
setup_config(file.choose())
# calculating alerts for last day posts and sending emails to subscribers
generate_alerts()
## End(Not run)
geolocate text in a data frame given a text column and optionally a language column
Description
extracts geolocaion information on text on a column of the provided data frame and returns a new data frame with geolocation information
Usage
geolocate_text(df, text_col = "text", lang_col = NULL, min_score = NULL)
Arguments
df |
A data frame containing at least character column with text, a column with the language name can be provided to improve geolocation quality |
text_col |
character, name of the column on the data frame containing the text to geolocalize, default:text |
lang_col |
character, name of the column on the data frame containing the language of texts, default: NULL |
min_score |
numeric, the minimum score obtained on the Lucene scoring function to accept matches on GeoNames. It has to be empirically set default: NULL |
Details
This function perform a call to the episomer database which includes functionality for geolocating for languages activated and successfully processed on the shiny app.
The geolocation process tries to find the best match in GeoNames database https://www.geonames.org/ including all local aliases for words.
If no language is associated to the text, all tokens will be sent as a query to the indexed GeoNames database.
If a language code is associated to the text and this language is trained on episomer, entity recognition techniques will be used to identify the best candidate in text to contain a location and only these tokens will be sent to the GeoNames query.
A custom scoring function is implemented to grant more weight to cities increasing with population to try to perform disambiguation.
Rules for forcing the geolocation choices of the algorithms and for tuning performance with manual annotations can be performed on the geotag tab of the Shiny app.
A prerequisite to this function is that the tasks download_dependencies update_geonames and update_languages has been run successfully.
This function is called from the Shiny app on geolocation evaluation tab but can also be used for manually evaluating the episomer geolocation algorithm.
Value
A new data frame containing the following geolocation columns: geo_code, geo_country_code, geo_country, geo_name, tags
See Also
Examples
## Not run:
library(episomer)
# setting up the data folder
message('Please choose the episomer data directory')
setup_config(file.choose())
# creating a test dataframe
df <- data.frame(text = c("Me gusta Santiago de Chile es una linda ciudad"), lang = c("es"))
geo <- geolocate_text(df = df, text_col = "text", lang_col="lang")
## End(Not run)
Getting already aggregated time series produced by detect_loop
Description
Reads and returns the required aggregated dataset for the selected period and topics defined by the filter.
Usage
get_aggregates(
dataset = "country_counts",
cache = TRUE,
filter = list(),
top_field = NULL,
top_freq = NULL
)
Arguments
dataset |
A character(1) vector with the name of the series to request, it must be one of 'country_counts', 'geolocated', 'topwords', 'hashtags', 'entities', 'urls', 'contexts', default: 'country_counts' |
cache |
Whether to use the cache for lookup and storing the returned dataframe, default: TRUE |
filter |
A named list defining the filter to apply on the requested series, it should be in the form of a named list; e.g., list(post_geo_country_code=list('FR', 'DE')) default: list() |
top_field |
Name of the top field used with top_frequency to enable optimisation for getting only most frequent elements. It will only keep top 500 items after first 50k lines on reverse index order |
top_freq |
character, Name of the frequency fields used with top_field to enable optimisation for retrieving only most frequent elements. It will only keep top 500 items after first 50k rows on reverse index order |
Details
This function returns data aggregated by episomer. The data is found on the 'series' folder, which contains Rds files per weekday and type of series. starting on v 1.0.x it will also look on Lucene indexes situated on fs folder. Names of files and folders are parsed to limit the files to be read. When using Lucene indexes, filters are directly applied on read. This is an improvement compared 'series' folder where filters are applied after read. All returned rows are joined into a single dataframe. If no filter is provided, the entire data series is returned, which can result in millions of rows depending on the time series. To limit by period, the filter list must include an element 'period' containing a date vector or list with two dates representing the start and end of the request.
To limit by topic, the filter list must include an element 'topic' containing a non-empty character vector or list with the names of the topics to return.
The available time series are:
"country_counts" counting posts and reposts by posted date, hour and country
"geolocated" counting posts and reposts by posted date and the smallest possible geolocated unit (city, administrative level or country)
"topwords" counting posts and reposts by posted date, country and the most popular words, (this excludes words used in the topic search)
The returned dataset can be cached for further calls if requested. Only one dataset per series is cached.
Value
A data frame containing the requested series for the requested period
See Also
Examples
## Not run:
message('Please choose the episomer data directory')
setup_config(file.choose())
# Getting all country posts between 2020-jan-10 and 2020-jan-31 for all topics
df <- get_aggregates(
dataset = "country_counts",
filter = list(period = c("2020-01-10", "2020-01-31"))
)
# Getting all country posts for the topic dengue
df <- get_aggregates(dataset = "country_counts", filter = list(topic = "dengue"))
# Getting all country posts between 2020-jan-10 and 2020-jan-31 for the topic dengue
df <- get_aggregates(
dataset = "country_counts",
filter = list(topic = "dengue", period = c("2020-01-10", "2020-01-31"))
)
## End(Not run)
Getting signals produced by the task generate_alerts of detect_loop
Description
Returns a data frame of signals produced by the detect_loop, which are stored on the signal folder.
Usage
get_alerts(
topic = character(),
countries = numeric(),
from = "1900-01-01",
until = "2100-01-01",
topposts = 0,
limit = 0,
duplicates = "all",
progress = function(a, b) {
}
)
Arguments
topic |
Character vector. When it is not empty it will limit the returned signals to the provided topics, default: character() |
countries |
Character vector containing the names of countries or regions or a numeric vector containing the indexes of countries as displayed at the Shiny App to filter the signals to return., default: numeric() |
from |
Date defining the beginning of the period of signals to return, default: '1900-01-01' |
until |
Date defining the end of the period of signals to return, default: '2100-01-01' |
topposts |
Integer number of top posts to be added to the alert. These are obtained from the post index based on topwords and Lucene score, default: 0 |
limit |
Maximum number of alerts returned, default: 0 |
duplicates |
Character, action to decide what to do with alerts generated on the same day. Options are "all" (keep all alerts), "first" get only first alert and "last" for getting only the last alert |
progress |
Function, function to report progress it should receive two parameter a progress between 0 and 1 and a message, default: empty function |
Details
For more details see the package vignette.
Value
a data frame containing the calculated alerts for the period. If no alerts are found then NULL is returned
See Also
Examples
## Not run:
library(episomer)
# setting up the data folder
message('Please choose the episomer data directory')
setup_config(file.choose())
# Getting signals produced for last 30 days for a particular country
get_alerts(
countries = c("Chile", "Australia", "France"),
from = as.Date(Sys.time())-30,
until = as.Date(Sys.time())
)
## End(Not run)
Get the detect_loop task status
Description
Reads the status of the detect_loop tasks and update it with changes requested by the Shiny app
Usage
get_tasks(statuses = list())
Arguments
statuses |
Character vector for limiting the status of the returned tasks, default: list() |
Details
After reading the tasks.json file and parsing it with jsonlite, this function will update the necessary fields in the tasks for executing and monitoring them.
Value
A named list containing all necessary information to run and monitor the detect loop tasks.
See Also
Examples
## Not run:
#getting tasks statuses
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
tasks <- get_tasks()
## End(Not run)
Send email to administrator if a failure of episomer is detected
Description
It validates if episomer is not collecting posts, aggregating posts or not calculating alerts
Usage
health_check(send_mail = TRUE, one_per_day = TRUE, caller = NULL)
Arguments
send_mail |
Boolean. Whether an email should be sent to the defined administrator, default: TRUE |
one_per_day |
Boolean. Whether a limit of one email per day will be applied, default: TRUE |
caller |
Character. Name of the service or function running the check, shown in the email so the administrator can tell which process sent it, default: NULL (the email then says "unknown") |
Details
This function sends an email to the defined administrator if episomer is not collecting posts, aggregating posts or not calculating alerts
Value
A list of health check errors found
Examples
## Not run:
#importing episomer
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
#sending the email to the administrator if episomer components are not properly working
health_check()
## End(Not run)
check whether the R folder is present in the current directory
Description
check whether the R folder is present in the current directory
Usage
is_r_folder_present()
internal function for exporting code of necessary functions for creating templates for a new social media
Description
internal function for exporting code of necessary functions for creating templates for a new social media
Usage
keep_roxygen_and_function_declarations(file_content)
Arguments
file_content |
char, lines of the script to extract content from |
extracts http(s) urls from the html content of a mastodon status
Description
extracts http(s) urls from the html content of a mastodon status
Usage
mastodon_extract_urls(content)
Arguments
content |
char, the html content of a status |
formats a date in the expected mastodon format (ISO 8601 UTC)
Description
formats a date in the expected mastodon format (ISO 8601 UTC)
Usage
mastodon_format_date(datetime)
Arguments
datetime |
the datetime to format |
compares two mastodon snowflake ids and returns TRUE if a < b. ids exceed 32-bit integers so they are compared with bit64.
Description
compares two mastodon snowflake ids and returns TRUE if a < b. ids exceed 32-bit integers so they are compared with bit64.
Usage
mastodon_id_lt(a, b)
Arguments
a |
char, first id |
b |
char, second id |
returns the domain of the mastodon instance a network collects from
Description
returns the domain of the mastodon instance a network collects from
Usage
mastodon_instance_of(network)
Arguments
network |
char, the name of the network |
tells if an optional mastodon object is actually present. the API serialises absent objects as '' (and not as 'null'), which jsonlite turns into an empty list: 'is.null()' is therefore NOT enough to test for absence ('status$quote', 'status$reblog', 'status$card', 'status$poll', 'status$in_reply_to_id'... are all '' on a plain status).
Description
tells if an optional mastodon object is actually present. the API serialises absent objects as '' (and not as 'null'), which jsonlite turns into an empty list: 'is.null()' is therefore NOT enough to test for absence ('status$quote', 'status$reblog', 'status$card', 'status$poll', 'status$in_reply_to_id'... are all '' on a plain status).
Usage
mastodon_is_present(x)
Arguments
x |
the value read from the parsed json |
returns the smallest of a list/vector of mastodon snowflake ids
Description
returns the smallest of a list/vector of mastodon snowflake ids
Usage
mastodon_min_id(ids)
Arguments
ids |
character vector of ids |
parse a date as provided by mastodon into a date_time object
Description
parse a date as provided by mastodon into a date_time object
Usage
mastodon_parse_date(date_input)
Arguments
date_input |
char, the text of a date (ISO 8601) |
extracts the quoted / embedded texts of a mastodon status, in the same spirit as bluesky_parse_quoted(): everything that carries text around the status itself is collected and concatenated into a single 'quoted_text' used downstream for keyword matching.
Description
The mastodon cases and their bluesky counterparts:
quote post ('status$quote$quoted_status', mastodon >= 4.4) and boost ('status$reblog') ~ bluesky 'embed$record': the content of the quoted / boosted status. These are the only cases that set 'is_quote'.
link preview card ('card', title + description) ~ bluesky 'embed$external'. Like bluesky, a card alone does NOT make the status a quote.
media alternative texts ('media_attachments[[i]]$description') ~ bluesky 'embed$images[[i]]$alt'.
polls ('poll') are acknowledged but their options are not collected, like bluesky videos / poll facets.
A quoted / boosted status is a full Status object of its own: it carries its own 'card' and its own 'media_attachments', and those are harvested too (bluesky does the same by reading 'post$embed$record$embeds[[i]]$external'). A quote post whose card is the only place where the keyword appears would otherwise be missed.
Usage
mastodon_parse_quoted(status)
Arguments
status |
list, the status to extract data from, in mastodon format |
Details
Texts coming from a status content are kept as raw html, consistently with the 'text' field of mastodon_parse_response() (see the html question in the vignette).
parses the response of the mastodon search API into the standardised episomer format. For more details see the vignette.
Description
parses the response of the mastodon search API into the standardised episomer format. For more details see the vignette.
Usage
mastodon_parse_response(response, plan)
Arguments
response |
list, the raw parsed json response (contains accounts, statuses, hashtags) |
plan |
list, the current plan, used to discard posts out of the targeted window |
function to check if there has been a rate limit error returned by the mastodon API
Description
function to check if there has been a rate limit error returned by the mastodon API
Usage
mastodon_rate_limited_check(resp)
Arguments
resp |
the httr2 response object |
function to extract the number of seconds to wait after a rate limit has been reached
Description
function to extract the number of seconds to wait after a rate limit has been reached
Usage
mastodon_rerun_after_rate_limit(resp)
Arguments
resp |
the httr2 response object |
Registers the fs_monitor for the current process or exits
Description
registers the fs_monitor (by writing fs.monitor.PID file) for the current process or stops if no configuration has been set or if it is already running
registers the social media message collection task or stops if no configuration has been set or if it is already running
stops the post collection task
registers the alert detection task or stops if no configuration has been set or if it is already running
stops the alert detection task
registers the episomer database task or stops if no configuration has been set or if it is already running
stops all episomer runner tasks
starts all episomer runner tasks
stops the episomer database task
check if search jobs for each activated social media are running and return the list names of social media with missing jobs
gets the post collection execution status
gets the database runner execution status
gets the alert detection runner execution status
Usage
register_fs_monitor()
register_search_runner_task()
stop_search_runner_task()
register_detect_runner_task()
stop_detect_runner_task()
register_fs_runner_task(
wait_until_response = FALSE,
bind_host = NULL,
bind_port = NULL,
timeout = Inf
)
stop_all_runner_tasks()
start_all_runner_tasks()
stop_fs_runner_task(timeout = 60)
missing_search_jobs()
is_search_running()
is_fs_running()
is_detect_running()
Arguments
wait_until_response |
Logical, whether to block until the fs runner answers on
|
bind_host |
Character, the interface the database has to bind for this run instead of the
configured |
bind_port |
Numeric, the port the database has to bind for this run instead of the
configured |
timeout |
Numeric how many seconds to wait for the database service to stop answering before giving up, default: 60 |
Details
Registers the fs_monitor (by writing fs.monitor.PID file) for the current process or stops if no configuration has been set or if it is already running This function has been exported so it can be properly called from the future package on the database runner, but it is not intended to be directly called by end users.
Registers the message collextion task or stops if no configuration has been set or if it is already running. Bluesky authentication needs to be previously set on the shiny app or by calling set_auth(). You can test if authentication is working on the shiny app troubleshot page or by calling (with dplyr): episomer::check_all() This function will use the task scheduler on windows and will fall back to launching the runner as a separate process (attached to this session) on Linux.
Stops the post collection task if it is already running This function will try also deactivate the respective scheduled task on Windows.
Registers the alert detection task or stops if no configuration has been set or if it is already running. To generate alerts, this task needs the post collection to had successfully run since the last time it ran. This function will use the task scheduler on windows and will fall back to launching the runner as a separate process (attached to this session) on Linux.
Stops the alert detection task if it is already running This function will try also deactivate the respective scheduled task on Windows.
Registers the episomer database task or stops if no configuration has been set or if it is already running. This task need the dependencies, geonames and languages steps to have been successfully ran. This can be done on the shiny app configuration page or by manually running the detect_runner_task. This function will try to use the task scheduler on windows and will fall back to launching the runner as a separate process (attached to this session) on Linux.
bind_host and bind_port start a database that is deliberately *not* on the
configured address, for a caller that needs one for itself: the language model retraining of
setup needs a running database, and it must not be mistaken for the real service
by whatever waits for that service to become healthy before starting (depends_on:
service_healthy in docker/compose.yml, a readiness probe in Kubernetes). They travel to the
database as command line arguments - jobs/fs.R, then fs_loop, then the Scala
API.run() - and nothing about them is written to properties.json, so a process killed
outright leaves no trace behind. Every call the current process makes to the API goes to that
address until clear_fs_endpoint_override() is called or the process ends.
"localhost" is the value to give bind_host in a container orchestrator: an
address reachable from inside the pod only, needing no exposed port and no service routing, and
therefore reachable even while the pod is still unready.
A database given either of them is always started attached to this session, on Windows as everywhere else, and never as a Windows scheduled task: it is meant to live for the length of one call, and a scheduled task would both outlive it and truncate its command line.
Stops the detect loop, the search loop and the fs loop This function will try also deactivate the respective scheduled task on Windows.
Starts the detect loop, the search loop and the fs loop This function will try also register the respective scheduled task on Windows.
Stops the episomer database task if it is already running This function will try also deactivate the respective scheduled task on Windows.
returns a char vector with the name of missing social media. The answer is cluster-wide: it is read from the runner leases ('<data_dir>/runners/'), so a social media collected by another machine sharing the same database is not reported as missing.
returns a logical value being TRUE if the post collection is running, on this machine *or on any other machine* sharing the same episomer database: the status is read from the runner leases and not from the local PID files. A service that stopped without releasing its lease is reported as running until its lease expires ('runner_ttl_search' seconds), unless it crashed on this very machine, which is detected at once.
returns a logical value being TRUE if the database runner is actually running. Unlike the other services this one is not answered by the runner lease but by an HTTP call to the database '/ping' endpoint: it is instantaneous, it needs no TTL, and it tells whether the service *answers* rather than whether some process holds its lease. The 'fs' runner does take a lease, for a different purpose - stopping a second database from opening the same storage.
returns a logical value being TRUE if the alert detection task is actually running, on
this machine or on any other machine sharing the same episomer database - see
is_search_running for what the runner leases can and cannot tell.
Value
Nothing
Nothing
Nothing
Nothing
Nothing
Nothing
Nothing
Nothing
Nothing
char list of social media with no search job running
logical Whether the post collection is running
logical Whether the database is running
logical Whether the alert detection task is running
Examples
## Not run:
#getting tasks statuses
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
register_fs_monitor()
## End(Not run)
## Not run:
#getting tasks statuses
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
register_search_runner_task()
## End(Not run)
## Not run:
#getting tasks statuses
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
stop_search_runner_task()
## End(Not run)
## Not run:
#getting tasks statuses
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
register_detect_runner_task()
## End(Not run)
## Not run:
#getting tasks statuses
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
stop_detect_runner_task()
## End(Not run)
## Not run:
#getting tasks statuses
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
register_fs_runner_task()
# a database only this process can see, on a port of its own
register_fs_runner_task(wait_until_response = TRUE, bind_host = "localhost", bind_port = 9080)
## End(Not run)
## Not run:
#getting tasks statuses
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
stop_all_runner_tasks()
## End(Not run)
## Not run:
#getting tasks statuses
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
start_all_runner_tasks()
## End(Not run)
## Not run:
#getting tasks statuses
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
stop_fs_runner_task()
## End(Not run)
## Not run:
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
missing_search_jobs()
## End(Not run)
## Not run:
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
is_search_running()
## End(Not run)
## Not run:
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
is_fs_running()
## End(Not run)
## Not run:
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
is_detect_running()
## End(Not run)
Save the configuration changes
Description
Permanently saves configuration changes to the data folder (excluding social media credentials, but not SMTP credentials)
Usage
save_config(
data_dir = conf$data_dir,
properties = TRUE,
sm_topics = NULL,
fs_remote = conf$fs_remote
)
Arguments
data_dir |
Path to a directory to save configuration settings if fs_remote is provided this value is ignored, Default: conf$data_dir |
properties |
Whether to save the general properties to the properties.json file, default: TRUE |
sm_topics |
Whether to save topic download plans to the topics.json file, default: TRUE |
fs_remote |
Path to the remote master instance of episomer, default: conf$fs_remote" |
Details
Permanently saves configuration changes to the data folder (excluding social media credentials, but not SMTP credentials)
to save social media credentials please use sm_api_set_auth_bluesky or
sm_api_set_auth_mastodon
Value
Nothing
See Also
setup_config
sm_api_set_auth_bluesky
sm_api_set_auth_mastodon
Examples
## Not run:
library(episomer)
#load configuration
message('Please choose the episomer data directory')
setup_config(file.choose())
#make some changes
#conf$collect_span = 90
#saving changes
save_config()
## End(Not run)
Runs the search loop
Description
Infinite loop ensuring the permanent collection of social media messages
Usage
search_loop(
data_dir = NA,
sandboxed = FALSE,
log_to_file = !logs_to_stdout(),
max_requests = 0
)
search_loop_worker(network, data_dir = NA, sandboxed = FALSE, max_requests = 0)
Arguments
data_dir |
The data directory to use. |
sandboxed |
Whether to run in sandboxed mode. |
log_to_file |
logical indicating if the search loop should log to a file, one per collected network (jobs/search.<network>.log). When FALSE every worker writes to the standard output of this process instead, which is what a container deployment needs - nothing collects a file inside a pod. Default: FALSE when the environment variable 'EPISOMER_LOGS_TO_STDOUT' is set to TRUE, TRUE otherwise |
max_requests |
The maximum number of requests to perform. |
network |
The social media network to search on. |
Details
The detect loop is a pure R function designed for downloading posts from the social media search API. It can handle several topics ensuring that all of them will be downloaded fairly using a round-robin philosophy and respecting social media API rate-limits.
The progress of this task is reported on the 'topics.*.json' files which are created by this function. This function will try to collect posts respecting a 'collect_span' window in minutes, which is defined on the Shiny app and defaults to 60 minutes.
To see more details about the collection algorithm please see episomer vignette.
In order to work, this task needs Bluesky and/or Mastodon credentials,
which can be set on the Shiny app or using sm_api_set_auth_bluesky or
sm_api_set_auth_mastodon
The search loop worker is a function that runs the search loop for a given social media network. It is used to run the search loop in a separate process.
Value
Nothing
Invisibly, why the worker stopped: "lease-lost" when another instance took this
network over, "ended" when max_requests was reached. Read by search_loop()
to tell an orderly handover from an unexpected end. A failed request does not stop the worker,
it is logged and tried again; only search_max_request_failures() consecutive failures do,
and that one raises rather than returning.
See Also
sm_api_set_auth_bluesky
sm_api_set_auth_mastodon
Examples
## Not run:
#Running the search loop
library(episomer)
message('Please choose the episomer data directory')
search_loop(file.choose())
## End(Not run)
perform full text search on posts collected with episomer
Description
perform full text search on posts collected with episomer (posts migrated from episomer v<1.0.x are also included)
Usage
search_posts(
query = NULL,
topic = NULL,
from = NULL,
to = NULL,
countries = NULL,
mentioning = NULL,
users = NULL,
hide_users = FALSE,
action = NULL,
max = 100,
by_relevance = FALSE
)
Arguments
query |
character. The query to be used if a text it will match the post text. To see how to match particular fields please see details, default:NULL |
topic |
character, Vector of topics to include on the search default:NULL |
from |
an object which can be converted to ‘"POSIXlt"’ only posts posted after or on this date will be included, default:NULL |
to |
an object which can be converted to ‘"POSIXlt"’ only posts posted before or on this date will be included, default:NULL |
countries |
character or numeric, the position or name of episomer regions to be included on the query, default:NULL |
mentioning |
character, limit the search to the posts mentioning the given users, default:NULL |
users |
character, limit the search to the posts created by the provided users, default:NULL |
hide_users |
logical, whether to hide user names on output replacing them by the USER keyword, default:FALSE |
action |
character, an action to be performed on the search results respecting the max parameter. Possible values are 'delete' or 'anonymise' , default:NULL |
max |
integer, maximum number of posts to be included on the search, default:100 |
by_relevance |
logical, whether to sort the results by relevance of the matching query or by indexing order, default:FALSE
If not provided the system will try to reuse the existing one from last session call of |
Details
episomer translate the query provided by all parameters into a single query that will be executed on post indexes which are weekly indexes. The q parameter should respect the syntax of the Lucene classic parser https://lucene.apache.org/core/8_5_0/queryparser/org/apache/lucene/queryparser/classic/QueryParser.html So other than the provided parameters, multi field queries are supported by using the syntax field_name:value1;value2 AND, OR and -(for excluding terms) are supported on q parameter. Order by week is always applied before relevance so even if you provide by_relevance = TRUE all of the matching posts of the first week will be returned first
Value
a data frame containing the posts matching the selected filters, the data frame contains the following columns: user_name, created_date, is_geo_located, is_quote, text, text_loc, user_id, hash, quote_lang, totalCount, created_at, topic_post_id, topic, lang, user_name, quoted_text, id, quopted_text_loc, tags
See Also
Examples
## Not run:
#Running the detect loop
library(episomer)
message('Please choose the episomer data directory')
setup_config(file.choose())
df <- search_posts(
q = "vaccination",
topic="COVID-19",
countries=c("Chile", "Australia", "France"),
from = Sys.Date(),
to = Sys.Date()
)
df$text
## End(Not run)
performs a search following the given plan, query and topic.
Description
performs a search following the given plan, query and topic.
Usage
search_topic(plan, query, topic, sandboxed = FALSE)
Arguments
plan |
list, the plan that defines the timespan to search for |
query |
char, the query to use when searching for the topic |
topic |
char, the topic associated to this search |
sandboxed |
logical, whether to un in sandboxed mode which prevent sending data to the embedded database. |
updates the modificatin date of a flag file indicating that messages have been sent to the embedded database.
Description
updates the modificatin date of a flag file indicating that messages have been sent to the embedded database.
Usage
search_touch()
Run the setup of episomer
Description
Perform configuration tasks needed for the proper work of episomer or change settings of these configuration
Usage
setup(data_dir = NULL, silent = FALSE, launch = TRUE)
Arguments
data_dir |
Character the data directory where episomer will store all files. If not provided and already set in the current session it will reused, default: NULL |
silent |
Logical whether episomer should take default actions without asking the user default: FALSE |
launch |
Logical whether episomer should run automatically extra steps when selecting Option 1 or 2 in the wizard (setting credentials, running services and shiny app) |
Details
Perform configuration tasks needed for the proper work of episomer or change settings of these configuration
Value
NULL.
Examples
## Not run:
#getting tasks statuses
library(episomer)
message('Please choose the episomer data directory')
setup(file.choose())
## End(Not run)
Load episomer application settings
Description
Load episomer application settings from the designated data directory
Usage
setup_config(
data_dir = default_data_dir(),
ignore_keyring = FALSE,
ignore_properties = FALSE,
ignore_topics = FALSE,
save_properties_first = FALSE,
save_topics_first = list(),
fs_remote = if (Sys.getenv("EPI_HOST") != "") {
Sys.getenv("EPI_HOST")
} else {
"http://localhost:8080"
}
)
Arguments
data_dir |
Path to the directory containing the application settings (it must exist). If not provided it takes the value of the latest call to setup_config in the current session, or the value of the EPI_HOME environment variable or episomer subdirectory in the working directory, default: default_data_dir(), i.e. conf$data_dir, then the EPI_HOME environment variable, then file.path(tempdir(), "episomer") |
ignore_keyring |
Whether to skip loading settings from the keyring (social media and SMTP credentials), default: FALSE |
ignore_properties |
Whether to skip loading settings managed by the Shiny app in properties.json file, Default: FALSE |
ignore_topics |
Whether to skip loading settings defined in the topics.xlsx file and download plans from topics.json file, default: FALSE |
save_properties_first |
Whether to save current settings before loading new ones from disk, default: FALSE |
save_topics_first |
List of social media to save its topics to disk before loading new ones from disk, default: list() |
fs_remote |
address of the central instance of episomer for accessing |
Details
episomer relies on settings and data stored in a system folder, so before loading the dashboard, collecting posts or detecting alerts the user has to designate this folder.
When a user wants to use episomer from the R console they will need to call this function for initialisation.
The 'data_folder' can also be given as a parameter for program launch functions episomer_app, search_loop or detect_loop, which will internally call this function.
This call will fill (or refresh) a package scoped environment 'conf' that will store the settings. Settings stored in conf are:
General properties of the Shiny app (stored in properties.json)
Download plans from the social media collection process (stored in topics.json merged with data from the topics.xlsx file
Credentials for social media APIs and SMTP stored in the defined keyring
The identity of the running instance: 'instance_id', a random identifier generated once per R process, and 'instance_host', the name of the machine. Both describe the current process rather than the shared configuration, so they are never written to properties.json. 'instance_host' is taken from the environment variable 'EPISOMER_INSTANCE' when it is set, and falls back to the system host name otherwise. Setting 'EPISOMER_INSTANCE' is recommended when running episomer in containers, whose host names are random, and when several machines share the same data directory: it is the name the dashboard displays to tell which machine a service is running on.
When calling this function and the keyring is locked, a password will be prompted to unlock the keyring. This behaviour can be changed by setting the environment variable 'ecdc_social_tool_kr_password' with the password.
Changes made to conf can be stored permanently (except for 'data_dir') using:
Value
Nothing
See Also
save_config
sm_api_set_auth_bluesky
sm_api_set_auth_mastodon
episomer_app
search_loop
detect_loop
Examples
## Not run:
library(episomer)
#loading system settings
message('Please choose the episomer data directory')
setup_config(file.choose())
## End(Not run)
Add an instance of a federated social media
Description
Adds a domain to the instances a federated social media family collects from. Each instance is collected as a network of its own, named <family>.<instance>, with its own plan file, its own search process and its own access token.
Usage
sm_add_instance(family, instance)
Arguments
family |
char, the federated social media family e.g. "mastodon" |
instance |
char, the domain of the instance to collect from e.g. "mstdn.party" |
Details
The network identifier built from family and instance is a persistent key: it names
the plan file, the secrets and the network column of every post stored for it. Removing an
instance and adding it back resumes on its former history, but renaming it orphans that
history.
The credentials still have to be provided with sm_api_set_auth, and the
configuration is not written to disk, call save_config afterwards. The social
media menu of setup does all of it at once.
Value
char, the identifier of the network collecting from this instance
See Also
Examples
## Not run:
library(episomer)
setup_config(file.choose())
network <- sm_add_instance("mastodon", "mstdn.party")
sm_api_set_auth(network)
save_config()
## End(Not run)
Get social media token
Description
Get social media token
Usage
sm_api_get_token(network)
Arguments
network |
char, network the name of the social media |
Details
this function implements the authethication on the respective social media and stores it securely. It is called by the search loop before starting message collection
Get social media token
Description
Get social media token
Usage
sm_api_get_token_bluesky(network = NULL)
Arguments
network |
char, unused, bluesky is not federated so all its networks would share the same credentials, default: NULL |
Details
this function implements the authethication on the respective social media and stores it securely. It is called by the search loop before starting message collection
Value
Token
Get social media token
Description
Get social media token
Usage
sm_api_get_token_mastodon(network)
Arguments
network |
char, the network to get the token for, its instance is the one the token was issued by |
Details
this function implements the authethication on the respective social media and stores it securely. It is called by the search loop before starting message collection
Value
Token
Receive the results provided by a request and return a logical value indicating whether the request returned results.
Description
Receive the results provided by a request and return a logical value indicating whether the request returned results.
Usage
sm_api_got_rows_bluesky(results)
Arguments
results |
list, results of the request in the standardised episomer format |
Details
This function needs to be implemented for each social media since it is interpreted as 'No more messages are available for this plan' When FALSE is returned the underlying plan will be ended
Receive the results provided by a request and return a logical value indicating whether the request returned results.
Description
Receive the results provided by a request and return a logical value indicating whether the request returned results.
Usage
sm_api_got_rows_mastodon(results)
Arguments
results |
list, results of the request in the standardised episomer format |
Details
This function needs to be implemented for each social media since it is interpreted as 'No more messages are available for this plan' When FALSE is returned the underlying plan will be ended
Whether the credentials needed to authenticate on a social media are configured
Description
Whether the credentials needed to authenticate on a social media are configured
Usage
sm_api_has_credentials(network)
Arguments
network |
char, network the name of the social media |
Details
this is a purely local check: it looks for stored secrets and never calls the underlying social media API, unlike sm_api_get_token which may perform a live token validity check as part of fetching a token. It is used to report or poll authentication status (setup() menu, check_sm_auth) without the cost of a network round-trip.
Whether the credentials needed to authenticate on Bluesky are configured
Description
Whether the credentials needed to authenticate on Bluesky are configured
Usage
sm_api_has_credentials_bluesky(network = NULL)
Arguments
network |
char, unused, bluesky is not federated so all its networks would share the same credentials, default: NULL |
Details
purely local: checks that a stored session or a handle+password pair is present, without calling the Bluesky API. See sm_api_get_token_bluesky for the live token validity check performed right before a search.
Value
logical
Whether the credentials needed to authenticate on this Mastodon instance are configured
Description
Whether the credentials needed to authenticate on this Mastodon instance are configured
Usage
sm_api_has_credentials_mastodon(network)
Arguments
network |
char, the network to check the token for, its instance is the one the token was issued by |
Details
purely local: checks that an access token is stored for this network, without calling the Mastodon API.
Value
logical
Search posts for a given query and produce standardised results
Description
Search posts for a given query and produce standardised results
Usage
sm_api_search(query, token, plan)
Arguments
query |
char, the query to use in the search in nattive format |
token |
char, the token to authenticate against the underlying social media api |
plan |
list, the plan containing the targeted time frame |
Details
This function impleents the search of messages for a given query and plan.
Search posts for a given query and produce standardised results
Description
Search posts for a given query and produce standardised results
Usage
sm_api_search_bluesky(query, token, plan, max_retries = 10, verbose = TRUE)
Arguments
query |
query to search for |
token |
Access token |
plan |
Plan object |
max_retries |
Maximum number of retries |
verbose |
Whether to print progress messages |
Details
This function impleents the search of messages for a given query and plan. The query has been already transformed by sm_api_translate_query_xxx so it is expected to be already in the native social media format The token has been produced by the function sm_api_get_token_xxx and shoulb be used to autenticate the request The plan should be used to extract the precise time-span to request messages
- Response attributes - network: string - posts: [...] - count: number, - pagination:{...} - post in posts - id: string - uri: string - created_at: datetime - user_name: string - text: string - lang: string - quoted_text: string - quoted_lang: string - tags: [...] - urls: [...] - categories: [...] - tag in post.tags: string - url in post.urls: string - category in post.categories: string - pagination: attributes used for paginating requests
This is the implementation of the bluesky search. You can find more information about the bluesky API here: https://docs.bsky.app/docs/api/app-bsky-feed-search-posts
Value
List with posts int the standard post format defined in episomer
Search posts for a given query and produce standardised results
Description
Search posts for a given query and produce standardised results
Usage
sm_api_search_mastodon(query, token, plan, max_retries = 10, verbose = TRUE)
Arguments
query |
query to search for |
token |
Access token |
plan |
Plan object |
max_retries |
Maximum number of retries |
verbose |
Whether to print progress messages |
Details
This function implements the search of messages for a given query and plan. The query has been already transformed by sm_api_translate_query_xxx so it is expected to be already in the native social media format The token has been produced by the function sm_api_get_token_xxx and shoulb be used to autenticate the request The plan should be used to extract the precise time-span to request messages
- Response attributes - network: string - posts: [...] - count: number, - pagination:{...} - post in posts - id: string - uri: string - created_at: datetime - user_name: string - text: string - lang: string - quoted_text: string - quoted_lang: string - tags: [...] - urls: [...] - categories: [...] - tag in post.tags: string - url in post.urls: string - category in post.categories: string - pagination: attributes used for paginating requests
Pagination combines ‘max_id' and 'offset', because 'max_id' alone is not enough on Mastodon’s status search: server-side 'max_id' is converted to an inclusive, SECOND-resolution 'before:<timestamp>' filter, so it can only address a whole second, never a position inside it. A popular keyword can have far more than one page (40) of matches in a single second, and ‘max_id' on its own would keep returning that second’s newest 40 forever. 'offset' alone is not enough either: the search is backed by Elasticsearch, whose 'max_result_window' caps the usable offset (~10000) — past it the API errors out.
The strategy (results are ordered id DESC) walks a bounded offset under a moving 'max_id': - 'max_id' ('plan$current_min_id') is the anchor selecting the "window": all posts in its second and older. It is null on the first request, which simply starts from the newest posts, and is then seeded onto the oldest id of that first page. - 'offset' ('plan$current_offset') walks *inside* that window, one page at a time (0, 40, ...). - As long as the offset stays below 'mastodon_max_offset' we keep the same anchor and grow the offset by one page, digging deeper into the current window. - When the offset would reach 'mastodon_max_offset' we rebase the anchor onto the oldest id seen so far and reset the offset to 0. Because the rebased window drops every second newer than that id, the oldest id sits near the top of the new window, so the bounded offset has room to dig past it. See sm_api_update_plan_after_request_mastodon for the logic.
This keeps the offset permanently below the Elasticsearch cap while the anchor gives unlimited time depth. Two consequences of the server dropping DB-less rows ('.objects.compact') shape the details: (1) a page usually returns fewer than the requested 40 rows even when more exist, so we advance the offset by the requested page size (pre-compact positions), never by the number of rows kept; (2) each anchor change re-reads the head of the second it lands on, producing some duplicate posts at the boundary. The client-side filters on the returned posts are the lower time bound ('plan_min_date', posts older than it are discarded) and a de-duplication against 'plan$seen_ids', a sliding memory of the last 'mastodon_seen_ids_size' ids returned by this plan (the API is not stable enough to guarantee a status is served only once). Neither filter touches the pagination bookkeeping, which is computed on the raw statuses.
Stop criterion: Mastodon orders results by 'id' (ingestion time) while the lower bound is on 'created_at', and the two axes diverge because of federation, so a single request walked by id can return only posts older than 'plan_min_date' and yet be followed by newer ones. We therefore do not end the plan on the first below-window request; instead we count CONSECUTIVE requests that bring back no in-window post ('created_at >= plan_min_date') in 'plan$consecutive_empty', and end the plan once that streak reaches 'conf$mastodon_max_empty_requests' (any in-window post resets it). The one exception is the very FIRST request of the plan (no anchor, no offset, i.e. the newest statuses matching the query): if it brings back no in-window post the plan ends immediately, since every following request walks strictly older ids and could only move further away from the window. Residual limitation: a single second holding more matches than 'mastodon_max_offset' cannot be fully drained.
This is the implementation of the mastodon search. You can find more information about the mastodon search API here: https://docs.joinmastodon.org/methods/search/#v2 Additionnaly more information about the "Status" object is available here: https://docs.joinmastodon.org/entities/Status/
Value
List with posts int the standard post format defined in episomer
Save credentials for a social media provider and store them securely
Description
Update configuration object and underlying storage with given bluesky username and password. The password is encrypted.
Usage
sm_api_set_auth(network, shiny_input_list = NULL)
Arguments
network |
char, the name of the social media |
shiny_input_list |
list, the shiny input object to extract the information from if not provided the password will be requested interactively |
Save bluesky credentials (login and password) and store them securely
Description
Update configuration object and underlying storage with given bluesky username and password. The password is encrypted.
Usage
sm_api_set_auth_bluesky(shiny_input_list = NULL, network = NULL)
Arguments
shiny_input_list |
List of shiny input values containing the bluesky specific credentials if not provided the input will be requested interactively |
network |
char, unused, bluesky is not federated so all its networks would share the same credentials, default: NULL |
Details
Update authentication tokens in configuration object
Value
Nothing. Called for side effects (saving credentials)
See Also
Examples
## Not run:
#Setting the configuration values
sm_api_set_auth_bluesky(
shiny_input_list = list(bluesky_user = "your user here", bluesky_password = "your password"),
)
## End(Not run)
Save mastodon credentials and store them securely
Description
Update the underlying storage with the mastodon access token of a network. The token is encrypted.
Usage
sm_api_set_auth_mastodon(shiny_input_list = NULL, network)
Arguments
shiny_input_list |
List of shiny input values containing the mastodon specific credentials if not provided the input will be requested interactively |
network |
char, the network the token belongs to. The instance the token has to be issued by is the one the network is named after. |
Details
Update the authentication token of the network. The instance is not asked for: it is
part of the network identifier, set once when registering it with
sm_add_instance.
Value
Nothing. Called for side effects (saving credentials)
See Also
Examples
## Not run:
#Setting the configuration values
sm_api_set_auth_mastodon(
shiny_input_list = list(
mastodon_mstdn_party_token = "your token here"
),
network = "mastodon.mstdn.party"
)
## End(Not run)
Translate a parsed query to the social media query format
Description
Translate a parsed query to the social media query format
Usage
sm_api_translate_query(network, parsed)
Arguments
network |
char, the name of the social media |
parsed |
char, parsed query to translate in one or many native equivalent queries |
Details
This function receive as a parameter a parsed query from the a topic in the list of topics. It can return one or many queries that matches the expected results using the underlying social media API
Translate a parsed query to the social media query format
Description
Translate a parsed query to the social media query format
Usage
sm_api_translate_query_bluesky(parsed)
Arguments
parsed |
list. Named list containing two attributes 'ors' and 'neg'. 'ors' is a list containing subqueries that should be contatenated with an OR logic - each subquery in 'ors' is a list containing terms that should be concatecated with an AND logic - each term in 'ors subqueries' is a list of synonyms for a particular literal 'neg' is a list of terms that should be removed from any result of the query |
Details
This function receive as a parameter a parsed query from the a topic in the list of topics. It can return one or many queries that matches the expected results using the underlying social media API
Translate a parsed query to the social media query format
Description
Translate a parsed query to the social media query format
Usage
sm_api_translate_query_mastodon(parsed)
Arguments
parsed |
list. Named list containing two attributes 'ors' and 'neg'. 'ors' is a list containing subqueries that should be contatenated with an OR logic - each subquery in 'ors' is a list containing terms that should be concatecated with an AND logic - each term in 'ors subqueries' is a list of synonyms for a particular literal 'neg' is a list of terms that should be removed from any result of the query |
Details
This function receive as a parameter a parsed query from the a topic in the list of topics. It can return one or many queries that matches the expected results using the underlying social media API
Takes a plan after a request has been performed and the standardised results provided as returned by the function sm_api_search_xxx it should return a plan with necessary information updated so next request will continue paginating as expected to obtain targeted messages
Description
Takes a plan after a request has been performed and the standardised results provided as returned by the function sm_api_search_xxx it should return a plan with necessary information updated so next request will continue paginating as expected to obtain targeted messages
Usage
sm_api_update_plan_after_request(plan, results)
Arguments
plan |
list, the plan producing the resusts |
results |
list, the result of the query in episomer format |
Takes a plan after a request has been performed and the standardised results provided as returned by the function sm_api_search_xxx it should return a plan with necessary information updated so next request will continue paginating as expected to obtain targeted messages
Description
Takes a plan after a request has been performed and the standardised results provided as returned by the function sm_api_search_xxx it should return a plan with necessary information updated so next request will continue paginating as expected to obtain targeted messages
Usage
sm_api_update_plan_after_request_bluesky(plan, results)
Arguments
plan |
list, the plan to update |
results |
list, the obtained results of the plan |
Takes a plan after a request has been performed and the standardised results provided as returned by the function sm_api_search_xxx it should return a plan with necessary information updated so next request will continue paginating as expected to obtain targeted messages
Description
Takes a plan after a request has been performed and the standardised results provided as returned by the function sm_api_search_xxx it should return a plan with necessary information updated so next request will continue paginating as expected to obtain targeted messages
Usage
sm_api_update_plan_after_request_mastodon(plan, results)
Arguments
plan |
list, the plan to update |
results |
list, the obtained results of the plan |
returns the code family of a network, i.e. the suffix of the sm_* functions implementing it
Description
returns the code family of a network, i.e. the suffix of the sm_* functions implementing it
Usage
sm_family(network)
Arguments
network |
char, the name of the social media |
Details
for a network bound to an instance the family is the part before the first dot, "mastodon.mstdn.party" is served by the sm_*_mastodon functions. Networks without an instance are their own family.
returns the instance domain a network collects from, or NULL when the network is not federated
Description
returns the instance domain a network collects from, or NULL when the network is not federated
Usage
sm_instance(network)
Arguments
network |
char, the name of the social media |
whether a social media family is federated, i.e. made of independent instances each collected as a network of its own
Description
whether a social media family is federated, i.e. made of independent instances each collected as a network of its own
Usage
sm_is_federated(family)
Arguments
family |
char, the social media family |
Details
a federated family serves one network per domain listed in its <family>_instances configuration property, and none when that list is empty. Families that do not implement sm_is_federated_<family> are not federated.
Whether this social media is made of independent instances
Description
Whether this social media is made of independent instances
Usage
sm_is_federated_bluesky()
Details
Bluesky is served by a single API endpoint, so it is collected as one network.
Value
FALSE
Whether this social media is made of independent instances
Description
Whether this social media is made of independent instances
Usage
sm_is_federated_mastodon()
Details
Mastodon is federated: every instance is a separate server with its own API endpoint and its own access tokens, so each instance listed in the mastodon_instances configuration property is collected as a network of its own.
Value
TRUE
returns a list with the custom social media plan attributes with the default values for a first plan in a topic.
Description
returns a list with the custom social media plan attributes with the default values for a first plan in a topic.
Usage
sm_plan_first_attributes(network)
Arguments
network |
char, the name of the social media |
returns a list with the custom social media plan attributes with the default values for a first plan in a topic.
Description
returns a list with the custom social media plan attributes with the default values for a first plan in a topic.
Usage
sm_plan_first_attributes_bluesky()
returns a list with the custom social media plan attributes with the default values for a first plan in a topic.
Description
returns a list with the custom social media plan attributes with the default values for a first plan in a topic.
Usage
sm_plan_first_attributes_mastodon()
prepare a plan for serialisation by transforming attributes with non standard serialisation types e.g. dates to string on the format expected by the parse functions
Description
prepare a plan for serialisation by transforming attributes with non standard serialisation types e.g. dates to string on the format expected by the parse functions
Usage
sm_plan_format(plan)
Arguments
plan |
the plan to format the attributes |
prepare a plan for serialisation by transforming attributes with non standard serialisation types e.g. dates to string on the format expected by the parse functions
Description
prepare a plan for serialisation by transforming attributes with non standard serialisation types e.g. dates to string on the format expected by the parse functions
Usage
sm_plan_format_bluesky(plan)
Arguments
plan |
list, the plan with the attributes go format |
prepare a plan for serialisation by transforming attributes with non standard serialisation types e.g. dates to string on the format expected by the parse functions
Description
prepare a plan for serialisation by transforming attributes with non standard serialisation types e.g. dates to string on the format expected by the parse functions
Usage
sm_plan_format_mastodon(plan)
Arguments
plan |
list, the plan with the attributes go format |
calculates and returns the estimated progress of a plan using custom attributes
Description
calculates and returns the estimated progress of a plan using custom attributes
Usage
sm_plan_get_progress(plan)
Arguments
plan |
list, the plan to obtain the progress from |
calculates and returns the estimated progress of a plan using custom attributes
Description
calculates and returns the estimated progress of a plan using custom attributes
Usage
sm_plan_get_progress_bluesky(plan)
Arguments
plan |
list, the plan to calculate the progress from |
calculates and returns the estimated progress of a plan using custom attributes
Description
calculates and returns the estimated progress of a plan using custom attributes
Usage
sm_plan_get_progress_mastodon(plan)
Arguments
plan |
list, the plan to calculate the progress from |
returns a list with the custom social media plan attributes with the values for the plan to be run after the plans provided as parameter
Description
returns a list with the custom social media plan attributes with the values for the plan to be run after the plans provided as parameter
Usage
sm_plan_next_attributes(network, plans)
Arguments
network |
char, network the name of the social media |
plans |
list, list of plans to use for calculate new plan attributes |
returns a list with the custom social media plan attributes with the values for the plan to be run after the plans provided as parameter
Description
returns a list with the custom social media plan attributes with the values for the plan to be run after the plans provided as parameter
Usage
sm_plan_next_attributes_bluesky(plans)
Arguments
plans |
list, the list with current plans of the given topic to calculate next plan attributes |
returns a list with the custom social media plan attributes with the values for the plan to be run after the plans provided as parameter
Description
returns a list with the custom social media plan attributes with the values for the plan to be run after the plans provided as parameter
Usage
sm_plan_next_attributes_mastodon(plans)
Arguments
plans |
list, the list with current plans of the given topic to calculate next plan attributes |
Return a message to log what the next query is going to be for the current plan
Description
Return a message to log what the next query is going to be for the current plan
Usage
sm_plan_next_search_info(plan)
Arguments
plan |
list, the plan to obtain the message |
parse custom attributes for a plan in this specific social media and returns them as a named list with attributes in the proper type
Description
parse custom attributes for a plan in this specific social media and returns them as a named list with attributes in the proper type
Usage
sm_plan_parse_attributes(network, ...)
Arguments
network |
char, the name of the social media |
... |
list, triple dot arguments to be passed as a parameter tu underlying functions |
parse custom attributes for a plan in this specific social media and returns them as a named list with attributes in the proper type
Description
parse custom attributes for a plan in this specific social media and returns them as a named list with attributes in the proper type
Usage
sm_plan_parse_attributes_bluesky(...)
Arguments
... |
list, triple dot arguments to be passed as a parameter tu underlying functions |
parse custom attributes for a plan in this specific social media and returns them as a named list with attributes in the proper type
Description
parse custom attributes for a plan in this specific social media and returns them as a named list with attributes in the proper type
Usage
sm_plan_parse_attributes_mastodon(...)
Arguments
... |
list, triple dot arguments to be passed as a parameter tu underlying functions |
Return a message to log what the next query is going to be for the current plan
Description
Return a message to log what the next query is going to be for the current plan
Usage
sm_plan_search_info_bluesky(plan)
Arguments
plan |
list, the plan to print the information about |
Return a message to log what the next query is going to be for the current plan
Description
Return a message to log what the next query is going to be for the current plan
Usage
sm_plan_search_info_mastodon(plan)
Arguments
plan |
list, the plan to print the information about |
Stop collecting from an instance of a federated social media
Description
Removes a domain from the instances a federated social media family collects from.
Usage
sm_remove_instance(family, instance)
Arguments
family |
char, the federated social media family e.g. "mastodon" |
instance |
char, the domain of the instance to stop collecting from |
Details
The posts already collected from this instance are NOT deleted, they stay stored under
the network name of the instance, as does its plan file topics.<family>.<instance>.json and its
access token. Adding the instance back therefore resumes on its former history.
The configuration is not written to disk, call save_config afterwards.
Value
Nothing
See Also
returns the name of a secret belonging to a network
Description
returns the name of a secret belonging to a network
Usage
sm_secret_name(network, name)
Arguments
network |
char, the name of the social media |
name |
char, the name of the secret within the network e.g. "token" |
Details
network identifiers contain dots, which are not safe in every secret backend (secret names are also used as environment variable names, see get_env_secrets), so they are flattened to underscores: the token of "mastodon.mstdn.party" is stored as "mastodon_mstdn_party_token".
Plot the trendline report of episomer dashboard
Description
Generates a trendline chart of number of posts by region for a single topic, including alerts detected using the reweighted version of the EARS algorithm
Usage
trend_line(
sms,
topic,
countries = c(1),
date_type = "created_date",
date_min = "1900-01-01",
date_max = "2100-01-01",
with_quotes = FALSE,
alpha = 0.025,
alpha_outlier = 0.05,
k_decay = 4,
no_historic = 7,
bonferroni_correction = FALSE,
same_weekday_baseline = FALSE
)
Arguments
sms |
Social media |
topic |
Character(1) containing the topic to use for the report |
countries |
Character vector containing the name of the countries and regions to plot or their respective indexes on the Shiny app select, default: c(1) |
date_type |
Character vector specifying the time granularity of the report either 'created_weeknum' or 'created_date', default: 'created_date' |
date_min |
Date indicating start of the reporting period, default: "1900-01-01" |
date_max |
Date indicating end of the reporting period, default: "2100-01-01" |
with_quotes |
Logical value indicating whether to include reposts in the time series, default: FALSE |
alpha |
Numeric(1) value indicating the alert detection confidence, default: 0.025 |
alpha_outlier |
Numeric(1) value indicating the outliers detection confidence for downweighting, default: 0.05 |
k_decay |
Strength of outliers downweighting, default: 4 |
no_historic |
Number of observations to build the baseline for signal detection, default: 7 |
bonferroni_correction |
Logical value indicating whether to apply the Bonferroni correction for signal detection, default: FALSE |
same_weekday_baseline |
Logical value indicating whether to use same day of weeks for building the baseline or consecutive days, default: FALSE |
Details
Produces a multi-region line chart for a particular topic of number of posts collected based on the provided parameters. Alerts will be calculated using a modified version of the EARS algorithm that applies a Farrington inspired downweighting of previous outliers.
Days in this function are considered as contiguous blocks of 24 hours, starting from the previous hour preceding the last collected post.
This function requires that search_loop and detect_loop have already run successfully in order to show results.
Value
A named list containing two elements: 'chart' with the ggplot2 figure and 'data' containing the data frame that was used to build the chart.
See Also
create_map
create_topwords
generate_alerts
detect_loop
search_loop
Examples
## Not run:
message('Please choose the episomer data directory')
setup_config(file.choose())
#Getting trendline for dengue for South America for the last 30 days
trend_line(
topic = "dengue",
countries = "South America",
date_min = as.Date(Sys.time())-30,
date_max=as.Date(Sys.time())
)
## End(Not run)
Updates the local copy of the GeoNames database
Description
Downloading and indexing a fresh version of the GeoNames database from the provided URL
Usage
update_geonames(download = TRUE, assemble = TRUE, index = TRUE)
Arguments
download |
Logical, whether to download geonames database default: TRUE |
assemble |
Logical, whether to calculate the geographical hierarchy to index: TRUE |
index |
Logical, whether to write geographical location in full text index default: TRUE |
Details
Run a one shot task to download and index a local copy of the GeoNames database. The GeoNames geographical database covers all countries and contains over eleven million place names that are available; Creative Commons Attribution 4.0 License.
The URL to download the database from is set on the configuration tab of the Shiny app, in case it changes.
The indexing is developed in Spark and Lucene
A prerequisite to this function is that the search_loop must already have stored collected posts in the search folder and that the task download_dependencies
has been successfully run.
Normally this function is not called directly by the user but from the detect_loop function.
Value
The list of tasks updated with produced messages
See Also
Examples
## Not run:
library(episomer)
# setting up the data folder
message('Please choose the episomer data directory')
setup_config(file.choose())
# geolocating last posts
tasks <- update_geonames()
## End(Not run)
Updates language index and retrain models
Description
Indexing downloaded languages models and proceed to retrain based on manual or automatic annotations
Usage
update_languages()
Details
Index locally downloaded fasttext pretrained models and train entity detection models. A fasttext model is a collection of vectors for a language automatically produced scrolling a big corpus of text that can be used to capture the semantic of a word.
The URL to download the vectors from are set on the configuration tab of the Shiny app.
This task will also update SVM models to predict whether a word is a location that will be used in the geolocation process.
The indexing is developed in SPARK and Lucene.
Normally this function is not called directly by the user but from the setup function.
Value
Nothing
See Also
Examples
## Not run:
library(episomer)
# setting up the data folder
message('Please choose the episomer data directory')
setup_config(file.choose())
# updating language tasks
tasks <- update_languages()
## End(Not run)