{"id":22966706,"url":"https://github.com/favstats/perspective","last_synced_at":"2026-01-15T23:04:13.495Z","repository":{"id":44964251,"uuid":"185277133","full_name":"favstats/peRspective","owner":"favstats","description":"An R wrapper for Conversation AI's Perspective API","archived":false,"fork":false,"pushed_at":"2021-07-14T07:29:13.000Z","size":40437,"stargazers_count":49,"open_issues_count":2,"forks_count":5,"subscribers_count":4,"default_branch":"master","last_synced_at":"2023-11-20T16:08:20.498Z","etag":null,"topics":["machine-learning","perspective-api","rstats","toxic-comment-classification"],"latest_commit_sha":null,"homepage":"https://favstats.github.io/peRspective","language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/favstats.png","metadata":{"files":{"readme":"README.Rmd","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-05-06T21:53:53.000Z","updated_at":"2023-11-15T20:16:28.000Z","dependencies_parsed_at":"2022-07-13T12:50:28.467Z","dependency_job_id":null,"html_url":"https://github.com/favstats/peRspective","commit_stats":null,"previous_names":[],"tags_count":1,"template":null,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/favstats%2FpeRspective","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/favstats%2FpeRspective/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/favstats%2FpeRspective/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/favstats%2FpeRspective/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/favstats","download_url":"https://codeload.github.com/favstats/peRspective/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246758373,"owners_count":20828919,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["machine-learning","perspective-api","rstats","toxic-comment-classification"],"created_at":"2024-12-14T20:45:16.758Z","updated_at":"2026-01-15T23:04:13.489Z","avatar_url":"https://github.com/favstats.png","language":"HTML","funding_links":[],"categories":[],"sub_categories":[],"readme":"---\noutput: github_document\n---\n\n\u003c!-- README.md is generated from README.Rmd. Please edit that file --\u003e\n\n```{r, setup, include = FALSE}\nknitr::opts_chunk$set(\n  collapse = TRUE,\n  comment = \"#\u003e\",\n  fig.path = \"man/figures/README-\",\n  out.width = \"100%\",\n  message = F,\n  warning = F\n)\n\nggplot2::theme_set(ggplot2::theme_minimal())\n\nlibrary(dplyr)\n```\n\n\n# peRspective \u003cimg src=\"man/figures/perspective.png\" width=\"160px\" align=\"right\"/\u003e\n\n\n```{r, echo = FALSE, results='asis', eval = T}\n\nlibrary(badger)\n\n\ngit_repo \u003c- \"favstats/peRspective\"\n\ncat(\n  \"[![](https://cranlogs.r-pkg.org/badges/grand-total/peRspective)](https://cran.rstudio.com/web/packages/peRspective/index.html)\",\n  \" [![R-CMD-check](https://github.com/favstats/peRspective/workflows/R-CMD-check/badge.svg)](https://github.com/favstats/peRspective/actions)\",\n  # badge_custom(\"My 1st Package\", \"Ever\", \"blue\"),\n  badge_cran_release(\"peRspective\", \"blue\"),\n  \"[![Codecov test coverage](https://codecov.io/gh/favstats/peRspective/branch/master/graph/badge.svg)](https://codecov.io/gh/favstats/peRspective?branch=master)\",\n\tbadge_code_size(git_repo),\n\tbadge_last_commit(git_repo)\n)\n```\n\nPerspective is an API that uses machine learning models to score the perceived impact a comment might have on a conversation. [Website](http://www.perspectiveapi.com/).\n\n`peRspective` provides access to the API using the R programming language.\n\nFor an excellent documentation of the Perspective API see [here](https://github.com/conversationai/perspectiveapi/tree/master/2-api).\n\n\u003e This is a work-in-progress project and I welcome feedback and pull requests!\n\n## Overview\n\n+ [Setup](https://github.com/favstats/peRspective#setup)\n+ [Models](https://github.com/favstats/peRspective#models)\n+ [Usage](https://github.com/favstats/peRspective#usage)\n    + [`prsp_score`](https://github.com/favstats/peRspective#prsp_score)\n    + [`prsp_stream`](https://github.com/favstats/peRspective#prsp_stream)\n\n\n\n\n## Setup\n\n### Get an API key\n\n[Follow these steps](https://developers.perspectiveapi.com/s/docs-get-started) as outlined by the Perspective API to get an API key.\n\n**NOTE:** Perspective API made some changes recently and you now have to apply for an API key via a Google Form.\n\n### Quota and character length Limits\n\nBe sure to check your quota limit! You can learn more about Perspective API quota limit by visiting [your google cloud project's Perspective API page](https://console.cloud.google.com/apis/api/commentanalyzer.googleapis.com/quotas).\n\n## Models\n\nFor detailed overview of the used models [see here](https://developers.perspectiveapi.com/s/about-the-api-attributes-and-languages).\n\n\n### Languages in production \n\nCurrently, Perspective API has production `TOXICITY` and `SEVERE_TOXICITY` attributes in the following languages:\n\n+ English (en)\n+ Spanish (es)\n+ French (fr)\n+ German (de)\n+ Portuguese (pt)\n+ Italian (it)\n+ Russian (ru)\n\n\n### Toxicity attributes\n \n| Attribute name               | Type  | Description                                                                                                                                                                                                                                                                             | Available Languages                                                                               |\n|------------------------------|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------|\n| `TOXICITY`                     | prod. | A rude, disrespectful, or unreasonable comment that is likely to make people leave a discussion.                                                                                                                                                                                        | English (en), Spanish (es), French (fr), German (de), Portuguese (pt), Italian (it), Russian (ru) |\n| `TOXICITY_EXPERIMENTAL`        | exp.  | A rude, disrespectful, or unreasonable comment that is likely to make people leave a discussion.                                                                                                                                                                                        | Arabic (ar)                                                                                       |\n| `SEVERE_TOXICITY`              | prod. | A very hateful, aggressive, disrespectful comment or otherwise very likely to make a user leave a discussion or give up on sharing their perspective. This attribute is much less sensitive to more mild forms of toxicity, such as comments that include positive uses of curse words. | en, fr, es, de, it, pt, ru                                                                        |\n| `SEVERE_TOXICITY_EXPERIMENTAL` | exp.  | A very hateful, aggressive, disrespectful comment or otherwise very likely to make a user leave a discussion or give up on sharing their perspective. This attribute is much less sensitive to more mild forms of toxicity, such as comments that include positive uses of curse words. | ar                                                                                                |\n| `IDENTITY_ATTACK`              | prod. | Negative or hateful comments targeting someone because of their identity.                                                                                                                                                                                                               | de, it, pt, ru, en                                                                                |\n| `IDENTITY_ATTACK_EXPERIMENTAL` | exp.  | Negative or hateful comments targeting someone because of their identity.                                                                                                                                                                                                               | fr, es, ar                                                                                        |\n| `INSULT`                       | prod. | Insulting, inflammatory, or negative comment towards a person or a group of people.                                                                                                                                                                                                     | de, it, pt, ru, en                                                                                |\n| `INSULT_EXPERIMENTAL`          | exp.  | Insulting, inflammatory, or negative comment towards a person or a group of people.                                                                                                                                                                                                     | fr, es, ar                                                                                        |\n| `PROFANITY`                    | prod. | Swear words, curse words, or other obscene or profane language.                                                                                                                                                                                                                         | de, it, pt, ru, en                                                                                |\n| `PROFANITY_EXPERIMENTAL`       | exp.  | Swear words, curse words, or other obscene or profane language.                                                                                                                                                                                                                         | fr, es, ar                                                                                        |\n| `THREAT`                       | prod. | Describes an intention to inflict pain, injury, or violence against an individual or group.                                                                                                                                                                                             | de, it, pt, ru, en                                                                                |\n| `THREAT_EXPERIMENTAL`          | exp.  | Describes an intention to inflict pain, injury, or violence against an individual or group.                                                                                                                                                                                             | fr, es, ar                                                                                        |\n| `SEXUALLY_EXPLICIT`            | exp.  | Contains references to sexual acts, body parts, or other lewd content.                                                                                                                                                                                                                  | en                                                                                                |\n| `FLIRTATION`                   | exp.  | Pickup lines, complimenting appearance, subtle sexual innuendos, etc.                                                                                                                                                                                                                   | en                                                                                                |\n \n### New York Times attributes\n\nThese attributes are experimental because they are trained on a single source of comments\u0026mdash;New York Times (NYT) data tagged by their moderation team\u0026mdash;and therefore may not work well for every use case. \n\n| Attribute name | Type | Description | Language |\n| -------------------- | ---- | ----------- | -------- |\n| `ATTACK_ON_AUTHOR` | exp. | Attack on the author of an article or post. | en |\n| `ATTACK_ON_COMMENTER` | exp. | Attack on fellow commenter. | en |\n| `INCOHERENT` | exp. | Difficult to understand, nonsensical. | en |\n| `INFLAMMATORY` | exp. | Intending to provoke or inflame. | en |\n| `LIKELY_TO_REJECT` | exp. | Overall measure of the likelihood for the comment to be rejected according to the NYT's moderation. | en |\n| `OBSCENE` | exp. | Obscene or vulgar language such as cursing. | en |\n| `SPAM` | exp. | Irrelevant and unsolicited commercial content. | en |\n| `UNSUBSTANTIAL` | exp. | Trivial or short comments. | en |\n\n\nA character vector that includes all`peRspective`  supported models can be obtained like this:\n\n```{r}\nc(\n  peRspective::prsp_models,\n  peRspective::prsp_exp_models\n)\n```\n\n## Usage\n\nFirst, install package from GitHub:\n\n```{r, eval = F}\ndevtools::install_github(\"favstats/peRspective\")\n```\n\nLoad package:\n\n```{r}\nlibrary(peRspective)\n```\n\nAlso the `tidyverse` for examples.\n\n```{r, eval = F}\nlibrary(tidyverse)\n```\n\n```{r, eval = F, echo=F}\nkey \u003c- readr::read_lines(\"../keys/prsp_simon.txt\")\n\nSys.setenv(perspective_api_key = key)\n```\n\n\n\n**Define your key variable.**\n\n`peRspective` functions will read the API key from environment variable `perspective_api_key`. In order to add your key to your environment file, you can use the function `edit_r_environ()` from the [`usethis` package](https://usethis.r-lib.org/).\n\n```{r, eval = F}\nusethis::edit_r_environ()\n```\n\n\nThis will open your .Renviron file in your text editor. Now, you can add the following line to it:\n\n```{r, eval = F}\nperspective_api_key=\"YOUR_API_KEY\"\n```\n\nSave the file and restart R for the changes to take effect.\n\nAlternatively, you can provide an explicit definition of your API key with each function call using the `key` argument.\n\n### `prsp_score`\n\nNow you can use `prsp_score` to score your comments with various models provided by the Perspective API.\n\n```{r, eval = T}\n\nmy_text \u003c- \"You wrote this? Wow. This is dumb and childish, please go f**** yourself.\"\n\ntext_scores \u003c- prsp_score(\n           text = my_text, \n           languages = \"en\",\n           score_model = peRspective::prsp_models\n           )\n\ntext_scores %\u003e% \n  tidyr::gather() %\u003e% \n  dplyr::mutate(key = forcats::fct_reorder(key, value)) %\u003e% \n  ggplot2::ggplot(ggplot2::aes(key, value)) +\n  ggplot2::geom_col() +\n  ggplot2::coord_flip() +\n  ggplot2::ylim(0, 1) +\n  ggplot2::geom_hline(yintercept = 0.5, linetype = \"dashed\") +\n  ggplot2::labs(x = \"Model\", y = \"Probability\", title = \"Perspective API Results\")\n```\n\n```{r, echo=F}\nSys.sleep(1)\n```\n\n\nA Trump Tweet:\n\n```{r}\ntrump_tweet \u003c- \"The Fake News Media has NEVER been more Dishonest or Corrupt than it is right now. There has never been a time like this in American History. Very exciting but also, very sad! Fake News is the absolute Enemy of the People and our Country itself!\"\n\ntext_scores \u003c- prsp_score(\n           trump_tweet, \n           score_sentences = F,\n           score_model = peRspective::prsp_models\n           )\n\ntext_scores %\u003e% \n  tidyr::gather() %\u003e% \n  dplyr::mutate(key = forcats::fct_reorder(key, value)) %\u003e% \n  ggplot2::ggplot(ggplot2::aes(key, value)) +\n  ggplot2::geom_col() +\n  ggplot2::coord_flip() +\n  ggplot2::ylim(0, 1) +\n  ggplot2::geom_hline(yintercept = 0.5, linetype = \"dashed\") +\n  ggplot2::labs(x = \"Model\", y = \"Probability\", title = \"Perspective API Results\")\n```\n\n```{r, echo=F}\nSys.sleep(1)\n```\n\nInstead of scoring just entire comments you can also score individual sentences with `score_sentences = T`. In this case the Perspective API will automatically split your text into reasonable sentences and score them in addition to an overall score.\n\n```{r, eval = T, fig.width=12, fig.height=8}\ntrump_tweet \u003c- \"The Fake News Media has NEVER been more Dishonest or Corrupt than it is right now. There has never been a time like this in American History. Very exciting but also, very sad! Fake News is the absolute Enemy of the People and our Country itself!\"\n\ntext_scores \u003c- prsp_score(\n           trump_tweet, \n           score_sentences = T,\n           score_model = peRspective::prsp_models\n           )\n\ntext_scores %\u003e% \n  tidyr::unnest(sentence_scores) %\u003e% \n  dplyr::select(type, score, sentences) %\u003e% \n  tidyr::gather(value, key, -sentences, -score) %\u003e% \n  dplyr::mutate(key = forcats::fct_reorder(key, score)) %\u003e% \n  ggplot2::ggplot(ggplot2::aes(key, score)) +\n  ggplot2::geom_col() +\n  ggplot2::coord_flip() +\n  ggplot2::facet_wrap(~sentences, ncol = 2) +\n  ggplot2::geom_hline(yintercept = 0.5, linetype = \"dashed\") +\n  ggplot2::labs(x = \"Model\", y = \"Probability\", title = \"Perspective API Results\")\n\n\n```\n\n```{r, echo=F}\nSys.sleep(1)\n```\n\nYou can also use Spanish (`es`) for `TOXICITY`, `SEVERE_TOXICITY` and `_EXPERIMENTAL` models.\n\n```{r}\nspanish_text \u003c- \"gastan en cosas que de nada sirven-nunca tratan de saber la verdad del funcionalismo de nuestro sistema solar y origen del cosmos-falso por Kepler. LAS UNIVERSIDADES DEL MUNDO NO SABEN ANALIZAR VERDAD O MENTIRA-LO QUE DICE KEPLER\"\n\n\ntext_scores \u003c- prsp_score(\n           text = spanish_text, \n           languages = \"es\",\n           score_model = c(\"TOXICITY\", \"SEVERE_TOXICITY\", \"INSULT_EXPERIMENTAL\")\n           )\n\ntext_scores %\u003e% \n  tidyr::gather() %\u003e% \n  dplyr::mutate(key = forcats::fct_reorder(key, value)) %\u003e% \n  ggplot2::ggplot(ggplot2::aes(key, value)) +\n  ggplot2::geom_col() +\n  ggplot2::coord_flip() +\n  ggplot2::geom_hline(yintercept = 0.5, linetype = \"dashed\")  +\n  ggplot2::labs(x = \"Model\", y = \"Probability\", title = \"Perspective API Results\")\n```\n\n**NOTE:** Your provided text will be stored by the Perspective API for future research. This option is the default. If the supplied texts are private or any of the authors of the texts are below 13 years old, `doNotStore` should be set to `TRUE.`\n\n### `prsp_stream`\n\n```{r, echo=F}\nSys.sleep(1)\n```\n\nSo far we have only seen how to get individual comments or sentences scored. But what if you would like to run the function for an entire dataset with a text column? This is where `prsp_stream` comes in. At its core `prsp_stream` is a loop implemented within `purrr::map` to iterate over your text column. To use it let's first generate a mock tibble.\n\n```{r}\ntext_sample \u003c- tibble(\n       ctext = c(\"You wrote this? Wow. This is dumb and childish, please go f**** yourself.\",\n                 \"I don't know what to say about this but it's not good. The commenter is just an idiot\",\n                 \"This goes even further!\",\n                 \"What the hell is going on?\",\n                 \"Please. I don't get it. Explain it again\",\n                 \"Annoying and irrelevant! I'd rather watch the paint drying on the wall!\"),\n       textid = c(\"#efdcxct\", \"#ehfcsct\", \n                  \"#ekacxwt\",  \"#ewatxad\", \n                  \"#ekacswt\",  \"#ewftxwd\")\n       )\n```\n\n\n```{r, echo=F}\nSys.sleep(1)\n```\n\n`prsp_stream` requires a `text` and `text_id` column. It wraps `prsp_score` and takes all its arguments. Let's run the most basic version:\n\n```{r, message=T}\ntext_sample %\u003e%\n  prsp_stream(text = ctext,\n              text_id = textid,\n              score_model = c(\"TOXICITY\", \"SEVERE_TOXICITY\"))\n```\n\nYou receive a `tibble` with your desired scorings including the `text_id` to match your score with your original dataframe.\n\nNow, the problem is that sometimes the call might fail at some point. It is therefore suggested to set `safe_output = TRUE`. This will put the function into a `purrr::safely` environment to ensure that your function will keep running even if you encounter errors. \n\nLet's try it out with a new dataset that contains text that the Perspective API can't score\n\n```{r, echo=F}\nSys.sleep(1)\n```\n\n```{r}\ntext_sample \u003c- tibble(\n       ctext = c(\"You wrote this? Wow. This is dumb and childish, please go f**** yourself.\",\n                 \"I don't know what to say about this but it's not good. The commenter is just an idiot\",\n                 ## empty string\n                 \"\",\n                 \"This goes even further!\",\n                 \"What the hell is going on?\",\n                 \"Please. I don't get it. Explain it again\",\n                 ## Gibberish\n                 \"kdlfkmgkdfmgkfmg\",\n                 \"Annoying and irrelevant! I'd rather watch the paint drying on the wall!\",\n                 ## Gibberish\n                 \"Hippi Hoppo\"),\n       textid = c(\"#efdcxct\", \"#ehfcsct\", \n                  \"#ekacxwt\",  \"#ewatxad\", \n                  \"#ekacswt\",  \"#ewftxwd\", \n                  \"#eeadswt\",  \"#enfhxed\",\n                  \"#efdmjd\")\n       )\n```\n\nAnd run the function with `safe_output = TRUE`.\n\n```{r, echo=F}\nSys.sleep(1)\n```\n\n```{r, message=T}\ntext_sample %\u003e%\n  prsp_stream(text = ctext,\n              text_id = textid,\n              score_model = c(\"TOXICITY\", \"SEVERE_TOXICITY\", \"INSULT\"),\n              safe_output = T)\n```\n\n`safe_output = T` will also provide us with the error messages that occured so that we can check what went wrong!\n\nFinally, there is one last argument: `verbose = TRUE`. Enable this argument and thanks to [`crayon`](https://github.com/r-lib/crayon) you will receive beautiful console output that guides you along the way, showing you errors and text scores as you go.\n\n```{r, echo=F}\nSys.sleep(1)\n```\n\n\n```{r, eval = F}\ntext_sample %\u003e%\n  prsp_stream(text = ctext,\n              text_id = textid,\n              score_model = c(\"TOXICITY\", \"SEVERE_TOXICITY\"),\n              verbose = T,\n              safe_output = T)\n```\n\n![](man/figures/prsp_stream_output.png)\n\nOr the (not as pretty) output in Markdown\n\n```{r, echo = F}\ntext_sample %\u003e%\n  prsp_stream(text = ctext,\n              text_id = textid,\n              score_model = c(\"TOXICITY\", \"SEVERE_TOXICITY\"),\n              verbose = T,\n              safe_output = T)\n\n\n```\n\n\n## Citation\n\nThank you for using peRspective! Please consider citing:\n\nVotta, Fabio. (2019). peRspective: A wrapper for the Perspective API. Source: https://github.com/favstats.\n\n\n\u003cdiv\u003eIcons made by \u003ca href=\"https://www.freepik.com/?__hstc=57440181.1504a979705d81fb44d4169a0ccdf2ae.1558036002089.1558036002089.1558036002089.1\u0026__hssc=57440181.4.1558036002090\u0026__hsfp=2902986854\" title=\"Freepik\"\u003eFreepik\u003c/a\u003e from \u003ca href=\"https://www.flaticon.com/\" \t\t\t    title=\"Flaticon\"\u003ewww.flaticon.com\u003c/a\u003e is licensed by \u003ca href=\"http://creativecommons.org/licenses/by/3.0/\" \t\t\t    title=\"Creative Commons BY 3.0\" target=\"_blank\"\u003eCC 3.0 BY\u003c/a\u003e\u003c/div\u003e","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffavstats%2Fperspective","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffavstats%2Fperspective","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffavstats%2Fperspective/lists"}