Skip to content

Commit 3473d3d

Browse files
authored
Add files via upload
0 parents  commit 3473d3d

9 files changed

Lines changed: 255 additions & 0 deletions

File tree

‎DESCRIPTION‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
Package: scAnnotationBot
2+
Type: Package
3+
Title: Annotates cell clusters in single-cell sequencing analysis.
4+
Version: 1.0.0
5+
Author: Yikun Gao
6+
Maintainer: The package maintainer <www2405637072@163.com>
7+
Description: This package annotates cell clusters in single-cell sequencing analysis by using ERNIEBot or DashScope models.
8+
License: `use_mit_license()`, `use_gpl3_license()` or friends to pick a license
9+
Encoding: UTF-8
10+
LazyData: true
11+
Imports: httr, jsonlite
12+
RoxygenNote: 7.2.3
13+
Suggests:
14+
testthat (>= 3.0.0)
15+
Config/testthat/edition: 3

‎NAMESPACE‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Generated by roxygen2: do not edit by hand
2+
3+
export(DashScopeCellType)
4+
export(ERNIEBotCellType)
5+
6+
importFrom(httr, POST, add_headers, content)
7+
importFrom(jsonlite, toJSON)
8+
importFrom(stats, setNames)

‎R/DashScope.R‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#' @title Annotates cell clusters in single-cell sequencing analysis.
2+
3+
#'
4+
5+
#' @description This package annotates cell clusters in single-cell sequencing analysis by using ERNIEBot or DashScope models.
6+
7+
#' @param api_key character. Obtained from the website https://dashscope.console.aliyun.com/apiKey.
8+
#' @param model character. Check from website https://dashscope.console.aliyun.com/billing, the default value is "qwen-max-longcontext".
9+
#' @param inputTable data.frame returned by FindAllMarkers.
10+
#' @param tissueName The tissue origin of single-cell sequencing data, such as "mouse brain".
11+
#' @param useGeneNumber numeric. The number of genes used for annotating cell types, with a default value of 10.
12+
13+
#' @return character vector
14+
15+
#' @export DashScopeCellType
16+
#' @name DashScopeCellType
17+
18+
library(httr)
19+
library(jsonlite)
20+
DashScopeChat = function(api_key, contentText, model = "qwen-max-longcontext") {
21+
url = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation'
22+
headers = add_headers("Content-Type" = "application/json",
23+
"Authorization" = paste("Bearer", api_key))
24+
json_input = list(
25+
model = model,
26+
input = list(
27+
messages = list(
28+
list(role = "system", content = "You are a tool used for annotating cell types in single-cell sequencing data, strictly executing annotation tasks according to the requirements!"),
29+
list(role = "user", content = contentText)
30+
)
31+
),
32+
parameters = list(result_format = "message")
33+
)
34+
response = POST(url, headers, body = json_input, encode = "json")
35+
response = content(response)
36+
prompt_tokens = response$usage$input_tokens
37+
completion_tokens = response$usage$output_tokens
38+
total_tokens = response$usage$total_tokens
39+
tokenMessage = paste0('Tokens usage report: ',
40+
'\n\t-prompt tokens: ',prompt_tokens,
41+
'\n\t-completion tokens: ',completion_tokens,
42+
'\n\t-total tokens: ',total_tokens,'\n')
43+
cat(tokenMessage)
44+
return(response$output$choices[[1]]$message$content)
45+
}
46+
47+
DashScopeCellType = function(api_key = NULL, model = "qwen-max-longcontext", inputTable, tissueName = NULL, useGeneNumber = 5) {
48+
if(is.null(api_key)) {
49+
print('API key is not available!')
50+
return()
51+
}
52+
clusterNum = length(levels(factor(inputTable$cluster)))
53+
minCluster = as.numeric(levels(factor(inputTable$cluster))[1])
54+
sectionSize = 30
55+
sliceNum = ceiling(clusterNum/sectionSize)
56+
responseList = list()
57+
for (i in 1:sliceNum) {
58+
cat(paste0('----------section ',i,' start----------\n'))
59+
section = inputTable[inputTable$cluster<=sectionSize*i & inputTable$cluster>=minCluster+sectionSize*(i-1),]
60+
markedClusters = tapply(section$gene, list(section$cluster), function(i) paste0(i[1:useGeneNumber], collapse = ","))
61+
message = paste0("Use the following markers to identify the cell types of ", tissueName, " tissue cells. Provide only the cell type names in English, formatted as number followed by a colon and the cell type name in English, with no additional description after the name and the end of the response.",
62+
"\n", paste0(names(markedClusters), ":", unlist(markedClusters), collapse = "\n"))
63+
response = DashScopeChat(api_key = api_key, content = message, model = model)
64+
responseList = append(responseList, response)
65+
}
66+
combinedRes = paste(unlist(responseList), collapse = "\n")
67+
clearedRes = gsub(pattern = "\n", replacement = "", x = combinedRes)
68+
clearedRes = strsplit(clearedRes, "\\d+:")[[1]]
69+
clearedRes = clearedRes[-1]
70+
cellTypes = setNames(clearedRes, levels(factor(inputTable$cluster)))
71+
return(cellTypes)
72+
}

‎R/ERNIEBot.R‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#' @title Annotates cell clusters in single-cell sequencing analysis.
2+
3+
#'
4+
5+
#' @description This package annotates cell clusters in single-cell sequencing analysis by using ERNIEBot or DashScope models.
6+
7+
#' @param account list. Obtained from the website https://console.bce.baidu.com/qianfan/ais/console/applicationConsole/application?_=1720524456151. client_id is the API Key, and client_secret is the Secret Key.
8+
#' @param model character. Check from website https://console.bce.baidu.com/qianfan/ais/console/onlineService. the default value is "completions_pro".
9+
#' @param inputTable data.frame returned by FindAllMarkers.
10+
#' @param tissueName The tissue origin of single-cell sequencing data, such as "mouse brain".
11+
#' @param useGeneNumber numeric. The number of genes used for annotating cell types, with a default value of 10.
12+
13+
#' @return character vector
14+
15+
#' @export ERNIEBotCellType
16+
#' @name ERNIEBotCellType
17+
18+
library(httr)
19+
library(jsonlite)
20+
getAccessToken_ERNIEBot = function(client_id, client_secret) {
21+
url = 'https://aip.baidubce.com/oauth/2.0/token'
22+
headers = c('Content-Type' = 'application/json')
23+
body = list(grant_type = 'client_credentials',
24+
client_id = client_id,
25+
client_secret = client_secret)
26+
response = POST(url, add_headers(headers), body = body)
27+
access_token = content(response)$access_token
28+
return(access_token)
29+
}
30+
31+
ERNIEBotChat = function(access_token, contentText, model = "completions_pro") {
32+
url = paste0('https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/',model)
33+
full_url = paste0(url, "?access_token=", access_token)
34+
headers = c('Content-Type' = 'application/json')
35+
data = list(
36+
messages = list(
37+
list(role = "user", content = contentText)
38+
),
39+
system = 'You are a tool used for annotating cell types in single-cell sequencing data, strictly executing annotation tasks according to the requirements!'
40+
)
41+
json_data = toJSON(data, auto_unbox = TRUE)
42+
response = POST(full_url, add_headers(headers), body = json_data)
43+
response = content(response)
44+
prompt_tokens = response$usage$prompt_tokens
45+
completion_tokens = response$usage$completion_tokens
46+
total_tokens = response$usage$total_tokens
47+
tokenMessage = paste0('Tokens usage report: ',
48+
'\n\t-prompt tokens: ',prompt_tokens,
49+
'\n\t-completion tokens: ',completion_tokens,
50+
'\n\t-total tokens: ',total_tokens, '\n')
51+
cat(tokenMessage)
52+
return(response$result)
53+
}
54+
55+
ERNIEBotCellType = function(account = list(client_id = NULL, client_secret = NULL), model = "completions_pro", inputTable, tissueName = NULL, useGeneNumber = 5) {
56+
if(is.null(account$client_id) || is.null(account$client_secret)) {
57+
print('client_id or client_secret is not available!')
58+
return()
59+
}
60+
access_token = getAccessToken_ERNIEBot(client_id = account$client_id, client_secret = account$client_secret)
61+
clusterNum = length(levels(factor(inputTable$cluster)))
62+
minCluster = as.numeric(levels(factor(inputTable$cluster))[1])
63+
sectionSize = 30
64+
sliceNum = ceiling(clusterNum/sectionSize)
65+
responseList = list()
66+
for (i in 1:sliceNum) {
67+
cat(paste0('----------section ',i,' start----------\n'))
68+
section = inputTable[inputTable$cluster<=sectionSize*i & inputTable$cluster>=minCluster+sectionSize*(i-1),]
69+
markedClusters = tapply(section$gene, list(section$cluster), function(i) paste0(i[1:useGeneNumber], collapse = ","))
70+
message = paste0("Use the following markers to identify the cell types of ", tissueName, " tissue cells. Provide only the cell type names in English, formatted as number followed by a colon and the cell type name in English, with no additional description after the name and the end of the response.",
71+
"\n", paste0(names(markedClusters), ":", unlist(markedClusters), collapse = "\n"))
72+
response = ERNIEBotChat(access_token = access_token, content = message, model = model)
73+
responseList = append(responseList, response)
74+
}
75+
combinedRes = paste(unlist(responseList), collapse = "\n")
76+
clearedRes = gsub(pattern = "\n", replacement = "", x = combinedRes)
77+
clearedRes = strsplit(clearedRes, "\\d+:")[[1]]
78+
clearedRes = clearedRes[-1]
79+
cellTypes = setNames(clearedRes, levels(factor(inputTable$cluster)))
80+
return(cellTypes)
81+
}

‎man/DashScopeCellType.Rd‎

Lines changed: 22 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎man/ERNIEBotCellType.Rd‎

Lines changed: 22 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎scAnnotationBot.Rproj‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
Version: 1.0
2+
3+
RestoreWorkspace: Default
4+
SaveWorkspace: Default
5+
AlwaysSaveHistory: Default
6+
7+
EnableCodeIndexing: Yes
8+
UseSpacesForTab: Yes
9+
NumSpacesForTab: 2
10+
Encoding: UTF-8
11+
12+
RnwWeave: Sweave
13+
LaTeX: pdfLaTeX
14+
15+
AutoAppendNewline: Yes
16+
StripTrailingWhitespace: Yes
17+
18+
BuildType: Package
19+
PackageUseDevtools: Yes
20+
PackageInstallArgs: --no-multiarch --with-keep.source

‎tests/testthat.R‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# This file is part of the standard setup for testthat.
2+
# It is recommended that you do not modify it.
3+
#
4+
# Where should you do additional test configuration?
5+
# Learn more about the roles of various files in:
6+
# * https://r-pkgs.org/tests.html
7+
# * https://testthat.r-lib.org/reference/test_package.html#special-files
8+
9+
library(testthat)
10+
library(scAnnotationBot)
11+
12+
test_check("scAnnotationBot")

‎tests/testthat/test-DashScope.R‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
test_that("multiplication works", {
2+
expect_equal(2 * 2, 4)
3+
})

0 commit comments

Comments
 (0)