repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
opencommit
github_2023
typescript
209
di-sukharev
BlakeEddie
@@ -1,228 +1,193 @@ import { - ChatCompletionRequestMessage, - ChatCompletionRequestMessageRoleEnum + ChatCompletionRequestMessage, + ChatCompletionRequestMessageRoleEnum } from 'openai'; -import {api} from './api'; -import {DEFAULT_MODEL_TOKEN_LIMIT, getConfig} from './commands/config'; -import {mergeDiffs} from './utils/mergeDiffs'; -import {i18n, I18nLocals} from './i18n'; -import {tokenCount} from './utils/tokenCount'; +import { api } from './api'; +import { DEFAULT_MODEL_TOKEN_LIMIT, getConfig } from './commands/config'; +import { mergeDiffs } from './utils/mergeDiffs'; +import { tokenCount } from './utils/tokenCount'; +import { getMainCommitPrompt } from './prompts'; const config = getConfig(); -const translation = i18n[(config?.OCO_LANGUAGE as I18nLocals) || 'en']; - -const INIT_MESSAGES_PROMPT: Array<ChatCompletionRequestMessage> = [ - { - role: ChatCompletionRequestMessageRoleEnum.System, - // prettier-ignore - content: `You are to act as the author of a commit message in git. Your mission is to create clean and comprehensive commit messages in the conventional commit convention and explain WHAT were the changes and WHY the changes were done. I'll send you an output of 'git diff --staged' command, and you convert it into a commit message. -${config?.OCO_EMOJI ? 'Use GitMoji convention to preface the commit.' : 'Do not preface the commit with anything.'} -${config?.OCO_DESCRIPTION ? 'Add a short description of WHY the changes are done after the commit message. Don\'t start it with "This commit", just describe the changes.' : "Don't add any descriptions to the commit, only commit message."} -Use the present tense. Lines must not be longer than 74 characters. Use ${translation.localLanguage} to answer.` - }, - { - role: ChatCompletionRequestMessageRoleEnum.User, - content: `diff --git a/src/server.ts b/src/server.ts -index ad4db42..f3b18a9 100644 ---- a/src/server.ts -+++ b/src/server.ts -@@ -10,7 +10,7 @@ -import { - initWinstonLogger(); - - const app = express(); - -const port = 7799; - +const PORT = 7799; - - app.use(express.json()); - -@@ -34,6 +34,6 @@ -app.use((_, res, next) => { - // ROUTES - app.use(PROTECTED_ROUTER_URL, protectedRouter); - - -app.listen(port, () => { - - console.log(\`Server listening on port \${port}\`); - +app.listen(process.env.PORT || PORT, () => { - + console.log(\`Server listening on port \${PORT}\`); - });` - }, - { - role: ChatCompletionRequestMessageRoleEnum.Assistant, - content: `${config?.OCO_EMOJI ? '🐛 ' : ''}${translation.commitFix} -${config?.OCO_EMOJI ? '✨ ' : ''}${translation.commitFeat} -${config?.OCO_DESCRIPTION ? translation.commitDescription : ''}` - } -]; -const generateCommitMessageChatCompletionPrompt = ( - diff: string -): Array<ChatCompletionRequestMessage> => { - const chatContextAsCompletionRequest = [...INIT_MESSAGES_PROMPT]; +const generateCommitMessageChatCompletionPrompt = async ( + diff: string +): Promise<Array<ChatCompletionRequestMessage>> => { + const INIT_MESSAGES_PROMPT = await getMainCommitPrompt(); + + const chatContextAsCompletionRequest = [...INIT_MESSAGES_PROMPT]; - chatContextAsCompletionRequest.push({ - role: ChatCompletionRequestMessageRoleEnum.User, - content: diff - }); + chatContextAsCompletionRequest.push({ + role: ChatCompletionRequestMessageRoleEnum.User, + content: diff + }); - return chatContextAsCompletionRequest; + // fs.writeFile( + // `.commitlint-debug`, + // JSON.stringify(chatContextAsCompletionRequest, null, 2) + // );
```suggestion ```
opencommit
github_2023
typescript
209
di-sukharev
di-sukharev
@@ -0,0 +1,79 @@ +import { spinner } from '@clack/prompts'; + +import { api } from '../../api'; +import { getConfig } from '../../commands/config'; +import { i18n, I18nLocals } from '../../i18n'; +import { COMMITLINT_LLM_CONFIG_PATH } from './constants'; +import { computeHash } from './crypto'; +import { commitlintPrompts, inferPromptsFromCommitlintConfig } from './prompts'; +import { getCommitLintPWDConfig } from './pwd-commitlint'; +import { CommitlintLLMConfig } from './types'; +import * as utils from './utils'; + +const config = getConfig(); +const translation = i18n[(config?.OCO_LANGUAGE as I18nLocals) || 'en']; + +export const configureCommitlintIntegration = async (force = false) => { + const spin = spinner(); + spin.start('Loading @commitlint configuration'); + + const fileExists = await utils.commitlintLLMConfigExists(); + + let commitLintConfig = await getCommitLintPWDConfig(); + + // debug complete @commitlint configuration
do we need this?
opencommit
github_2023
typescript
209
di-sukharev
di-sukharev
@@ -0,0 +1,79 @@ +import { spinner } from '@clack/prompts'; + +import { api } from '../../api'; +import { getConfig } from '../../commands/config'; +import { i18n, I18nLocals } from '../../i18n'; +import { COMMITLINT_LLM_CONFIG_PATH } from './constants'; +import { computeHash } from './crypto'; +import { commitlintPrompts, inferPromptsFromCommitlintConfig } from './prompts'; +import { getCommitLintPWDConfig } from './pwd-commitlint'; +import { CommitlintLLMConfig } from './types'; +import * as utils from './utils'; + +const config = getConfig(); +const translation = i18n[(config?.OCO_LANGUAGE as I18nLocals) || 'en']; + +export const configureCommitlintIntegration = async (force = false) => { + const spin = spinner(); + spin.start('Loading @commitlint configuration'); + + const fileExists = await utils.commitlintLLMConfigExists(); + + let commitLintConfig = await getCommitLintPWDConfig(); + + // debug complete @commitlint configuration + // await fs.writeFile( + // `${OPENCOMMIT_COMMITLINT_CONFIG}-commitlint-debug`, + // JSON.stringify(commitLintConfig, null, 2) + // ); + + const hash = await computeHash(JSON.stringify(commitLintConfig)); + + spin.stop(`Read @commitlint configuration (hash: ${hash})`); + + if (fileExists) { + // Check if we need to update the prompts. + const { hash: existingHash } = await utils.getCommitlintLLMConfig(); + if (hash === existingHash && !force) { + spin.stop( + 'Hashes are the same, no need to update the config. Run "force" command to bypass.' + ); + return; + } + } + + spin.start('Generating consistency with given @commitlint rules'); + + const prompts = inferPromptsFromCommitlintConfig(commitLintConfig); + + const consistencyPrompts = + commitlintPrompts.GEN_COMMITLINT_CONSISTENCY_PROMPT(prompts); + + // debug prompt which will generate a consistency
do we need this?
opencommit
github_2023
others
132
di-sukharev
di-sukharev
@@ -155,4 +157,4 @@ Or follow the process of your IDE Source Control feature, when it calls `git com ## Payments -You pay for your own requests to OpenAI API. OpenCommit uses ChatGPT official model, that is ~10x times cheaper than GPT-3 and ~6x times cheaper than GPT-4. +You pay for your own requests to OpenAI API. OpenCommit uses ChatGPT (3.5-turbo) official model, that is ~15x times cheaper than GPT-4.
this is also in dev, why is that highlighted?
opencommit
github_2023
typescript
171
di-sukharev
di-sukharev
@@ -67,7 +67,7 @@ export const configValidators = { [CONFIG_KEYS.OPENAI_MAX_TOKENS](value: any) { validateConfig( CONFIG_KEYS.OPENAI_MAX_TOKENS, - typeof value === 'number', + isNaN(+value),
it should be `typeof value === 'number' && !isNaN(+value)`
opencommit
github_2023
typescript
25
di-sukharev
austinamorusoyardstick
@@ -75,14 +80,13 @@ const configPath = pathJoin(homedir(), '.opencommit'); export const getConfig = (): ConfigType | null => { const configExists = existsSync(configPath); - if (!configExists) return null; - const configFile = readFileSync(configPath, 'utf8'); - const config = iniParse(configFile); + const configFile = configExists ? readFileSync(configPath, 'utf8') : ''; + const config = configFile? iniParse(configFile) : {}; - for (const configKey of Object.keys(config)) { + for (const configKey in CONFIG_KEYS) { const validValue = configValidators[configKey as CONFIG_KEYS]( - config[configKey] + config.hasOwnProperty(configKey) ? config[configKey] : process.env[configKey]
Wouldn't you want the inverse of this setting the .env file as the priority and not the global config as priority? Usually I think local config then fallback to global. I can also see just wanting to force the usage of one or the other via a process.env flag too.
opencommit
github_2023
typescript
25
di-sukharev
di-sukharev
@@ -25,7 +25,7 @@ export const prepareCommitMessageHook = async () => { const config = getConfig(); - if (!config?.OPENAI_API_KEY) { + if (!config?.OPENCOMMIT_OPENAI_API_KEY) { throw new Error( 'No OPEN_AI_API exists. Set your OPEN_AI_API=<key> in ~/.opencommit'
```suggestion 'No OPENCOMMIT_OPENAI_API_KEY exists. Set your OPENCOMMIT_OPENAI_API_KEY=<key> in "~/.opencommit" or local ".env" file' ```
opencommit
github_2023
typescript
25
di-sukharev
AdrielBento
@@ -7,10 +7,13 @@ import { intro, outro } from '@clack/prompts'; import chalk from 'chalk'; import { COMMANDS } from '../CommandsEnum'; +import * as dotenv from 'dotenv' +dotenv.config() + export enum CONFIG_KEYS {
@0xKrauser A new setting was added in this PR: https://github.com/di-sukharev/opencommit/pull/31. So it will be necessary to update the branch to adjust it
opencommit
github_2023
typescript
70
di-sukharev
di-sukharev
@@ -61,58 +62,127 @@ ${chalk.grey('——————————————————')} ${commitMessage} ${chalk.grey('——————————————————')}` ); + + const promptUserConfirm = async(commitText: string ) => { + + const isCommitConfirmedByUser = await select({ + message: 'Confirm the commit message', + options: [ + {value: "yes", label: "Yes"}, + {value: "no", label: "No"}, + {value: "edit", label: "Edit"} + ] + + }); - const isCommitConfirmedByUser = await confirm({ - message: 'Confirm the commit message' - }); - - if (isCommitConfirmedByUser && !isCancel(isCommitConfirmedByUser)) { - const { stdout } = await execa('git', [ - 'commit', - '-m', - commitMessage, - ...extraArgs - ]); - - outro(`${chalk.green('✔')} successfully committed`); - - outro(stdout); - const remotes = await getGitRemotes(); - - if (remotes.length === 1) { - const isPushConfirmedByUser = await confirm({ - message: 'Do you want to run `git push`?' - }); - - if (isPushConfirmedByUser && !isCancel(isPushConfirmedByUser)) { - const pushSpinner = spinner(); - pushSpinner.start(`Running \`git push ${remotes[0]}\``); - const { stdout } = await execa('git', ['push', remotes[0]]); - pushSpinner.stop( - `${chalk.green('✔')} successfully pushed all commits to ${remotes[0]}` - ); - if (stdout) outro(stdout); + if (isCommitConfirmedByUser == "yes" && !isCancel(isCommitConfirmedByUser)) { + const { stdout } = await execa('git', [ + 'commit', + '-m', + commitText, + ...extraArgs + ]); + + outro(`${chalk.green('✔')} successfully committed`); + + outro(stdout); + const remotes = await getGitRemotes(); + + if (remotes.length === 1) { + const isPushConfirmedByUser = await confirm({ + message: 'Do you want to run `git push`?' + }); + + if (isPushConfirmedByUser && !isCancel(isPushConfirmedByUser)) { + const pushSpinner = spinner(); + pushSpinner.start(`Running \`git push ${remotes[0]}\``); + const { stdout } = await execa('git', ['push', remotes[0]]); + pushSpinner.stop( + `${chalk.green('✔')} successfully pushed all commits to ${remotes[0]}` + ); + if (stdout) outro(stdout); + } + } else { + const selectedRemote = (await select({ + message: 'Choose a remote to push to', + options: remotes.map((remote) => ({ value: remote, label: remote })) + })) as string; + + if (!isCancel(selectedRemote)) { + const pushSpinner = spinner(); + pushSpinner.start(`Running \`git push ${selectedRemote}\``); + const { stdout } = await execa('git', ['push', selectedRemote]); + pushSpinner.stop( + `${chalk.green( + '✔' + )} successfully pushed all commits to ${selectedRemote}` + ); + + if (stdout) outro(stdout); + } else outro(`${chalk.gray('✖')} process cancelled`); + } + } else if (isCommitConfirmedByUser == "edit" && !isCancel(isCommitConfirmedByUser)) { + await promptUserEdit(commitText) + } else if (isCommitConfirmedByUser == "no" && !isCancel(isCommitConfirmedByUser)) { + outro(`👋 exiting`); + } + } + + const promptUserEdit = async(commitText: string) => { + let commitLines = commitText.split("\n") + let updatedCommitMessage + + if (commitLines.length > 1 ) { + let newCommitLines = [] + + for (const line of commitLines) { + if (line !== "") { + const newLine = await text({ + message: 'Update line:', + initialValue: line, + placeholder: "", + validate(value) { + if (line == commitLines[commitLines.length -1] && newCommitLines.length == 0 && value == "") { + return "Message cannot be empty" + } + } + }) + + if (typeof newLine == 'symbol') { + process.exit(0) + } + + if (newLine !== undefined) { + newCommitLines.push(newLine) + } + } } + + updatedCommitMessage = newCommitLines.join("\n\n") + } else { - const selectedRemote = (await select({ - message: 'Choose a remote to push to', - options: remotes.map((remote) => ({ value: remote, label: remote })) - })) as string; - - if (!isCancel(selectedRemote)) { - const pushSpinner = spinner(); - pushSpinner.start(`Running \`git push ${selectedRemote}\``); - const { stdout } = await execa('git', ['push', selectedRemote]); - pushSpinner.stop( - `${chalk.green( - '✔' - )} successfully pushed all commits to ${selectedRemote}` - ); - - if (stdout) outro(stdout); - } else outro(`${chalk.gray('✖')} process cancelled`); + updatedCommitMessage = await text({ + message: 'Update the commit message:', + initialValue: commitLines[0], + validate: (value) => value == "" ? "Message cannot be empty" : "" + }) + } + + if (typeof updatedCommitMessage == 'symbol') { + process.exit(0)
it exports `isCancel(updatedCommitMessage)` function, you should use it for consistency
opencommit
github_2023
typescript
70
di-sukharev
di-sukharev
@@ -60,79 +62,147 @@ ${chalk.grey('——————————————————')} ${commitMessage} ${chalk.grey('——————————————————')}` ); + + const promptUserConfirm = async(commitText: string ) => { + + const isCommitConfirmedByUser = await select({ + message: 'Confirm the commit message', + options: [ + {value: "yes", label: "Yes"}, + {value: "no", label: "No"}, + {value: "edit", label: "Edit"} + ] + + }); - const isCommitConfirmedByUser = await confirm({ - message: 'Confirm the commit message?' - }); - - if (isCommitConfirmedByUser && !isCancel(isCommitConfirmedByUser)) { - const { stdout } = await execa('git', [ - 'commit', - '-m', - commitMessage, - ...extraArgs - ]); - - outro(`${chalk.green('✔')} successfully committed`); - - outro(stdout); - - const remotes = await getGitRemotes(); - - if (!remotes.length) { - const { stdout } = await execa('git', ['push']); - if (stdout) outro(stdout); - process.exit(0); - } - - if (remotes.length === 1) { - const isPushConfirmedByUser = await confirm({ - message: 'Do you want to run `git push`?' - }); - - if (isPushConfirmedByUser && !isCancel(isPushConfirmedByUser)) { - const pushSpinner = spinner(); - - pushSpinner.start(`Running \`git push ${remotes[0]}\``); + if (isCommitConfirmedByUser == "yes" && !isCancel(isCommitConfirmedByUser)) { + const { stdout } = await execa('git', [ + 'commit', + '-m', + commitText, + ...extraArgs + ]); - const { stdout } = await execa('git', [ - 'push', - '--verbose', - remotes[0] - ]); + outro(`${chalk.green('✔')} successfully committed`); - pushSpinner.stop( - `${chalk.green('✔')} successfully pushed all commits to ${remotes[0]}` - ); + outro(stdout); + + const remotes = await getGitRemotes(); + if (!remotes.length) { + const { stdout } = await execa('git', ['push']); if (stdout) outro(stdout); - } else { - outro('`git push` aborted'); process.exit(0); } - } else { - const selectedRemote = (await select({ - message: 'Choose a remote to push to', - options: remotes.map((remote) => ({ value: remote, label: remote })) - })) as string; - - if (!isCancel(selectedRemote)) { - const pushSpinner = spinner(); - - pushSpinner.start(`Running \`git push ${selectedRemote}\``); - const { stdout } = await execa('git', ['push', selectedRemote]); + if (remotes.length === 1) { + const isPushConfirmedByUser = await confirm({ + message: 'Do you want to run `git push`?' + }); + + if (isPushConfirmedByUser && !isCancel(isPushConfirmedByUser)) { + const pushSpinner = spinner(); + + pushSpinner.start(`Running \`git push ${remotes[0]}\``); + + const { stdout } = await execa('git', [ + 'push', + '--verbose', + remotes[0] + ]); + + pushSpinner.stop( + `${chalk.green('✔')} successfully pushed all commits to ${remotes[0]}` + ); + + if (stdout) outro(stdout); + } else { + const selectedRemote = (await select({ + message: 'Choose a remote to push to', + options: remotes.map((remote) => ({ value: remote, label: remote })) + })) as string; + + if (!isCancel(selectedRemote)) { + const pushSpinner = spinner(); + pushSpinner.start(`Running \`git push ${selectedRemote}\``); + const { stdout } = await execa('git', ['push', selectedRemote]); + pushSpinner.stop( + `${chalk.green( + '✔' + )} successfully pushed all commits to ${selectedRemote}` + ); + + if (stdout) outro(stdout); + } else { + outro('`git push` aborted'); + process.exit(0); + } + } + } + } else if (isCommitConfirmedByUser == "edit" && !isCancel(isCommitConfirmedByUser)) { + + let defaultEditor = process.env.EDITOR || (process.platform === 'win32' ? 'notepad.exe' : 'vi'); + let defaultOpenCommand + let linuxTermFlag = '' + + switch (os.platform()) { + case 'darwin': + defaultOpenCommand = 'open' + break + case 'win32': + defaultOpenCommand = 'start' + break + case 'linux': + if ( + defaultEditor == 'vi' || + defaultEditor == 'vim' || + defaultEditor == 'nvim' || + defaultEditor == 'nano' || + defaultEditor == 'micro' || + defaultEditor == 'emacs' + ) { + defaultOpenCommand = 'x-terminal-emulator' + linuxTermFlag = '-e' + break + } else { + defaultOpenCommand = 'xdg-open' + break + } + } + + //const editSpinner = spinner()
remove comment
opencommit
github_2023
typescript
70
di-sukharev
di-sukharev
@@ -60,79 +62,147 @@ ${chalk.grey('——————————————————')} ${commitMessage} ${chalk.grey('——————————————————')}` ); + + const promptUserConfirm = async(commitText: string ) => { + + const isCommitConfirmedByUser = await select({ + message: 'Confirm the commit message', + options: [ + {value: "yes", label: "Yes"}, + {value: "no", label: "No"}, + {value: "edit", label: "Edit"} + ] + + }); - const isCommitConfirmedByUser = await confirm({ - message: 'Confirm the commit message?' - }); - - if (isCommitConfirmedByUser && !isCancel(isCommitConfirmedByUser)) { - const { stdout } = await execa('git', [ - 'commit', - '-m', - commitMessage, - ...extraArgs - ]); - - outro(`${chalk.green('✔')} successfully committed`); - - outro(stdout); - - const remotes = await getGitRemotes(); - - if (!remotes.length) { - const { stdout } = await execa('git', ['push']); - if (stdout) outro(stdout); - process.exit(0); - } - - if (remotes.length === 1) { - const isPushConfirmedByUser = await confirm({ - message: 'Do you want to run `git push`?' - }); - - if (isPushConfirmedByUser && !isCancel(isPushConfirmedByUser)) { - const pushSpinner = spinner(); - - pushSpinner.start(`Running \`git push ${remotes[0]}\``); + if (isCommitConfirmedByUser == "yes" && !isCancel(isCommitConfirmedByUser)) { + const { stdout } = await execa('git', [ + 'commit', + '-m', + commitText, + ...extraArgs + ]); - const { stdout } = await execa('git', [ - 'push', - '--verbose', - remotes[0] - ]); + outro(`${chalk.green('✔')} successfully committed`); - pushSpinner.stop( - `${chalk.green('✔')} successfully pushed all commits to ${remotes[0]}` - ); + outro(stdout); + + const remotes = await getGitRemotes(); + if (!remotes.length) { + const { stdout } = await execa('git', ['push']); if (stdout) outro(stdout); - } else { - outro('`git push` aborted'); process.exit(0); } - } else { - const selectedRemote = (await select({ - message: 'Choose a remote to push to', - options: remotes.map((remote) => ({ value: remote, label: remote })) - })) as string; - - if (!isCancel(selectedRemote)) { - const pushSpinner = spinner(); - - pushSpinner.start(`Running \`git push ${selectedRemote}\``); - const { stdout } = await execa('git', ['push', selectedRemote]); + if (remotes.length === 1) { + const isPushConfirmedByUser = await confirm({ + message: 'Do you want to run `git push`?' + }); + + if (isPushConfirmedByUser && !isCancel(isPushConfirmedByUser)) { + const pushSpinner = spinner(); + + pushSpinner.start(`Running \`git push ${remotes[0]}\``); + + const { stdout } = await execa('git', [ + 'push', + '--verbose', + remotes[0] + ]); + + pushSpinner.stop( + `${chalk.green('✔')} successfully pushed all commits to ${remotes[0]}` + ); + + if (stdout) outro(stdout); + } else { + const selectedRemote = (await select({ + message: 'Choose a remote to push to', + options: remotes.map((remote) => ({ value: remote, label: remote })) + })) as string; + + if (!isCancel(selectedRemote)) { + const pushSpinner = spinner(); + pushSpinner.start(`Running \`git push ${selectedRemote}\``); + const { stdout } = await execa('git', ['push', selectedRemote]); + pushSpinner.stop( + `${chalk.green( + '✔' + )} successfully pushed all commits to ${selectedRemote}` + ); + + if (stdout) outro(stdout); + } else { + outro('`git push` aborted'); + process.exit(0); + } + } + } + } else if (isCommitConfirmedByUser == "edit" && !isCancel(isCommitConfirmedByUser)) { + + let defaultEditor = process.env.EDITOR || (process.platform === 'win32' ? 'notepad.exe' : 'vi'); + let defaultOpenCommand + let linuxTermFlag = '' + + switch (os.platform()) { + case 'darwin': + defaultOpenCommand = 'open' + break + case 'win32': + defaultOpenCommand = 'start' + break + case 'linux': + if ( + defaultEditor == 'vi' || + defaultEditor == 'vim' || + defaultEditor == 'nvim' || + defaultEditor == 'nano' || + defaultEditor == 'micro' || + defaultEditor == 'emacs' + ) { + defaultOpenCommand = 'x-terminal-emulator' + linuxTermFlag = '-e' + break + } else { + defaultOpenCommand = 'xdg-open' + break + } + } + + //const editSpinner = spinner() + //editSpinner.start('Please close the file when you are done editing it.') + + fs.writeFileSync('tmp_commit.txt', commitText); + + outro('🙏 Please close the file when you are done editing it.') + + const { } = await execa(`${defaultOpenCommand}`, [linuxTermFlag, defaultEditor, 'tmp_commit.txt']); + + process.stdin.resume(); + + //editSpinner.stop('Thank you!')
same
opencommit
github_2023
typescript
48
di-sukharev
AdrielBento
@@ -47,6 +62,7 @@ export const hookCommand = command( ); } + console.log("made it")
@matt-degraffenreid I think you forgot to remove that log ```suggestion ```
opencommit
github_2023
typescript
43
di-sukharev
di-sukharev
@@ -198,4 +198,4 @@ export async function commit( } process.exit(0); -} +}
could you remove this change pls :)
opencommit
github_2023
typescript
42
di-sukharev
di-sukharev
@@ -78,39 +71,32 @@ ${chalk.grey('——————————————————')}` outro(stdout); const remotes = await getGitRemotes(); - + const currentBranch = await getCurrentBranch(); + if (remotes.length === 1) { - const isPushConfirmedByUser = await confirm({ - message: 'Do you want to run `git push`?' - }); - - if (isPushConfirmedByUser && !isCancel(isPushConfirmedByUser)) { - const pushSpinner = spinner(); - pushSpinner.start(`Running \`git push ${remotes[0]}\``); - const { stdout } = await execa('git', ['push', remotes[0]]); - pushSpinner.stop( - `${chalk.green('✔')} successfully pushed all commits to ${remotes[0]}` - ); - if (stdout) outro(stdout); - } - } else { - const selectedRemote = (await select({ - message: 'Choose a remote to push to', - options: remotes.map((remote) => ({ value: remote, label: remote })) - })) as string; - - if (!isCancel(selectedRemote)) { - const pushSpinner = spinner(); - pushSpinner.start(`Running \`git push ${selectedRemote}\``); - const { stdout } = await execa('git', ['push', selectedRemote]); - pushSpinner.stop( - `${chalk.green( - '✔' - )} successfully pushed all commits to ${selectedRemote}` - ); - - if (stdout) outro(stdout); - } else outro(`${chalk.gray('✖')} process cancelled`); + const isPushConfirmedByUser = await confirm({
prettier issue
opencommit
github_2023
typescript
42
di-sukharev
di-sukharev
@@ -185,6 +172,8 @@ export async function commit( .join('\n')}` ); + await generateCommitMessageFromGitDiff(staged.diff);
this is old code :) have you tested the code running `npm run dev`? it doesn't work :0
opencommit
github_2023
typescript
20
di-sukharev
di-sukharev
@@ -55,9 +61,17 @@ ${chalk.grey('——————————————————')}` if (isPushConfirmedByUser && !isCancel(isPushConfirmedByUser)) { const pushSpinner = spinner(); - pushSpinner.start('Running `git push`'); - const { stdout } = await execa('git', ['push']); - pushSpinner.stop(`${chalk.green('✔')} successfully pushed all commits`); + // Get the list of remotes and ask the user to choose the desired remote + const remotes = await getGitRemotes(); + const selectedRemote = await select({
that's an awesome job! let's do `if (remotes.length === 1) push the remote without asking`. WDYT?
opencommit
github_2023
typescript
35
di-sukharev
AdrielBento
@@ -0,0 +1,23 @@ +import { getOpenCommitLatestVersion } from '../api'; +import currentPackage from '../../package.json' assert { type: 'json' }; +import chalk from 'chalk'; +export const checkIsLatestVersion = async () => { + const latestVersion = await getOpenCommitLatestVersion(); + + if (latestVersion) { + const currentVersion = currentPackage.version; + + if (currentVersion !== latestVersion) { + console.warn( + chalk.yellow(
@nader-zouaoui What do you think about already suggesting the command to perform the update? ex: > 🎉 Update to latest version by running: `npm update opencommit`
opencommit
github_2023
others
35
di-sukharev
AdrielBento
@@ -1,6 +1,6 @@ { "name": "opencommit", - "version": "1.1.11",
@nader-zouaoui the current version is already 1.1.16. Is your branch up to date?
opencommit
github_2023
others
22
di-sukharev
di-sukharev
@@ -84,6 +84,18 @@ To remove description: oc config set description=false ``` +### Ignore files +You can ignore files from submission to OpenGPT by creating a `.opencommitignore` file. For example:
```suggestion You can ignore files from submission to OpenAI by creating a `.opencommitignore` file. For example: ```
opencommit
github_2023
others
6
di-sukharev
di-sukharev
@@ -53,10 +54,12 @@ "dotenv": "^16.0.3", "esbuild": "^0.15.18", "eslint": "^8.28.0", + "prettier": "^2.8.4", "ts-node": "^10.9.1", "typescript": "^4.9.3" }, "dependencies": { + "@bdsqqq/try": "^2.3.1",
let's change this to a separate file with code: ``` export const trytm = async <T>( promise: Promise<T>, ): Promise<[T, null] | [null, Error]> => { try { const data = await promise; return [data, null]; } catch (throwable) { if (throwable instanceof Error) return [null, throwable]; throw throwable; } }; ```
opencommit
github_2023
typescript
6
di-sukharev
di-sukharev
@@ -65,7 +80,14 @@ ${chalk.grey('——————————————————')}` }; export async function commit(isStageAllFlag = false) { + const [stagedFiles, errorStagedFiles] = await trytm(getStagedFiles());
this is same as line 94, pick one pls
opencommit
github_2023
typescript
6
di-sukharev
di-sukharev
@@ -65,7 +80,14 @@ ${chalk.grey('——————————————————')}` }; export async function commit(isStageAllFlag = false) { + const [stagedFiles, errorStagedFiles] = await trytm(getStagedFiles()); + const [changedFiles, errorChangedFiles] = await trytm(getChangedFiles());
nice idea of checking isAnyFileChanged
opencommit
github_2023
typescript
6
di-sukharev
di-sukharev
@@ -47,3 +47,34 @@ export const getStagedGitDiff = async ( diff }; }; + +export const getStagedFiles = async (): Promise<string[]> => {
this is same as `getStagedGitDiff` line 21, but i would refactor it, so it's really a `get` function. now it's also staging files. could you refactor it to something like `getAndSetStagedDiff`? using your `gitAdd` function
opencommit
github_2023
typescript
6
di-sukharev
di-sukharev
@@ -65,13 +79,28 @@ ${chalk.grey('——————————————————')}` }; export async function commit(isStageAllFlag = false) { + if (isStageAllFlag) { + await gitAdd({ files: await getChangedFiles() });
<3
opencommit
github_2023
typescript
6
di-sukharev
di-sukharev
@@ -13,37 +13,41 @@ const excludeBigFilesFromDiff = ['*-lock.*', '*.lock'].map( (file) => `:(exclude)${file}` ); -export interface StagedDiff { - files: string[]; - diff: string; -} - -export const getStagedGitDiff = async ( - isStageAllFlag = false -): Promise<StagedDiff | null> => { - if (isStageAllFlag) { - const stageAllSpinner = spinner(); - stageAllSpinner.start('Staging all changes'); - await execa('git', ['add', '.']); - stageAllSpinner.stop('Done'); - } - - const diffStaged = ['diff', '--staged']; +export const getStagedFiles = async (): Promise<string[]> => { const { stdout: files } = await execa('git', [ - ...diffStaged, + 'diff', '--name-only', - ...excludeBigFilesFromDiff
why do you remove this? package-lock.json is gonna be counted like a change, and it's too big for openAI api, splitting it in chunks looks like overengineering and waste of tokens sent to the API. I'd provide an error message if only `excluded` files are staged like: "staged files are .lock files which are excluded by default as it's too big, commit it yourself, don't waste your api tokens". WDYT?
opencommit
github_2023
typescript
6
di-sukharev
di-sukharev
@@ -17,7 +17,9 @@ export const prepareCommitMessageHook = async () => { if (commitSource) return; - const staged = await getStagedGitDiff(); + await gitAdd({ files: await getChangedFiles() });
```suggestion const changedFiles = await getChangedFiles(); if (changedFiles) await gitAdd({ files: changedFiles }); else { outro("No changes detected, write some code and run `oc` again"); process.exit(1); } ```
opencommit
github_2023
typescript
6
di-sukharev
di-sukharev
@@ -9,41 +9,88 @@ export const assertGitRepo = async () => { } }; -const excludeBigFilesFromDiff = ['*-lock.*', '*.lock'].map( - (file) => `:(exclude)${file}` -); - -export interface StagedDiff { - files: string[]; - diff: string; -} - -export const getStagedGitDiff = async ( - isStageAllFlag = false -): Promise<StagedDiff | null> => { - if (isStageAllFlag) { - const stageAllSpinner = spinner(); - stageAllSpinner.start('Staging all changes'); - await execa('git', ['add', '.']); - stageAllSpinner.stop('Done'); - } +export const someFilesExcludedMessage = (files: string[]) => { + return text({ + message: `Some files are .lock files which are excluded by default as it's too big, commit it yourself, don't waste your api tokens. \n${files + .filter((file) => file.includes('.lock') || file.includes('-lock.')) + .join('\n') + }` + }); +}; - const diffStaged = ['diff', '--staged']; +export const getStagedFiles = async (): Promise<string[]> => { const { stdout: files } = await execa('git', [ - ...diffStaged, + 'diff', '--name-only', - ...excludeBigFilesFromDiff + '--cached' + ]); + + if (!files) return []; + + const excludedFiles = files + .split('\n') + .filter((file) => !!file) + .filter((file) => file.includes('.lock') || file.includes('-lock.'));
great!
opencommit
github_2023
typescript
6
di-sukharev
di-sukharev
@@ -9,41 +9,88 @@ export const assertGitRepo = async () => { } }; -const excludeBigFilesFromDiff = ['*-lock.*', '*.lock'].map( - (file) => `:(exclude)${file}` -); - -export interface StagedDiff { - files: string[]; - diff: string; -} - -export const getStagedGitDiff = async ( - isStageAllFlag = false -): Promise<StagedDiff | null> => { - if (isStageAllFlag) { - const stageAllSpinner = spinner(); - stageAllSpinner.start('Staging all changes'); - await execa('git', ['add', '.']); - stageAllSpinner.stop('Done'); - } +export const someFilesExcludedMessage = (files: string[]) => { + return text({ + message: `Some files are .lock files which are excluded by default as it's too big, commit it yourself, don't waste your api tokens. \n${files + .filter((file) => file.includes('.lock') || file.includes('-lock.')) + .join('\n') + }` + }); +}; - const diffStaged = ['diff', '--staged']; +export const getStagedFiles = async (): Promise<string[]> => { const { stdout: files } = await execa('git', [ - ...diffStaged, + 'diff', '--name-only', - ...excludeBigFilesFromDiff + '--cached' + ]); + + if (!files) return []; + + const excludedFiles = files + .split('\n') + .filter((file) => !!file)
```suggestion .filter(Boolean) ```
opencommit
github_2023
typescript
6
di-sukharev
di-sukharev
@@ -106,14 +140,37 @@ export async function commit(isStageAllFlag = false) { await commit(true);
```suggestion return await commit(true); ```
mysqldump
github_2023
go
7
jarvanstack
jarvanstack
@@ -42,7 +42,6 @@ func NewDBWrapper(db *sql.DB, dryRun bool) *DBWrapper { } func (db *DBWrapper) Exec(query string, args ...interface{}) (sql.Result, error) { - fmt.Printf("[SQL] query: %s , args: %v \n", query, args)
这行代码对于某些情况下的调试是十分有用的,如果你不想要输出调试信息。可以添加一个 option 来控制是否输出调试信息。
gwater2
github_2023
others
39
meetric1
bloodycop7
@@ -0,0 +1,1214 @@ + +This is the gwater localization file. Everything in this file is added as a language string to gmod. +Note that the translation cannot be longer than 4000 bytes (1 english character is 1 byte). + +Input format: +"gwater2.key_here"=[[ +Your translation here +]] + +Do NOT edit 'gwater2.key_here' + +Use decent language, be literate and don't be a barbarian. :) + +------------------------ +-------- ERRORS -------- +------------------------ + +"gwater2.error.modulenotinstalled"=[[ +!!!МОЛЯ, ПРОЧЕТЕТЕ МЕ!!! + +GWATER2 НЕ МОЖЕ ДА НАМЕРИ МОДУЛ! + +Това вероятно означава, че не сте инсталирали DLL файловете на GWater2. +Моля, инсталирайте бинарните файлове и се уверете, че DLL файловете на GWater2 се намират в папката GarrysMod/garrysmod/lua/bin. +Имайте предвид, че GWater2 НЕ работи нативно на Linux или Mac системи. +]] + +"gwater2.error.modulefailedtoload.1"=[[ +!!!МОЛЯ, ПРОЧЕТЕТЕ МЕ!!! + +GWATER2 НЕ МОЖЕ ДА ЗАРЕДИ МОДУЛ! +Това вероятно означава, че не сте инсталирали FleX бинарните файлове правилно в папката GarrysMod/ +Моля, проверете инсталацията си и рестартирайте играта. +]] + +"gwater2.error.modulefailedtoload.2"=[[ +Ако сте сигурни, че сте го инсталирали правилно, рестартирайте играта няколко пъти. Това е проблем с кода на Garry и не мога да го поправя. +]] + +"gwater2.error.modulefailedtoload.3"=[[ +Не се колебайте да потърсите помощ, ако проблемът продължава. МОЛЯ, предоставете следните 3 реда, когато искате помощ: + +Грешка: %s +Клон: %s +jit.arch: %s +]] + +"gwater2.error.chatlog"=[[ +Не може да се зареди! Моля, проверете менюто с проблеми за повече информация (ESC меню -> долния десен ъгъл) +]] + +"gwater2.gun.adv.notloaded"=[[ +GWATER2 не можа да се зареди! +Проверете конзолата и менюто с проблеми (ESC меню -> долния ляв ъгъл) за грешки +]] + +------------------------ +------ WATER GUN ------- +------------------------ + +"gwater2.gun.adv.controls.lclk"=[[ +Ляво-клик за създаване на частици
Wouldn't it be better to say "Ляв-клик"
gwater2
github_2023
others
39
meetric1
bloodycop7
@@ -0,0 +1,1214 @@ + +This is the gwater localization file. Everything in this file is added as a language string to gmod. +Note that the translation cannot be longer than 4000 bytes (1 english character is 1 byte). + +Input format: +"gwater2.key_here"=[[ +Your translation here +]] + +Do NOT edit 'gwater2.key_here' + +Use decent language, be literate and don't be a barbarian. :) + +------------------------ +-------- ERRORS -------- +------------------------ + +"gwater2.error.modulenotinstalled"=[[ +!!!МОЛЯ, ПРОЧЕТЕТЕ МЕ!!! + +GWATER2 НЕ МОЖЕ ДА НАМЕРИ МОДУЛ! + +Това вероятно означава, че не сте инсталирали DLL файловете на GWater2. +Моля, инсталирайте бинарните файлове и се уверете, че DLL файловете на GWater2 се намират в папката GarrysMod/garrysmod/lua/bin. +Имайте предвид, че GWater2 НЕ работи нативно на Linux или Mac системи. +]] + +"gwater2.error.modulefailedtoload.1"=[[ +!!!МОЛЯ, ПРОЧЕТЕТЕ МЕ!!! + +GWATER2 НЕ МОЖЕ ДА ЗАРЕДИ МОДУЛ! +Това вероятно означава, че не сте инсталирали FleX бинарните файлове правилно в папката GarrysMod/ +Моля, проверете инсталацията си и рестартирайте играта. +]] + +"gwater2.error.modulefailedtoload.2"=[[ +Ако сте сигурни, че сте го инсталирали правилно, рестартирайте играта няколко пъти. Това е проблем с кода на Garry и не мога да го поправя. +]] + +"gwater2.error.modulefailedtoload.3"=[[ +Не се колебайте да потърсите помощ, ако проблемът продължава. МОЛЯ, предоставете следните 3 реда, когато искате помощ: + +Грешка: %s +Клон: %s +jit.arch: %s +]] + +"gwater2.error.chatlog"=[[ +Не може да се зареди! Моля, проверете менюто с проблеми за повече информация (ESC меню -> долния десен ъгъл) +]] + +"gwater2.gun.adv.notloaded"=[[ +GWATER2 не можа да се зареди! +Проверете конзолата и менюто с проблеми (ESC меню -> долния ляв ъгъл) за грешки +]] + +------------------------ +------ WATER GUN ------- +------------------------ + +"gwater2.gun.adv.controls.lclk"=[[ +Ляво-клик за създаване на частици +]] + +"gwater2.gun.adv.controls.rclk"=[[ +Дясно-клик за отваряне на менюто на оръжието
Same thing here, "Десен-клик"
gwater2
github_2023
others
39
meetric1
bloodycop7
@@ -0,0 +1,1214 @@ + +This is the gwater localization file. Everything in this file is added as a language string to gmod. +Note that the translation cannot be longer than 4000 bytes (1 english character is 1 byte). + +Input format: +"gwater2.key_here"=[[ +Your translation here +]] + +Do NOT edit 'gwater2.key_here' + +Use decent language, be literate and don't be a barbarian. :) + +------------------------ +-------- ERRORS -------- +------------------------ + +"gwater2.error.modulenotinstalled"=[[ +!!!МОЛЯ, ПРОЧЕТЕТЕ МЕ!!! + +GWATER2 НЕ МОЖЕ ДА НАМЕРИ МОДУЛ! + +Това вероятно означава, че не сте инсталирали DLL файловете на GWater2. +Моля, инсталирайте бинарните файлове и се уверете, че DLL файловете на GWater2 се намират в папката GarrysMod/garrysmod/lua/bin. +Имайте предвид, че GWater2 НЕ работи нативно на Linux или Mac системи. +]] + +"gwater2.error.modulefailedtoload.1"=[[ +!!!МОЛЯ, ПРОЧЕТЕТЕ МЕ!!! + +GWATER2 НЕ МОЖЕ ДА ЗАРЕДИ МОДУЛ! +Това вероятно означава, че не сте инсталирали FleX бинарните файлове правилно в папката GarrysMod/ +Моля, проверете инсталацията си и рестартирайте играта. +]] + +"gwater2.error.modulefailedtoload.2"=[[ +Ако сте сигурни, че сте го инсталирали правилно, рестартирайте играта няколко пъти. Това е проблем с кода на Garry и не мога да го поправя. +]] + +"gwater2.error.modulefailedtoload.3"=[[ +Не се колебайте да потърсите помощ, ако проблемът продължава. МОЛЯ, предоставете следните 3 реда, когато искате помощ: + +Грешка: %s +Клон: %s +jit.arch: %s +]] + +"gwater2.error.chatlog"=[[ +Не може да се зареди! Моля, проверете менюто с проблеми за повече информация (ESC меню -> долния десен ъгъл) +]] + +"gwater2.gun.adv.notloaded"=[[ +GWATER2 не можа да се зареди! +Проверете конзолата и менюто с проблеми (ESC меню -> долния ляв ъгъл) за грешки +]] + +------------------------ +------ WATER GUN ------- +------------------------ + +"gwater2.gun.adv.controls.lclk"=[[ +Ляво-клик за създаване на частици +]] + +"gwater2.gun.adv.controls.rclk"=[[ +Дясно-клик за отваряне на менюто на оръжието +]] + +"gwater2.gun.adv.controls.reload"=[[ +Презаредете, за да премахнете всички +]] + +------------------------ +------- ENTITIES ------- +------------------------ + +"gwater2.ent.drain.side"=[[ +ТАЗИ СТРАНА +ИЗТЕЧА ЛИКВИД
Replace ЛИКВИД with ТЕЧНОСТ
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,318 @@ +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 + +from .song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + self._proto = song._proto.lyrics + if self._proto is None: + self._proto = song_pb2.Lyrics() + self.lines = [LyricLine(lyrics=self, proto=line_proto) for line_proto in self._proto.lines]
Python models shouldn't have any private fields other than the proto and a reference to its parent instance. This is because we write and read based on the proto, all the model instances is only created on-demand and only serves as a wrapper of the proto. For lines: You should get lines on-demand, otherwise you will need to maintain this list when anything inside it changes, also there is a pretty significant performance drawback if you maintain this list all the time. To do this you can simply rewrite `def get_lines` as a generator similar to [this](https://github.com/tuneflow/tuneflow-py/blob/main/src/tuneflow_py/models/song.py#L47)
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,318 @@ +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 + +from .song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + self._proto = song._proto.lyrics + if self._proto is None: + self._proto = song_pb2.Lyrics() + self.lines = [LyricLine(lyrics=self, proto=line_proto) for line_proto in self._proto.lines] + + # Operations that syncronize the proto with line instances
Same here, this is anti-pattern.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,313 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + lyric_line = LyricLine(lyrics=self, start_tick=start_tick) + if resolve_order: + self.sort_lines() + return lyric_line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + line = self.create_line(start_tick=start_tick, resolve_order=False) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + def get_index_of_line_at_tick(self, tick: int): + if len(self._proto.lines) == 0: + return -1 + start_search_index = lower_equal( + self._proto.lines, tick, key=lambda line: line.start_tick + ) + for index in range(start_search_index, -1, -1): + line = self._proto.lines[index] + if tick >= line.start_tick and tick <= line.end_tick: + return index + return -1 + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + start_tick=line_proto.words[0].start_tick, + proto=line_proto + ) + + def get_line_at_index(self, index: int): + proto = self._proto.lines[index] + if len(proto.words) == 0: + raise Exception("Lyric line has no words") + return LyricLine( + lyrics=self, + start_tick=proto.words[0].start_tick, + proto=self._proto.lines[index] + ) + + def remove_line_at_index(self, index: int): + if index < 0 or index >= len(self._proto.lines): + return + self._proto.lines.pop(index) + + def clone_line(self, original_line: "LyricLine"): + line = LyricLine(lyrics=self, start_tick=original_line.get_start_tick()) + for lyric_word in original_line.get_words(): + line.create_word( + word=lyric_word.get_word(), + start_tick=lyric_word.get_start_tick(), + end_tick=lyric_word.get_end_tick(), + ) + self._proto.lines.append(line._proto) + return line + + def sort_lines(self): + self._proto.lines.sort(key=lambda line: line.words[0].start_tick) + + def clear(self): + del self._proto.lines[:] + + +class LyricLine: + def __init__(self, lyrics: Lyrics, start_tick: int, proto: song_pb2.LyricLine | None = None) -> None: + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = self.lyrics._proto.lines.add() + + if len(self._proto.words) == 0: + placeholder_word = LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + self._proto.words.append(placeholder_word._proto) + + + def is_empty(self) -> bool: + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List["LyricWord"]:
You can define the 3 classes in the order of LyricWord, LyricLine and Lyrics so that you can use the original type instead strings.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,313 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + lyric_line = LyricLine(lyrics=self, start_tick=start_tick) + if resolve_order: + self.sort_lines() + return lyric_line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + line = self.create_line(start_tick=start_tick, resolve_order=False) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + def get_index_of_line_at_tick(self, tick: int): + if len(self._proto.lines) == 0: + return -1 + start_search_index = lower_equal( + self._proto.lines, tick, key=lambda line: line.start_tick + ) + for index in range(start_search_index, -1, -1): + line = self._proto.lines[index] + if tick >= line.start_tick and tick <= line.end_tick: + return index + return -1 + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + start_tick=line_proto.words[0].start_tick, + proto=line_proto + ) + + def get_line_at_index(self, index: int): + proto = self._proto.lines[index] + if len(proto.words) == 0: + raise Exception("Lyric line has no words") + return LyricLine( + lyrics=self, + start_tick=proto.words[0].start_tick, + proto=self._proto.lines[index] + ) + + def remove_line_at_index(self, index: int): + if index < 0 or index >= len(self._proto.lines): + return + self._proto.lines.pop(index) + + def clone_line(self, original_line: "LyricLine"): + line = LyricLine(lyrics=self, start_tick=original_line.get_start_tick()) + for lyric_word in original_line.get_words(): + line.create_word( + word=lyric_word.get_word(), + start_tick=lyric_word.get_start_tick(), + end_tick=lyric_word.get_end_tick(), + ) + self._proto.lines.append(line._proto) + return line + + def sort_lines(self): + self._proto.lines.sort(key=lambda line: line.words[0].start_tick) + + def clear(self): + del self._proto.lines[:] + + +class LyricLine: + def __init__(self, lyrics: Lyrics, start_tick: int, proto: song_pb2.LyricLine | None = None) -> None: + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = self.lyrics._proto.lines.add()
I'm a little hesitant to inexplicitly add this line into lyrics here since this seems like a side-effect and is not expected to happen in the constructor. We should probably add the line in Lyrics.create_line or Lyrics.create_line_from_string instead.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,313 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True):
Add comments for the function so that people know how to use it. Same below. Feel free to check the documentation in typescript SDK.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,313 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + lyric_line = LyricLine(lyrics=self, start_tick=start_tick) + if resolve_order: + self.sort_lines() + return lyric_line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + line = self.create_line(start_tick=start_tick, resolve_order=False) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + def get_index_of_line_at_tick(self, tick: int): + if len(self._proto.lines) == 0: + return -1 + start_search_index = lower_equal( + self._proto.lines, tick, key=lambda line: line.start_tick
Do you need to pass a line proto as the second param here? Since we are comparing them as line protos.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,313 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + lyric_line = LyricLine(lyrics=self, start_tick=start_tick) + if resolve_order: + self.sort_lines() + return lyric_line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + line = self.create_line(start_tick=start_tick, resolve_order=False) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + def get_index_of_line_at_tick(self, tick: int): + if len(self._proto.lines) == 0: + return -1 + start_search_index = lower_equal( + self._proto.lines, tick, key=lambda line: line.start_tick + ) + for index in range(start_search_index, -1, -1): + line = self._proto.lines[index] + if tick >= line.start_tick and tick <= line.end_tick: + return index + return -1 + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + start_tick=line_proto.words[0].start_tick, + proto=line_proto + ) + + def get_line_at_index(self, index: int): + proto = self._proto.lines[index] + if len(proto.words) == 0: + raise Exception("Lyric line has no words") + return LyricLine( + lyrics=self, + start_tick=proto.words[0].start_tick, + proto=self._proto.lines[index] + ) + + def remove_line_at_index(self, index: int): + if index < 0 or index >= len(self._proto.lines): + return + self._proto.lines.pop(index) + + def clone_line(self, original_line: "LyricLine"):
Since we are building models as proto wrappers, cloning a model instance is simply as easy as cloning the proto, which you can simply do with CopyFrom, example: https://github.com/tuneflow/tuneflow-py/blob/main/src/tuneflow_py/models/track.py#L406
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,313 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + lyric_line = LyricLine(lyrics=self, start_tick=start_tick) + if resolve_order: + self.sort_lines() + return lyric_line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + line = self.create_line(start_tick=start_tick, resolve_order=False) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + def get_index_of_line_at_tick(self, tick: int): + if len(self._proto.lines) == 0: + return -1 + start_search_index = lower_equal( + self._proto.lines, tick, key=lambda line: line.start_tick + ) + for index in range(start_search_index, -1, -1): + line = self._proto.lines[index] + if tick >= line.start_tick and tick <= line.end_tick: + return index + return -1 + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + start_tick=line_proto.words[0].start_tick, + proto=line_proto + ) + + def get_line_at_index(self, index: int): + proto = self._proto.lines[index] + if len(proto.words) == 0: + raise Exception("Lyric line has no words") + return LyricLine( + lyrics=self, + start_tick=proto.words[0].start_tick, + proto=self._proto.lines[index] + ) + + def remove_line_at_index(self, index: int): + if index < 0 or index >= len(self._proto.lines): + return + self._proto.lines.pop(index) + + def clone_line(self, original_line: "LyricLine"): + line = LyricLine(lyrics=self, start_tick=original_line.get_start_tick()) + for lyric_word in original_line.get_words(): + line.create_word( + word=lyric_word.get_word(), + start_tick=lyric_word.get_start_tick(), + end_tick=lyric_word.get_end_tick(), + ) + self._proto.lines.append(line._proto) + return line + + def sort_lines(self): + self._proto.lines.sort(key=lambda line: line.words[0].start_tick)
You should probably use a common method defined in LyricLine to get the start tick of the line, so that it is consistent everywhere and catches edge cases.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,313 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + lyric_line = LyricLine(lyrics=self, start_tick=start_tick) + if resolve_order: + self.sort_lines() + return lyric_line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + line = self.create_line(start_tick=start_tick, resolve_order=False) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + def get_index_of_line_at_tick(self, tick: int): + if len(self._proto.lines) == 0: + return -1 + start_search_index = lower_equal( + self._proto.lines, tick, key=lambda line: line.start_tick + ) + for index in range(start_search_index, -1, -1): + line = self._proto.lines[index] + if tick >= line.start_tick and tick <= line.end_tick: + return index + return -1 + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + start_tick=line_proto.words[0].start_tick, + proto=line_proto + ) + + def get_line_at_index(self, index: int): + proto = self._proto.lines[index] + if len(proto.words) == 0: + raise Exception("Lyric line has no words") + return LyricLine( + lyrics=self, + start_tick=proto.words[0].start_tick, + proto=self._proto.lines[index] + ) + + def remove_line_at_index(self, index: int): + if index < 0 or index >= len(self._proto.lines): + return + self._proto.lines.pop(index) + + def clone_line(self, original_line: "LyricLine"): + line = LyricLine(lyrics=self, start_tick=original_line.get_start_tick()) + for lyric_word in original_line.get_words(): + line.create_word( + word=lyric_word.get_word(), + start_tick=lyric_word.get_start_tick(), + end_tick=lyric_word.get_end_tick(), + ) + self._proto.lines.append(line._proto) + return line + + def sort_lines(self): + self._proto.lines.sort(key=lambda line: line.words[0].start_tick) + + def clear(self): + del self._proto.lines[:] + + +class LyricLine: + def __init__(self, lyrics: Lyrics, start_tick: int, proto: song_pb2.LyricLine | None = None) -> None: + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = self.lyrics._proto.lines.add() + + if len(self._proto.words) == 0: + placeholder_word = LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + self._proto.words.append(placeholder_word._proto) + + + def is_empty(self) -> bool: + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List["LyricWord"]: + for word_proto in self._proto.words: + yield LyricWord( + line=self, + word=word_proto.word, + start_tick=word_proto.start_tick, + end_tick=word_proto.end_tick, + proto=word_proto + ) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + def get_start_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return self._proto.words[0].start_tick + + def get_end_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(self._proto.words, key=lambda item: item.end_tick).end_tick + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = (end_tick - start_tick) / (original_end - original_start) + for word in self.get_words(): + word_start_tick = int( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = int( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def create_words_from_string( + self, + input: str, + start_tick: int, + end_tick: int, + tokenizer: Optional[LyricTokenizer] = None, + ) -> None: + words = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(words) == 0: + return + tick_per_word = (end_tick - start_tick) / len(words) + del self._proto.words[:] + for i, word in enumerate(words): + start = int(start_tick + i * tick_per_word) + end = int(start_tick + (i + 1) * tick_per_word) + self._proto.words.add(word=word, start_tick=start, end_tick=end) + self.sort_words() + + def create_word(self, word: str, start_tick: int, end_tick: int, resolve_order: bool = True): + if self.is_empty(): + del self._proto.words[:] + self._proto.words.add(word=word, start_tick=start_tick, end_tick=end_tick) + if resolve_order: + self.sort_words() + + def clear(self): + new_word = self.create_placeholder_word() + del self._proto.words[:] + self._proto.words.append(new_word._proto) + + def create_placeholder_word(self): + return LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=self.get_start_tick(), + end_tick=self.get_start_tick() + DEFAULT_PPQ * 4 * 2, + ) + + def remove_word(self, word: "LyricWord"): + search_index = lower_equal(self._proto.words, word, key=lambda w: w.start_tick) + while search_index >= 0 and self._proto.words[search_index]: + lyric_word = self._proto.words[search_index] + if lyric_word == word: + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + self._proto.words.pop(search_index) + search_index -= 1 + + def remove_word_at_index(self, index: int): + if index < 0 or index >= len(self._proto.words): + raise IndexError("Index out of range") + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + self._proto.words.pop(index) + + def sort_words(self): + start_tick = self.get_start_tick() + self._proto.words.sort(key=lambda word: word.start_tick) + if self.get_start_tick() != start_tick: + self.lyrics.sort_lines() + + @staticmethod + def default_lyric_tokenizer(input: str) -> List[str]: + tokens = [] + + current_token = '' + for char in input: + if char == ' ': + if current_token: + tokens.append(current_token) + current_token = '' + tokens.append(char) + elif re.match(r'[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]', char): + if current_token: + tokens.append(current_token) + current_token = '' + tokens.append(char) + elif unicodedata.category(char).startswith('P'): + if current_token: + if re.match(r"^[']+$", char) and re.match(r'^[A-Za-z0-9]+$', current_token): + current_token += char + else: + tokens.append(current_token) + tokens.append(char) + current_token = '' + else: + tokens.append(char) + else: + current_token += char + + if current_token: + tokens.append(current_token) + + return tokens + + +class LyricWord: + PLACEHOLDER_WORD = "^%%^" + + def __init__(self, line: LyricLine, word: str, start_tick: int, end_tick: int, proto: song_pb2.LyricLine.LyricWord | None = None): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + if (self._proto.start_tick >= self._proto.end_tick and resolve_order): + self.delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def move_to(self, start_tick: int, end_tick: int): + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def delete_from_parent(self): + self.line.remove_word(self) + + def __eq__(self, other: song_pb2.LyricLine.LyricWord | "LyricWord"):
Why would we compare this to a proto?
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -85,6 +86,113 @@ def remove_track(self, track_id: str): dep_track.remove_output() return track + def get_bar_beats(self, end_tick: int) -> List[BarBeat]:
Please add tests for all bar beat related methods, too.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,313 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + lyric_line = LyricLine(lyrics=self, start_tick=start_tick) + if resolve_order: + self.sort_lines() + return lyric_line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + line = self.create_line(start_tick=start_tick, resolve_order=False) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + def get_index_of_line_at_tick(self, tick: int): + if len(self._proto.lines) == 0: + return -1 + start_search_index = lower_equal( + self._proto.lines, tick, key=lambda line: line.start_tick + ) + for index in range(start_search_index, -1, -1): + line = self._proto.lines[index] + if tick >= line.start_tick and tick <= line.end_tick: + return index + return -1 + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + start_tick=line_proto.words[0].start_tick, + proto=line_proto + ) + + def get_line_at_index(self, index: int): + proto = self._proto.lines[index] + if len(proto.words) == 0: + raise Exception("Lyric line has no words") + return LyricLine( + lyrics=self, + start_tick=proto.words[0].start_tick, + proto=self._proto.lines[index] + ) + + def remove_line_at_index(self, index: int): + if index < 0 or index >= len(self._proto.lines): + return + self._proto.lines.pop(index) + + def clone_line(self, original_line: "LyricLine"): + line = LyricLine(lyrics=self, start_tick=original_line.get_start_tick()) + for lyric_word in original_line.get_words(): + line.create_word( + word=lyric_word.get_word(), + start_tick=lyric_word.get_start_tick(), + end_tick=lyric_word.get_end_tick(), + ) + self._proto.lines.append(line._proto) + return line + + def sort_lines(self): + self._proto.lines.sort(key=lambda line: line.words[0].start_tick) + + def clear(self): + del self._proto.lines[:] + + +class LyricLine: + def __init__(self, lyrics: Lyrics, start_tick: int, proto: song_pb2.LyricLine | None = None) -> None: + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = self.lyrics._proto.lines.add() + + if len(self._proto.words) == 0: + placeholder_word = LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + self._proto.words.append(placeholder_word._proto) + + + def is_empty(self) -> bool: + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List["LyricWord"]: + for word_proto in self._proto.words: + yield LyricWord( + line=self, + word=word_proto.word, + start_tick=word_proto.start_tick, + end_tick=word_proto.end_tick, + proto=word_proto + ) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + def get_start_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return self._proto.words[0].start_tick + + def get_end_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(self._proto.words, key=lambda item: item.end_tick).end_tick + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = (end_tick - start_tick) / (original_end - original_start) + for word in self.get_words(): + word_start_tick = int(
round?
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,313 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + lyric_line = LyricLine(lyrics=self, start_tick=start_tick) + if resolve_order: + self.sort_lines() + return lyric_line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + line = self.create_line(start_tick=start_tick, resolve_order=False) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + def get_index_of_line_at_tick(self, tick: int): + if len(self._proto.lines) == 0: + return -1 + start_search_index = lower_equal( + self._proto.lines, tick, key=lambda line: line.start_tick + ) + for index in range(start_search_index, -1, -1): + line = self._proto.lines[index] + if tick >= line.start_tick and tick <= line.end_tick: + return index + return -1 + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + start_tick=line_proto.words[0].start_tick, + proto=line_proto + ) + + def get_line_at_index(self, index: int): + proto = self._proto.lines[index] + if len(proto.words) == 0: + raise Exception("Lyric line has no words") + return LyricLine( + lyrics=self, + start_tick=proto.words[0].start_tick, + proto=self._proto.lines[index] + ) + + def remove_line_at_index(self, index: int): + if index < 0 or index >= len(self._proto.lines): + return + self._proto.lines.pop(index) + + def clone_line(self, original_line: "LyricLine"): + line = LyricLine(lyrics=self, start_tick=original_line.get_start_tick()) + for lyric_word in original_line.get_words(): + line.create_word( + word=lyric_word.get_word(), + start_tick=lyric_word.get_start_tick(), + end_tick=lyric_word.get_end_tick(), + ) + self._proto.lines.append(line._proto) + return line + + def sort_lines(self): + self._proto.lines.sort(key=lambda line: line.words[0].start_tick) + + def clear(self): + del self._proto.lines[:] + + +class LyricLine: + def __init__(self, lyrics: Lyrics, start_tick: int, proto: song_pb2.LyricLine | None = None) -> None: + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = self.lyrics._proto.lines.add() + + if len(self._proto.words) == 0: + placeholder_word = LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + self._proto.words.append(placeholder_word._proto) + + + def is_empty(self) -> bool: + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List["LyricWord"]: + for word_proto in self._proto.words: + yield LyricWord( + line=self, + word=word_proto.word, + start_tick=word_proto.start_tick, + end_tick=word_proto.end_tick, + proto=word_proto + ) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + def get_start_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return self._proto.words[0].start_tick + + def get_end_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(self._proto.words, key=lambda item: item.end_tick).end_tick + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = (end_tick - start_tick) / (original_end - original_start) + for word in self.get_words(): + word_start_tick = int( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = int(
round?
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,313 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + lyric_line = LyricLine(lyrics=self, start_tick=start_tick) + if resolve_order: + self.sort_lines() + return lyric_line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + line = self.create_line(start_tick=start_tick, resolve_order=False) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + def get_index_of_line_at_tick(self, tick: int): + if len(self._proto.lines) == 0: + return -1 + start_search_index = lower_equal( + self._proto.lines, tick, key=lambda line: line.start_tick + ) + for index in range(start_search_index, -1, -1): + line = self._proto.lines[index] + if tick >= line.start_tick and tick <= line.end_tick: + return index + return -1 + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + start_tick=line_proto.words[0].start_tick, + proto=line_proto + ) + + def get_line_at_index(self, index: int): + proto = self._proto.lines[index] + if len(proto.words) == 0: + raise Exception("Lyric line has no words") + return LyricLine( + lyrics=self, + start_tick=proto.words[0].start_tick, + proto=self._proto.lines[index] + ) + + def remove_line_at_index(self, index: int): + if index < 0 or index >= len(self._proto.lines): + return + self._proto.lines.pop(index) + + def clone_line(self, original_line: "LyricLine"): + line = LyricLine(lyrics=self, start_tick=original_line.get_start_tick()) + for lyric_word in original_line.get_words(): + line.create_word( + word=lyric_word.get_word(), + start_tick=lyric_word.get_start_tick(), + end_tick=lyric_word.get_end_tick(), + ) + self._proto.lines.append(line._proto) + return line + + def sort_lines(self): + self._proto.lines.sort(key=lambda line: line.words[0].start_tick) + + def clear(self): + del self._proto.lines[:] + + +class LyricLine: + def __init__(self, lyrics: Lyrics, start_tick: int, proto: song_pb2.LyricLine | None = None) -> None: + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = self.lyrics._proto.lines.add() + + if len(self._proto.words) == 0: + placeholder_word = LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + self._proto.words.append(placeholder_word._proto) + + + def is_empty(self) -> bool: + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List["LyricWord"]: + for word_proto in self._proto.words: + yield LyricWord( + line=self, + word=word_proto.word, + start_tick=word_proto.start_tick, + end_tick=word_proto.end_tick, + proto=word_proto + ) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + def get_start_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return self._proto.words[0].start_tick + + def get_end_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(self._proto.words, key=lambda item: item.end_tick).end_tick + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = (end_tick - start_tick) / (original_end - original_start) + for word in self.get_words(): + word_start_tick = int( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = int( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def create_words_from_string( + self, + input: str, + start_tick: int, + end_tick: int, + tokenizer: Optional[LyricTokenizer] = None, + ) -> None: + words = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(words) == 0: + return + tick_per_word = (end_tick - start_tick) / len(words) + del self._proto.words[:] + for i, word in enumerate(words): + start = int(start_tick + i * tick_per_word)
round?
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,313 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + lyric_line = LyricLine(lyrics=self, start_tick=start_tick) + if resolve_order: + self.sort_lines() + return lyric_line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + line = self.create_line(start_tick=start_tick, resolve_order=False) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + def get_index_of_line_at_tick(self, tick: int): + if len(self._proto.lines) == 0: + return -1 + start_search_index = lower_equal( + self._proto.lines, tick, key=lambda line: line.start_tick + ) + for index in range(start_search_index, -1, -1): + line = self._proto.lines[index] + if tick >= line.start_tick and tick <= line.end_tick: + return index + return -1 + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + start_tick=line_proto.words[0].start_tick, + proto=line_proto + ) + + def get_line_at_index(self, index: int): + proto = self._proto.lines[index] + if len(proto.words) == 0: + raise Exception("Lyric line has no words") + return LyricLine( + lyrics=self, + start_tick=proto.words[0].start_tick, + proto=self._proto.lines[index] + ) + + def remove_line_at_index(self, index: int): + if index < 0 or index >= len(self._proto.lines): + return + self._proto.lines.pop(index) + + def clone_line(self, original_line: "LyricLine"): + line = LyricLine(lyrics=self, start_tick=original_line.get_start_tick()) + for lyric_word in original_line.get_words(): + line.create_word( + word=lyric_word.get_word(), + start_tick=lyric_word.get_start_tick(), + end_tick=lyric_word.get_end_tick(), + ) + self._proto.lines.append(line._proto) + return line + + def sort_lines(self): + self._proto.lines.sort(key=lambda line: line.words[0].start_tick) + + def clear(self): + del self._proto.lines[:] + + +class LyricLine: + def __init__(self, lyrics: Lyrics, start_tick: int, proto: song_pb2.LyricLine | None = None) -> None: + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = self.lyrics._proto.lines.add() + + if len(self._proto.words) == 0: + placeholder_word = LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + self._proto.words.append(placeholder_word._proto) + + + def is_empty(self) -> bool: + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List["LyricWord"]: + for word_proto in self._proto.words: + yield LyricWord( + line=self, + word=word_proto.word, + start_tick=word_proto.start_tick, + end_tick=word_proto.end_tick, + proto=word_proto + ) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + def get_start_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return self._proto.words[0].start_tick + + def get_end_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(self._proto.words, key=lambda item: item.end_tick).end_tick + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = (end_tick - start_tick) / (original_end - original_start) + for word in self.get_words(): + word_start_tick = int( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = int( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def create_words_from_string( + self, + input: str, + start_tick: int, + end_tick: int, + tokenizer: Optional[LyricTokenizer] = None, + ) -> None: + words = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(words) == 0: + return + tick_per_word = (end_tick - start_tick) / len(words) + del self._proto.words[:] + for i, word in enumerate(words): + start = int(start_tick + i * tick_per_word) + end = int(start_tick + (i + 1) * tick_per_word)
round?
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,313 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + lyric_line = LyricLine(lyrics=self, start_tick=start_tick) + if resolve_order: + self.sort_lines() + return lyric_line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + line = self.create_line(start_tick=start_tick, resolve_order=False) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + def get_index_of_line_at_tick(self, tick: int): + if len(self._proto.lines) == 0: + return -1 + start_search_index = lower_equal( + self._proto.lines, tick, key=lambda line: line.start_tick + ) + for index in range(start_search_index, -1, -1): + line = self._proto.lines[index] + if tick >= line.start_tick and tick <= line.end_tick: + return index + return -1 + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + start_tick=line_proto.words[0].start_tick, + proto=line_proto + ) + + def get_line_at_index(self, index: int): + proto = self._proto.lines[index] + if len(proto.words) == 0: + raise Exception("Lyric line has no words") + return LyricLine( + lyrics=self, + start_tick=proto.words[0].start_tick, + proto=self._proto.lines[index] + ) + + def remove_line_at_index(self, index: int): + if index < 0 or index >= len(self._proto.lines): + return + self._proto.lines.pop(index) + + def clone_line(self, original_line: "LyricLine"): + line = LyricLine(lyrics=self, start_tick=original_line.get_start_tick()) + for lyric_word in original_line.get_words(): + line.create_word( + word=lyric_word.get_word(), + start_tick=lyric_word.get_start_tick(), + end_tick=lyric_word.get_end_tick(), + ) + self._proto.lines.append(line._proto) + return line + + def sort_lines(self): + self._proto.lines.sort(key=lambda line: line.words[0].start_tick) + + def clear(self): + del self._proto.lines[:] + + +class LyricLine: + def __init__(self, lyrics: Lyrics, start_tick: int, proto: song_pb2.LyricLine | None = None) -> None: + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = self.lyrics._proto.lines.add() + + if len(self._proto.words) == 0: + placeholder_word = LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + self._proto.words.append(placeholder_word._proto) + + + def is_empty(self) -> bool: + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List["LyricWord"]: + for word_proto in self._proto.words: + yield LyricWord( + line=self, + word=word_proto.word, + start_tick=word_proto.start_tick, + end_tick=word_proto.end_tick, + proto=word_proto + ) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + def get_start_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return self._proto.words[0].start_tick + + def get_end_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(self._proto.words, key=lambda item: item.end_tick).end_tick + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = (end_tick - start_tick) / (original_end - original_start) + for word in self.get_words(): + word_start_tick = int( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = int( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def create_words_from_string( + self, + input: str, + start_tick: int, + end_tick: int, + tokenizer: Optional[LyricTokenizer] = None, + ) -> None: + words = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(words) == 0: + return + tick_per_word = (end_tick - start_tick) / len(words) + del self._proto.words[:] + for i, word in enumerate(words): + start = int(start_tick + i * tick_per_word) + end = int(start_tick + (i + 1) * tick_per_word) + self._proto.words.add(word=word, start_tick=start, end_tick=end) + self.sort_words() + + def create_word(self, word: str, start_tick: int, end_tick: int, resolve_order: bool = True): + if self.is_empty(): + del self._proto.words[:] + self._proto.words.add(word=word, start_tick=start_tick, end_tick=end_tick) + if resolve_order: + self.sort_words()
Return the new word?
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,313 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + lyric_line = LyricLine(lyrics=self, start_tick=start_tick) + if resolve_order: + self.sort_lines() + return lyric_line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + line = self.create_line(start_tick=start_tick, resolve_order=False) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + def get_index_of_line_at_tick(self, tick: int): + if len(self._proto.lines) == 0: + return -1 + start_search_index = lower_equal( + self._proto.lines, tick, key=lambda line: line.start_tick + ) + for index in range(start_search_index, -1, -1): + line = self._proto.lines[index] + if tick >= line.start_tick and tick <= line.end_tick: + return index + return -1 + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + start_tick=line_proto.words[0].start_tick, + proto=line_proto + ) + + def get_line_at_index(self, index: int): + proto = self._proto.lines[index] + if len(proto.words) == 0: + raise Exception("Lyric line has no words") + return LyricLine( + lyrics=self, + start_tick=proto.words[0].start_tick, + proto=self._proto.lines[index] + ) + + def remove_line_at_index(self, index: int): + if index < 0 or index >= len(self._proto.lines): + return + self._proto.lines.pop(index) + + def clone_line(self, original_line: "LyricLine"): + line = LyricLine(lyrics=self, start_tick=original_line.get_start_tick()) + for lyric_word in original_line.get_words(): + line.create_word( + word=lyric_word.get_word(), + start_tick=lyric_word.get_start_tick(), + end_tick=lyric_word.get_end_tick(), + ) + self._proto.lines.append(line._proto) + return line + + def sort_lines(self): + self._proto.lines.sort(key=lambda line: line.words[0].start_tick) + + def clear(self): + del self._proto.lines[:] + + +class LyricLine: + def __init__(self, lyrics: Lyrics, start_tick: int, proto: song_pb2.LyricLine | None = None) -> None: + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = self.lyrics._proto.lines.add() + + if len(self._proto.words) == 0: + placeholder_word = LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + self._proto.words.append(placeholder_word._proto) + + + def is_empty(self) -> bool: + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List["LyricWord"]: + for word_proto in self._proto.words: + yield LyricWord( + line=self, + word=word_proto.word, + start_tick=word_proto.start_tick, + end_tick=word_proto.end_tick, + proto=word_proto + ) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + def get_start_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return self._proto.words[0].start_tick + + def get_end_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(self._proto.words, key=lambda item: item.end_tick).end_tick + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = (end_tick - start_tick) / (original_end - original_start) + for word in self.get_words(): + word_start_tick = int( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = int( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def create_words_from_string( + self, + input: str, + start_tick: int, + end_tick: int, + tokenizer: Optional[LyricTokenizer] = None, + ) -> None: + words = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(words) == 0: + return + tick_per_word = (end_tick - start_tick) / len(words) + del self._proto.words[:] + for i, word in enumerate(words): + start = int(start_tick + i * tick_per_word) + end = int(start_tick + (i + 1) * tick_per_word) + self._proto.words.add(word=word, start_tick=start, end_tick=end) + self.sort_words() + + def create_word(self, word: str, start_tick: int, end_tick: int, resolve_order: bool = True): + if self.is_empty(): + del self._proto.words[:] + self._proto.words.add(word=word, start_tick=start_tick, end_tick=end_tick) + if resolve_order: + self.sort_words() + + def clear(self): + new_word = self.create_placeholder_word() + del self._proto.words[:] + self._proto.words.append(new_word._proto) + + def create_placeholder_word(self): + return LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=self.get_start_tick(), + end_tick=self.get_start_tick() + DEFAULT_PPQ * 4 * 2, + ) + + def remove_word(self, word: "LyricWord"): + search_index = lower_equal(self._proto.words, word, key=lambda w: w.start_tick)
You should pass in word._proto as the second param for lower_equal, be sure to double check this with a test.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,313 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + lyric_line = LyricLine(lyrics=self, start_tick=start_tick) + if resolve_order: + self.sort_lines() + return lyric_line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + line = self.create_line(start_tick=start_tick, resolve_order=False) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + def get_index_of_line_at_tick(self, tick: int): + if len(self._proto.lines) == 0: + return -1 + start_search_index = lower_equal( + self._proto.lines, tick, key=lambda line: line.start_tick + ) + for index in range(start_search_index, -1, -1): + line = self._proto.lines[index] + if tick >= line.start_tick and tick <= line.end_tick: + return index + return -1 + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + start_tick=line_proto.words[0].start_tick, + proto=line_proto + ) + + def get_line_at_index(self, index: int): + proto = self._proto.lines[index] + if len(proto.words) == 0: + raise Exception("Lyric line has no words") + return LyricLine( + lyrics=self, + start_tick=proto.words[0].start_tick, + proto=self._proto.lines[index] + ) + + def remove_line_at_index(self, index: int): + if index < 0 or index >= len(self._proto.lines): + return + self._proto.lines.pop(index) + + def clone_line(self, original_line: "LyricLine"): + line = LyricLine(lyrics=self, start_tick=original_line.get_start_tick()) + for lyric_word in original_line.get_words(): + line.create_word( + word=lyric_word.get_word(), + start_tick=lyric_word.get_start_tick(), + end_tick=lyric_word.get_end_tick(), + ) + self._proto.lines.append(line._proto) + return line + + def sort_lines(self): + self._proto.lines.sort(key=lambda line: line.words[0].start_tick) + + def clear(self): + del self._proto.lines[:] + + +class LyricLine: + def __init__(self, lyrics: Lyrics, start_tick: int, proto: song_pb2.LyricLine | None = None) -> None: + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = self.lyrics._proto.lines.add() + + if len(self._proto.words) == 0: + placeholder_word = LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + self._proto.words.append(placeholder_word._proto) + + + def is_empty(self) -> bool: + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List["LyricWord"]: + for word_proto in self._proto.words: + yield LyricWord( + line=self, + word=word_proto.word, + start_tick=word_proto.start_tick, + end_tick=word_proto.end_tick, + proto=word_proto + ) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + def get_start_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return self._proto.words[0].start_tick + + def get_end_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(self._proto.words, key=lambda item: item.end_tick).end_tick + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = (end_tick - start_tick) / (original_end - original_start) + for word in self.get_words(): + word_start_tick = int( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = int( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def create_words_from_string( + self, + input: str, + start_tick: int, + end_tick: int, + tokenizer: Optional[LyricTokenizer] = None, + ) -> None: + words = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(words) == 0: + return + tick_per_word = (end_tick - start_tick) / len(words) + del self._proto.words[:] + for i, word in enumerate(words): + start = int(start_tick + i * tick_per_word) + end = int(start_tick + (i + 1) * tick_per_word) + self._proto.words.add(word=word, start_tick=start, end_tick=end) + self.sort_words() + + def create_word(self, word: str, start_tick: int, end_tick: int, resolve_order: bool = True): + if self.is_empty(): + del self._proto.words[:] + self._proto.words.add(word=word, start_tick=start_tick, end_tick=end_tick) + if resolve_order: + self.sort_words() + + def clear(self): + new_word = self.create_placeholder_word() + del self._proto.words[:] + self._proto.words.append(new_word._proto) + + def create_placeholder_word(self): + return LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=self.get_start_tick(), + end_tick=self.get_start_tick() + DEFAULT_PPQ * 4 * 2, + ) + + def remove_word(self, word: "LyricWord"): + search_index = lower_equal(self._proto.words, word, key=lambda w: w.start_tick) + while search_index >= 0 and self._proto.words[search_index]: + lyric_word = self._proto.words[search_index] + if lyric_word == word: + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + self._proto.words.pop(search_index) + search_index -= 1 + + def remove_word_at_index(self, index: int): + if index < 0 or index >= len(self._proto.words): + raise IndexError("Index out of range") + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + self._proto.words.pop(index) + + def sort_words(self): + start_tick = self.get_start_tick() + self._proto.words.sort(key=lambda word: word.start_tick) + if self.get_start_tick() != start_tick: + self.lyrics.sort_lines() + + @staticmethod + def default_lyric_tokenizer(input: str) -> List[str]:
Add comment documentation so that people know the default tokenizer behaviour.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,313 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + lyric_line = LyricLine(lyrics=self, start_tick=start_tick) + if resolve_order: + self.sort_lines() + return lyric_line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + line = self.create_line(start_tick=start_tick, resolve_order=False) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + def get_index_of_line_at_tick(self, tick: int): + if len(self._proto.lines) == 0: + return -1 + start_search_index = lower_equal( + self._proto.lines, tick, key=lambda line: line.start_tick + ) + for index in range(start_search_index, -1, -1): + line = self._proto.lines[index] + if tick >= line.start_tick and tick <= line.end_tick: + return index + return -1 + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + start_tick=line_proto.words[0].start_tick, + proto=line_proto + ) + + def get_line_at_index(self, index: int): + proto = self._proto.lines[index] + if len(proto.words) == 0: + raise Exception("Lyric line has no words") + return LyricLine( + lyrics=self, + start_tick=proto.words[0].start_tick, + proto=self._proto.lines[index] + ) + + def remove_line_at_index(self, index: int): + if index < 0 or index >= len(self._proto.lines): + return + self._proto.lines.pop(index) + + def clone_line(self, original_line: "LyricLine"): + line = LyricLine(lyrics=self, start_tick=original_line.get_start_tick()) + for lyric_word in original_line.get_words(): + line.create_word( + word=lyric_word.get_word(), + start_tick=lyric_word.get_start_tick(), + end_tick=lyric_word.get_end_tick(), + ) + self._proto.lines.append(line._proto) + return line + + def sort_lines(self): + self._proto.lines.sort(key=lambda line: line.words[0].start_tick) + + def clear(self): + del self._proto.lines[:] + + +class LyricLine: + def __init__(self, lyrics: Lyrics, start_tick: int, proto: song_pb2.LyricLine | None = None) -> None: + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = self.lyrics._proto.lines.add() + + if len(self._proto.words) == 0: + placeholder_word = LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + self._proto.words.append(placeholder_word._proto) + + + def is_empty(self) -> bool: + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List["LyricWord"]: + for word_proto in self._proto.words: + yield LyricWord( + line=self, + word=word_proto.word, + start_tick=word_proto.start_tick, + end_tick=word_proto.end_tick, + proto=word_proto + ) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + def get_start_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return self._proto.words[0].start_tick + + def get_end_tick(self) -> int: + if len(self._proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(self._proto.words, key=lambda item: item.end_tick).end_tick + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = (end_tick - start_tick) / (original_end - original_start) + for word in self.get_words(): + word_start_tick = int( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = int( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def create_words_from_string( + self, + input: str, + start_tick: int, + end_tick: int, + tokenizer: Optional[LyricTokenizer] = None, + ) -> None: + words = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(words) == 0: + return + tick_per_word = (end_tick - start_tick) / len(words) + del self._proto.words[:] + for i, word in enumerate(words): + start = int(start_tick + i * tick_per_word) + end = int(start_tick + (i + 1) * tick_per_word) + self._proto.words.add(word=word, start_tick=start, end_tick=end) + self.sort_words() + + def create_word(self, word: str, start_tick: int, end_tick: int, resolve_order: bool = True): + if self.is_empty(): + del self._proto.words[:] + self._proto.words.add(word=word, start_tick=start_tick, end_tick=end_tick) + if resolve_order: + self.sort_words() + + def clear(self): + new_word = self.create_placeholder_word() + del self._proto.words[:] + self._proto.words.append(new_word._proto) + + def create_placeholder_word(self): + return LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=self.get_start_tick(), + end_tick=self.get_start_tick() + DEFAULT_PPQ * 4 * 2, + ) + + def remove_word(self, word: "LyricWord"): + search_index = lower_equal(self._proto.words, word, key=lambda w: w.start_tick) + while search_index >= 0 and self._proto.words[search_index]: + lyric_word = self._proto.words[search_index] + if lyric_word == word: + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + self._proto.words.pop(search_index) + search_index -= 1 + + def remove_word_at_index(self, index: int): + if index < 0 or index >= len(self._proto.words): + raise IndexError("Index out of range") + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + self._proto.words.pop(index) + + def sort_words(self): + start_tick = self.get_start_tick() + self._proto.words.sort(key=lambda word: word.start_tick) + if self.get_start_tick() != start_tick: + self.lyrics.sort_lines() + + @staticmethod + def default_lyric_tokenizer(input: str) -> List[str]: + tokens = [] + + current_token = '' + for char in input: + if char == ' ': + if current_token: + tokens.append(current_token) + current_token = '' + tokens.append(char) + elif re.match(r'[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]', char): + if current_token: + tokens.append(current_token) + current_token = '' + tokens.append(char) + elif unicodedata.category(char).startswith('P'): + if current_token: + if re.match(r"^[']+$", char) and re.match(r'^[A-Za-z0-9]+$', current_token): + current_token += char + else: + tokens.append(current_token) + tokens.append(char) + current_token = '' + else: + tokens.append(char) + else: + current_token += char + + if current_token: + tokens.append(current_token) + + return tokens + + +class LyricWord: + PLACEHOLDER_WORD = "^%%^" + + def __init__(self, line: LyricLine, word: str, start_tick: int, end_tick: int, proto: song_pb2.LyricLine.LyricWord | None = None): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + if (self._proto.start_tick >= self._proto.end_tick and resolve_order): + self.delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def move_to(self, start_tick: int, end_tick: int): + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick
Sort words.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,133 @@ +import unittest +from typing import Dict +from tuneflow_py.models.song import Song +from tuneflow_py.models.lyric import Lyrics, LyricLine, LyricWord + + +class MockLyricLine:
Mocks are usually used as a substitute for a component that will be running in the test but not the primary test target. For example if class A has an private member instance of class B, when you test class A, you don't want to test anything related to class B, so you can mock the instance of class B instead. In this case you are essentially doing assertion, which can probably be done through a simple function.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,421 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class LyricWord: + ''' + LyricWord is the primary unit of a LyricLine + The class is a wrapper of the LyricWord proto object + A word is located with start_tick and end_tick + ''' + # The default word placeholer for an empty lyric line + PLACEHOLDER_WORD = "^%%^" + + def __init__( + self, + line: LyricLine, + word: str | None = None, + start_tick: int | None = None, + end_tick: int | None = None, + proto: song_pb2.LyricLine.LyricWord | None = None + ): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word:
Does this check for empty string ''?
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,421 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class LyricWord: + ''' + LyricWord is the primary unit of a LyricLine + The class is a wrapper of the LyricWord proto object + A word is located with start_tick and end_tick + ''' + # The default word placeholer for an empty lyric line + PLACEHOLDER_WORD = "^%%^" + + def __init__( + self, + line: LyricLine, + word: str | None = None, + start_tick: int | None = None, + end_tick: int | None = None, + proto: song_pb2.LyricLine.LyricWord | None = None + ): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + ''' + Set a new start tick for the word. + This might delete the word if the new start tick is greater than or equal to the end tick. + + Args: + start_tick (int): The new start tick of the word. + ''' + if self._proto.start_tick >= self._proto.end_tick and resolve_order: + self.delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def set_end_tick(self, end_tick: int, resolve_order=True): + ''' + Set a new end tick for the word. + This might delete the word if the new end tick is less than or equal to the start tick. + + Args: + end_tick (int): The new end tick of the word. + ''' + if end_tick <= self._proto.start_tick and resolve_order: + self.delete_from_parent() + return + self._proto.end_tick = end_tick + + def move_to(self, start_tick: int, end_tick: int): + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + self.line.sort_words()
Also check if you need to delete the word.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,421 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class LyricWord: + ''' + LyricWord is the primary unit of a LyricLine + The class is a wrapper of the LyricWord proto object + A word is located with start_tick and end_tick + ''' + # The default word placeholer for an empty lyric line + PLACEHOLDER_WORD = "^%%^" + + def __init__( + self, + line: LyricLine, + word: str | None = None, + start_tick: int | None = None, + end_tick: int | None = None, + proto: song_pb2.LyricLine.LyricWord | None = None + ): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + ''' + Set a new start tick for the word. + This might delete the word if the new start tick is greater than or equal to the end tick. + + Args: + start_tick (int): The new start tick of the word. + ''' + if self._proto.start_tick >= self._proto.end_tick and resolve_order: + self.delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def set_end_tick(self, end_tick: int, resolve_order=True): + ''' + Set a new end tick for the word. + This might delete the word if the new end tick is less than or equal to the start tick. + + Args: + end_tick (int): The new end tick of the word. + ''' + if end_tick <= self._proto.start_tick and resolve_order: + self.delete_from_parent() + return + self._proto.end_tick = end_tick + + def move_to(self, start_tick: int, end_tick: int): + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + self.line.sort_words() + + def delete_from_parent(self): + ''' + Delete the word from the parent line. + ''' + self.line.remove_word(self) + + def __eq__(self, other: LyricWord): + if isinstance(other, song_pb2.LyricLine.LyricWord): + return ( + self._proto.start_tick == other.start_tick + and self._proto.end_tick == other.end_tick + and self._proto.word == other.word + ) + elif isinstance(other, LyricWord): + return ( + self._proto.start_tick == other._proto.start_tick + and self._proto.end_tick == other._proto.end_tick + and self._proto.word == other._proto.word + ) + return False + + +class LyricLine: + ''' + Lyrics is composed of a list of LyricLine objects + The class is a wrapper of the LyricLine proto object
The second line is not necessary information for users since they should never be interacting with protos directly
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,421 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class LyricWord: + ''' + LyricWord is the primary unit of a LyricLine + The class is a wrapper of the LyricWord proto object + A word is located with start_tick and end_tick + ''' + # The default word placeholer for an empty lyric line + PLACEHOLDER_WORD = "^%%^" + + def __init__( + self, + line: LyricLine, + word: str | None = None, + start_tick: int | None = None, + end_tick: int | None = None, + proto: song_pb2.LyricLine.LyricWord | None = None + ): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + ''' + Set a new start tick for the word. + This might delete the word if the new start tick is greater than or equal to the end tick. + + Args: + start_tick (int): The new start tick of the word. + ''' + if self._proto.start_tick >= self._proto.end_tick and resolve_order: + self.delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def set_end_tick(self, end_tick: int, resolve_order=True): + ''' + Set a new end tick for the word. + This might delete the word if the new end tick is less than or equal to the start tick. + + Args: + end_tick (int): The new end tick of the word. + ''' + if end_tick <= self._proto.start_tick and resolve_order: + self.delete_from_parent() + return + self._proto.end_tick = end_tick + + def move_to(self, start_tick: int, end_tick: int): + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + self.line.sort_words() + + def delete_from_parent(self): + ''' + Delete the word from the parent line. + ''' + self.line.remove_word(self) + + def __eq__(self, other: LyricWord): + if isinstance(other, song_pb2.LyricLine.LyricWord): + return ( + self._proto.start_tick == other.start_tick + and self._proto.end_tick == other.end_tick + and self._proto.word == other.word + ) + elif isinstance(other, LyricWord): + return ( + self._proto.start_tick == other._proto.start_tick + and self._proto.end_tick == other._proto.end_tick + and self._proto.word == other._proto.word + ) + return False + + +class LyricLine: + ''' + Lyrics is composed of a list of LyricLine objects + The class is a wrapper of the LyricLine proto object + ''' + + def __init__( + self, + lyrics: Lyrics, + start_tick: int | None = None, + proto: song_pb2.LyricLine | None = None + ): + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine() + + if len(self._proto.words) == 0: + # Create a default placeholder for the empty line + self._proto.words.add( + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + + def is_empty(self) -> bool: + # A line is empty if it only contains a placeholder word + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List[LyricWord]:
The return type is a generator
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,421 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class LyricWord: + ''' + LyricWord is the primary unit of a LyricLine + The class is a wrapper of the LyricWord proto object + A word is located with start_tick and end_tick + ''' + # The default word placeholer for an empty lyric line + PLACEHOLDER_WORD = "^%%^" + + def __init__( + self, + line: LyricLine, + word: str | None = None, + start_tick: int | None = None, + end_tick: int | None = None, + proto: song_pb2.LyricLine.LyricWord | None = None + ): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + ''' + Set a new start tick for the word. + This might delete the word if the new start tick is greater than or equal to the end tick. + + Args: + start_tick (int): The new start tick of the word. + ''' + if self._proto.start_tick >= self._proto.end_tick and resolve_order: + self.delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def set_end_tick(self, end_tick: int, resolve_order=True): + ''' + Set a new end tick for the word. + This might delete the word if the new end tick is less than or equal to the start tick. + + Args: + end_tick (int): The new end tick of the word. + ''' + if end_tick <= self._proto.start_tick and resolve_order: + self.delete_from_parent() + return + self._proto.end_tick = end_tick + + def move_to(self, start_tick: int, end_tick: int): + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + self.line.sort_words() + + def delete_from_parent(self): + ''' + Delete the word from the parent line. + ''' + self.line.remove_word(self) + + def __eq__(self, other: LyricWord): + if isinstance(other, song_pb2.LyricLine.LyricWord): + return ( + self._proto.start_tick == other.start_tick + and self._proto.end_tick == other.end_tick + and self._proto.word == other.word + ) + elif isinstance(other, LyricWord): + return ( + self._proto.start_tick == other._proto.start_tick + and self._proto.end_tick == other._proto.end_tick + and self._proto.word == other._proto.word + ) + return False + + +class LyricLine: + ''' + Lyrics is composed of a list of LyricLine objects + The class is a wrapper of the LyricLine proto object + ''' + + def __init__( + self, + lyrics: Lyrics, + start_tick: int | None = None, + proto: song_pb2.LyricLine | None = None + ): + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine() + + if len(self._proto.words) == 0: + # Create a default placeholder for the empty line + self._proto.words.add( + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + + def is_empty(self) -> bool: + # A line is empty if it only contains a placeholder word + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List[LyricWord]: + for word_proto in self._proto.words: + yield LyricWord(line=self, proto=word_proto) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + @staticmethod + def _get_start_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return line_proto.words[0].start_tick + + @staticmethod + def _get_end_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(line_proto.words, key=lambda word_proto: word_proto.end_tick).end_tick + + def get_start_tick(self) -> int: + return LyricLine._get_start_tick(self._proto) + + def get_end_tick(self) -> int: + return LyricLine._get_end_tick(self._proto) + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = round((end_tick - start_tick) / (original_end - original_start)) + for word in self.get_words(): + word_start_tick = round( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = round( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def create_words_from_string( + self, + input: str, + start_tick: int, + end_tick: int, + tokenizer: Optional[LyricTokenizer] = None, + ) -> None: + words = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(words) == 0:
Do we have another method to update the line from a string? If it is only used to add words to the line it should be fine and we can mark it as a private method, but we also need another user-facing method that takes a string input and updates words in the line, in that case, we should clear the line if the input is empty.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,421 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class LyricWord: + ''' + LyricWord is the primary unit of a LyricLine + The class is a wrapper of the LyricWord proto object + A word is located with start_tick and end_tick + ''' + # The default word placeholer for an empty lyric line + PLACEHOLDER_WORD = "^%%^" + + def __init__( + self, + line: LyricLine, + word: str | None = None, + start_tick: int | None = None, + end_tick: int | None = None, + proto: song_pb2.LyricLine.LyricWord | None = None + ): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + ''' + Set a new start tick for the word. + This might delete the word if the new start tick is greater than or equal to the end tick. + + Args: + start_tick (int): The new start tick of the word. + ''' + if self._proto.start_tick >= self._proto.end_tick and resolve_order: + self.delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def set_end_tick(self, end_tick: int, resolve_order=True): + ''' + Set a new end tick for the word. + This might delete the word if the new end tick is less than or equal to the start tick. + + Args: + end_tick (int): The new end tick of the word. + ''' + if end_tick <= self._proto.start_tick and resolve_order: + self.delete_from_parent() + return + self._proto.end_tick = end_tick + + def move_to(self, start_tick: int, end_tick: int): + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + self.line.sort_words() + + def delete_from_parent(self): + ''' + Delete the word from the parent line. + ''' + self.line.remove_word(self) + + def __eq__(self, other: LyricWord): + if isinstance(other, song_pb2.LyricLine.LyricWord): + return ( + self._proto.start_tick == other.start_tick + and self._proto.end_tick == other.end_tick + and self._proto.word == other.word + ) + elif isinstance(other, LyricWord): + return ( + self._proto.start_tick == other._proto.start_tick + and self._proto.end_tick == other._proto.end_tick + and self._proto.word == other._proto.word + ) + return False + + +class LyricLine: + ''' + Lyrics is composed of a list of LyricLine objects + The class is a wrapper of the LyricLine proto object + ''' + + def __init__( + self, + lyrics: Lyrics, + start_tick: int | None = None, + proto: song_pb2.LyricLine | None = None + ): + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine() + + if len(self._proto.words) == 0: + # Create a default placeholder for the empty line + self._proto.words.add( + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + + def is_empty(self) -> bool: + # A line is empty if it only contains a placeholder word + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List[LyricWord]: + for word_proto in self._proto.words: + yield LyricWord(line=self, proto=word_proto) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + @staticmethod + def _get_start_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return line_proto.words[0].start_tick + + @staticmethod + def _get_end_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(line_proto.words, key=lambda word_proto: word_proto.end_tick).end_tick + + def get_start_tick(self) -> int: + return LyricLine._get_start_tick(self._proto) + + def get_end_tick(self) -> int: + return LyricLine._get_end_tick(self._proto) + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = round((end_tick - start_tick) / (original_end - original_start)) + for word in self.get_words(): + word_start_tick = round( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = round( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def create_words_from_string( + self, + input: str, + start_tick: int, + end_tick: int, + tokenizer: Optional[LyricTokenizer] = None, + ) -> None: + words = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(words) == 0: + return + tick_per_word = (end_tick - start_tick) // len(words) + del self._proto.words[:] + for i, word in enumerate(words): + start = start_tick + i * tick_per_word + # Adjust the last word to match the end tick + end = start_tick + (i + 1) * tick_per_word if i < len(words) - 1 else end_tick + self._proto.words.add(word=word, start_tick=start, end_tick=end) + self.sort_words() + + def create_word(self, word: str, start_tick: int, end_tick: int, resolve_order: bool = True): + if self.is_empty(): + del self._proto.words[:] + proto = self._proto.words.add(word=word, start_tick=start_tick, end_tick=end_tick) + if resolve_order: + self.sort_words() + return LyricWord( + line=self, + word=word, + start_tick=start_tick, + end_tick=end_tick, + proto=proto, + ) + + def clear(self): + new_word = self.create_placeholder_word() + del self._proto.words[:] + self._proto.words.append(new_word._proto) + + def create_placeholder_word(self): + return LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=self.get_start_tick(), + end_tick=self.get_start_tick() + DEFAULT_PPQ * 4 * 2, + ) + + def remove_word(self, word: LyricWord): + search_index = lower_equal(self._proto.words, word._proto, key=lambda word: word.start_tick) + while search_index >= 0 and self._proto.words[search_index]: + lyric_word = self._proto.words[search_index] + if lyric_word == word._proto: + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + del self._proto.words[search_index] + search_index -= 1 + + def remove_word_at_index(self, index: int): + if index < 0 or index >= len(self._proto.words): + raise IndexError("Index out of range") + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + del self._proto.words[index] + + def sort_words(self): + self._proto.words.sort(key=lambda word: word.start_tick) + self.lyrics.sort_lines() + + @staticmethod + def default_lyric_tokenizer(input: str) -> List[str]: + """ + Tokenizes the input string based on specific rules. + + Args: + input (str): The input string to be tokenized. + + Returns: + List[str]: A list of tokens generated based on the rules. + """ + tokens = [] + + current_token = '' + for char in input: + if char == ' ': + # Handle spaces + if current_token: + tokens.append(current_token) + current_token = '' + tokens.append(char) + elif re.match(r'[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]', char): + # Handle Japanese, Chinese, Korean characters + if current_token: + tokens.append(current_token) + current_token = '' + tokens.append(char) + elif unicodedata.category(char).startswith('P'): + # Handle punctuation marks + if current_token: + if re.match(r"^[']+$", char) and re.match(r'^[A-Za-z0-9]+$', current_token): + current_token += char + else: + tokens.append(current_token) + tokens.append(char) + current_token = '' + else: + tokens.append(char) + else: + current_token += char + + if current_token: + tokens.append(current_token) + + return tokens + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + ''' + Creates a new empty LyricLine object at the given start_tick. + + Args: + start_tick (int): The starting tick for the new lyric line. + resolve_order (bool, optional): Whether to sort the lyric lines by start_tick. Defaults to True. + + Returns: + LyricLine: The newly created LyricLine object. + ''' + line_proto = self._proto.lines.add() + line = LyricLine(lyrics=self, start_tick=start_tick, proto=line_proto) + if resolve_order: + self.sort_lines() + return line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + """ + Create a Line object from a string of words. + + Args: + input (str): The input string of words. + start_tick (int): The starting tick of the line. + end_tick (int): The ending tick of the line. + tokenizer (Optional[LyricTokenizer], optional): The tokenizer to use for splitting the input string into words. + If None, the default tokenizer will be used. Defaults to None. + + Returns: + Line: The created Line object. + + Raises: + ValueError: If the input string is empty. + """ + line_proto = self._proto.lines.add() + line = LyricLine(lyrics=self, start_tick=start_tick, proto=line_proto) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + @staticmethod + def _get_index_of_line_at_tick(proto: song_pb2.Lyrics, tick: int): + ''' + Internal generator implementation that locates lyrlic line at a given tick. + ''' + if len(proto.lines) == 0: + return -1 + start_search_index = lower_equal( + [LyricLine._get_start_tick(line) for line in proto.lines], + tick, + ) + for index in range(start_search_index, -1, -1): + line = proto.lines[index] + if tick >= LyricLine._get_start_tick(line) and tick <= LyricLine._get_end_tick(line): + yield index + return -1 + + def get_index_of_line_at_tick(self, tick: int): + """ + Yield the index of the line in this proto that contains the given tick, + or -1 if no such line exists. + + Args: + tick (int): The tick to search for. + + Yields: + int: The index of the line that contains the tick, or -1 if not found. + """ + for index in Lyrics._get_index_of_line_at_tick(self._proto, tick): + yield index + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + start_tick=line_proto.words[0].start_tick, + proto=line_proto + ) + + def get_line_at_index(self, index: int): + proto = self._proto.lines[index] + if len(proto.words) == 0: + raise Exception("Lyric line has no words") + return LyricLine( + lyrics=self, + start_tick=proto.words[0].start_tick, + proto=self._proto.lines[index] + ) + + def remove_line_at_index(self, index: int): + if index < 0 or index >= len(self._proto.lines): + return + del self._proto.lines[index] + + def clone_line(self, original_line: LyricLine): + new_line = song_pb2.LyricLine() + self._proto.lines.add().CopyFrom(original_line._proto)
new_line is not used here, or you should probably create the proto first, copy it, then return a wrapper for the cloned proto
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,421 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class LyricWord: + ''' + LyricWord is the primary unit of a LyricLine + The class is a wrapper of the LyricWord proto object + A word is located with start_tick and end_tick + ''' + # The default word placeholer for an empty lyric line + PLACEHOLDER_WORD = "^%%^" + + def __init__( + self, + line: LyricLine, + word: str | None = None, + start_tick: int | None = None, + end_tick: int | None = None, + proto: song_pb2.LyricLine.LyricWord | None = None + ): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + ''' + Set a new start tick for the word. + This might delete the word if the new start tick is greater than or equal to the end tick. + + Args: + start_tick (int): The new start tick of the word. + ''' + if self._proto.start_tick >= self._proto.end_tick and resolve_order: + self.delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def set_end_tick(self, end_tick: int, resolve_order=True): + ''' + Set a new end tick for the word. + This might delete the word if the new end tick is less than or equal to the start tick. + + Args: + end_tick (int): The new end tick of the word. + ''' + if end_tick <= self._proto.start_tick and resolve_order: + self.delete_from_parent() + return + self._proto.end_tick = end_tick + + def move_to(self, start_tick: int, end_tick: int): + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + self.line.sort_words() + + def delete_from_parent(self): + ''' + Delete the word from the parent line. + ''' + self.line.remove_word(self) + + def __eq__(self, other: LyricWord): + if isinstance(other, song_pb2.LyricLine.LyricWord): + return ( + self._proto.start_tick == other.start_tick + and self._proto.end_tick == other.end_tick + and self._proto.word == other.word + ) + elif isinstance(other, LyricWord): + return ( + self._proto.start_tick == other._proto.start_tick + and self._proto.end_tick == other._proto.end_tick + and self._proto.word == other._proto.word + ) + return False + + +class LyricLine: + ''' + Lyrics is composed of a list of LyricLine objects + The class is a wrapper of the LyricLine proto object + ''' + + def __init__( + self, + lyrics: Lyrics, + start_tick: int | None = None, + proto: song_pb2.LyricLine | None = None + ): + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine() + + if len(self._proto.words) == 0: + # Create a default placeholder for the empty line + self._proto.words.add( + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + + def is_empty(self) -> bool: + # A line is empty if it only contains a placeholder word + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List[LyricWord]: + for word_proto in self._proto.words: + yield LyricWord(line=self, proto=word_proto) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + @staticmethod + def _get_start_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return line_proto.words[0].start_tick + + @staticmethod + def _get_end_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(line_proto.words, key=lambda word_proto: word_proto.end_tick).end_tick + + def get_start_tick(self) -> int: + return LyricLine._get_start_tick(self._proto) + + def get_end_tick(self) -> int: + return LyricLine._get_end_tick(self._proto) + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = round((end_tick - start_tick) / (original_end - original_start)) + for word in self.get_words(): + word_start_tick = round( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = round( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def create_words_from_string( + self, + input: str, + start_tick: int, + end_tick: int, + tokenizer: Optional[LyricTokenizer] = None, + ) -> None: + words = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(words) == 0: + return + tick_per_word = (end_tick - start_tick) // len(words) + del self._proto.words[:] + for i, word in enumerate(words): + start = start_tick + i * tick_per_word + # Adjust the last word to match the end tick + end = start_tick + (i + 1) * tick_per_word if i < len(words) - 1 else end_tick + self._proto.words.add(word=word, start_tick=start, end_tick=end) + self.sort_words() + + def create_word(self, word: str, start_tick: int, end_tick: int, resolve_order: bool = True): + if self.is_empty(): + del self._proto.words[:] + proto = self._proto.words.add(word=word, start_tick=start_tick, end_tick=end_tick) + if resolve_order: + self.sort_words() + return LyricWord( + line=self, + word=word, + start_tick=start_tick, + end_tick=end_tick, + proto=proto, + ) + + def clear(self): + new_word = self.create_placeholder_word() + del self._proto.words[:] + self._proto.words.append(new_word._proto) + + def create_placeholder_word(self): + return LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=self.get_start_tick(), + end_tick=self.get_start_tick() + DEFAULT_PPQ * 4 * 2, + ) + + def remove_word(self, word: LyricWord): + search_index = lower_equal(self._proto.words, word._proto, key=lambda word: word.start_tick) + while search_index >= 0 and self._proto.words[search_index]:
`self._proto.words[search_index]` doesn't seem to do your job, if you want to check index boundary in python you need to do it explicitly, otherwise, accessing an out of range index raises error.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,421 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class LyricWord: + ''' + LyricWord is the primary unit of a LyricLine + The class is a wrapper of the LyricWord proto object + A word is located with start_tick and end_tick + ''' + # The default word placeholer for an empty lyric line + PLACEHOLDER_WORD = "^%%^" + + def __init__( + self, + line: LyricLine, + word: str | None = None, + start_tick: int | None = None, + end_tick: int | None = None, + proto: song_pb2.LyricLine.LyricWord | None = None + ): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + ''' + Set a new start tick for the word. + This might delete the word if the new start tick is greater than or equal to the end tick. + + Args: + start_tick (int): The new start tick of the word. + ''' + if self._proto.start_tick >= self._proto.end_tick and resolve_order: + self.delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def set_end_tick(self, end_tick: int, resolve_order=True): + ''' + Set a new end tick for the word. + This might delete the word if the new end tick is less than or equal to the start tick. + + Args: + end_tick (int): The new end tick of the word. + ''' + if end_tick <= self._proto.start_tick and resolve_order: + self.delete_from_parent() + return + self._proto.end_tick = end_tick + + def move_to(self, start_tick: int, end_tick: int): + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + self.line.sort_words() + + def delete_from_parent(self): + ''' + Delete the word from the parent line. + ''' + self.line.remove_word(self) + + def __eq__(self, other: LyricWord): + if isinstance(other, song_pb2.LyricLine.LyricWord): + return ( + self._proto.start_tick == other.start_tick + and self._proto.end_tick == other.end_tick + and self._proto.word == other.word + ) + elif isinstance(other, LyricWord): + return ( + self._proto.start_tick == other._proto.start_tick + and self._proto.end_tick == other._proto.end_tick + and self._proto.word == other._proto.word + ) + return False + + +class LyricLine: + ''' + Lyrics is composed of a list of LyricLine objects + The class is a wrapper of the LyricLine proto object + ''' + + def __init__( + self, + lyrics: Lyrics, + start_tick: int | None = None, + proto: song_pb2.LyricLine | None = None + ): + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine() + + if len(self._proto.words) == 0: + # Create a default placeholder for the empty line + self._proto.words.add( + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + + def is_empty(self) -> bool: + # A line is empty if it only contains a placeholder word + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List[LyricWord]: + for word_proto in self._proto.words: + yield LyricWord(line=self, proto=word_proto) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + @staticmethod + def _get_start_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return line_proto.words[0].start_tick + + @staticmethod + def _get_end_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(line_proto.words, key=lambda word_proto: word_proto.end_tick).end_tick + + def get_start_tick(self) -> int: + return LyricLine._get_start_tick(self._proto) + + def get_end_tick(self) -> int: + return LyricLine._get_end_tick(self._proto) + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = round((end_tick - start_tick) / (original_end - original_start)) + for word in self.get_words(): + word_start_tick = round( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = round( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def create_words_from_string( + self, + input: str, + start_tick: int, + end_tick: int, + tokenizer: Optional[LyricTokenizer] = None, + ) -> None: + words = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(words) == 0: + return + tick_per_word = (end_tick - start_tick) // len(words) + del self._proto.words[:] + for i, word in enumerate(words): + start = start_tick + i * tick_per_word + # Adjust the last word to match the end tick + end = start_tick + (i + 1) * tick_per_word if i < len(words) - 1 else end_tick + self._proto.words.add(word=word, start_tick=start, end_tick=end) + self.sort_words() + + def create_word(self, word: str, start_tick: int, end_tick: int, resolve_order: bool = True): + if self.is_empty(): + del self._proto.words[:] + proto = self._proto.words.add(word=word, start_tick=start_tick, end_tick=end_tick) + if resolve_order: + self.sort_words() + return LyricWord( + line=self, + word=word, + start_tick=start_tick, + end_tick=end_tick, + proto=proto, + ) + + def clear(self): + new_word = self.create_placeholder_word() + del self._proto.words[:] + self._proto.words.append(new_word._proto) + + def create_placeholder_word(self): + return LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=self.get_start_tick(), + end_tick=self.get_start_tick() + DEFAULT_PPQ * 4 * 2, + ) + + def remove_word(self, word: LyricWord): + search_index = lower_equal(self._proto.words, word._proto, key=lambda word: word.start_tick) + while search_index >= 0 and self._proto.words[search_index]: + lyric_word = self._proto.words[search_index] + if lyric_word == word._proto:
How does this work? Does it check for all subfields?
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,421 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class LyricWord: + ''' + LyricWord is the primary unit of a LyricLine + The class is a wrapper of the LyricWord proto object + A word is located with start_tick and end_tick + ''' + # The default word placeholer for an empty lyric line + PLACEHOLDER_WORD = "^%%^" + + def __init__( + self, + line: LyricLine, + word: str | None = None, + start_tick: int | None = None, + end_tick: int | None = None, + proto: song_pb2.LyricLine.LyricWord | None = None + ): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + ''' + Set a new start tick for the word. + This might delete the word if the new start tick is greater than or equal to the end tick. + + Args: + start_tick (int): The new start tick of the word. + ''' + if self._proto.start_tick >= self._proto.end_tick and resolve_order: + self.delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def set_end_tick(self, end_tick: int, resolve_order=True): + ''' + Set a new end tick for the word. + This might delete the word if the new end tick is less than or equal to the start tick. + + Args: + end_tick (int): The new end tick of the word. + ''' + if end_tick <= self._proto.start_tick and resolve_order: + self.delete_from_parent() + return + self._proto.end_tick = end_tick + + def move_to(self, start_tick: int, end_tick: int): + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + self.line.sort_words() + + def delete_from_parent(self): + ''' + Delete the word from the parent line. + ''' + self.line.remove_word(self) + + def __eq__(self, other: LyricWord): + if isinstance(other, song_pb2.LyricLine.LyricWord): + return ( + self._proto.start_tick == other.start_tick + and self._proto.end_tick == other.end_tick + and self._proto.word == other.word + ) + elif isinstance(other, LyricWord): + return ( + self._proto.start_tick == other._proto.start_tick + and self._proto.end_tick == other._proto.end_tick + and self._proto.word == other._proto.word + ) + return False + + +class LyricLine: + ''' + Lyrics is composed of a list of LyricLine objects + The class is a wrapper of the LyricLine proto object + ''' + + def __init__( + self, + lyrics: Lyrics, + start_tick: int | None = None, + proto: song_pb2.LyricLine | None = None + ): + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine() + + if len(self._proto.words) == 0: + # Create a default placeholder for the empty line + self._proto.words.add( + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + + def is_empty(self) -> bool: + # A line is empty if it only contains a placeholder word + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List[LyricWord]: + for word_proto in self._proto.words: + yield LyricWord(line=self, proto=word_proto) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + @staticmethod + def _get_start_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return line_proto.words[0].start_tick + + @staticmethod + def _get_end_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(line_proto.words, key=lambda word_proto: word_proto.end_tick).end_tick + + def get_start_tick(self) -> int: + return LyricLine._get_start_tick(self._proto) + + def get_end_tick(self) -> int: + return LyricLine._get_end_tick(self._proto) + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = round((end_tick - start_tick) / (original_end - original_start)) + for word in self.get_words(): + word_start_tick = round( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = round( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def create_words_from_string( + self, + input: str, + start_tick: int, + end_tick: int, + tokenizer: Optional[LyricTokenizer] = None, + ) -> None: + words = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(words) == 0: + return + tick_per_word = (end_tick - start_tick) // len(words) + del self._proto.words[:] + for i, word in enumerate(words): + start = start_tick + i * tick_per_word + # Adjust the last word to match the end tick + end = start_tick + (i + 1) * tick_per_word if i < len(words) - 1 else end_tick + self._proto.words.add(word=word, start_tick=start, end_tick=end) + self.sort_words() + + def create_word(self, word: str, start_tick: int, end_tick: int, resolve_order: bool = True): + if self.is_empty(): + del self._proto.words[:] + proto = self._proto.words.add(word=word, start_tick=start_tick, end_tick=end_tick) + if resolve_order: + self.sort_words() + return LyricWord( + line=self, + word=word, + start_tick=start_tick, + end_tick=end_tick, + proto=proto, + ) + + def clear(self): + new_word = self.create_placeholder_word() + del self._proto.words[:] + self._proto.words.append(new_word._proto) + + def create_placeholder_word(self): + return LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=self.get_start_tick(), + end_tick=self.get_start_tick() + DEFAULT_PPQ * 4 * 2, + ) + + def remove_word(self, word: LyricWord): + search_index = lower_equal(self._proto.words, word._proto, key=lambda word: word.start_tick) + while search_index >= 0 and self._proto.words[search_index]: + lyric_word = self._proto.words[search_index] + if lyric_word == word._proto: + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + del self._proto.words[search_index]
I guess we should break here since we do not want to delete all occurences.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,421 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class LyricWord: + ''' + LyricWord is the primary unit of a LyricLine + The class is a wrapper of the LyricWord proto object + A word is located with start_tick and end_tick + ''' + # The default word placeholer for an empty lyric line + PLACEHOLDER_WORD = "^%%^" + + def __init__( + self, + line: LyricLine, + word: str | None = None, + start_tick: int | None = None, + end_tick: int | None = None, + proto: song_pb2.LyricLine.LyricWord | None = None + ): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + ''' + Set a new start tick for the word. + This might delete the word if the new start tick is greater than or equal to the end tick. + + Args: + start_tick (int): The new start tick of the word. + ''' + if self._proto.start_tick >= self._proto.end_tick and resolve_order: + self.delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def set_end_tick(self, end_tick: int, resolve_order=True): + ''' + Set a new end tick for the word. + This might delete the word if the new end tick is less than or equal to the start tick. + + Args: + end_tick (int): The new end tick of the word. + ''' + if end_tick <= self._proto.start_tick and resolve_order: + self.delete_from_parent() + return + self._proto.end_tick = end_tick + + def move_to(self, start_tick: int, end_tick: int): + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + self.line.sort_words() + + def delete_from_parent(self): + ''' + Delete the word from the parent line. + ''' + self.line.remove_word(self) + + def __eq__(self, other: LyricWord): + if isinstance(other, song_pb2.LyricLine.LyricWord): + return ( + self._proto.start_tick == other.start_tick + and self._proto.end_tick == other.end_tick + and self._proto.word == other.word + ) + elif isinstance(other, LyricWord): + return ( + self._proto.start_tick == other._proto.start_tick + and self._proto.end_tick == other._proto.end_tick + and self._proto.word == other._proto.word + ) + return False + + +class LyricLine: + ''' + Lyrics is composed of a list of LyricLine objects + The class is a wrapper of the LyricLine proto object + ''' + + def __init__( + self, + lyrics: Lyrics, + start_tick: int | None = None, + proto: song_pb2.LyricLine | None = None + ): + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine() + + if len(self._proto.words) == 0:
I guess this is only needed when proto is not provided.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,421 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class LyricWord: + ''' + LyricWord is the primary unit of a LyricLine + The class is a wrapper of the LyricWord proto object + A word is located with start_tick and end_tick + ''' + # The default word placeholer for an empty lyric line + PLACEHOLDER_WORD = "^%%^" + + def __init__( + self, + line: LyricLine, + word: str | None = None, + start_tick: int | None = None, + end_tick: int | None = None, + proto: song_pb2.LyricLine.LyricWord | None = None + ): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + ''' + Set a new start tick for the word. + This might delete the word if the new start tick is greater than or equal to the end tick. + + Args: + start_tick (int): The new start tick of the word. + ''' + if self._proto.start_tick >= self._proto.end_tick and resolve_order: + self.delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def set_end_tick(self, end_tick: int, resolve_order=True): + ''' + Set a new end tick for the word. + This might delete the word if the new end tick is less than or equal to the start tick. + + Args: + end_tick (int): The new end tick of the word. + ''' + if end_tick <= self._proto.start_tick and resolve_order: + self.delete_from_parent() + return + self._proto.end_tick = end_tick + + def move_to(self, start_tick: int, end_tick: int): + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + self.line.sort_words() + + def delete_from_parent(self): + ''' + Delete the word from the parent line. + ''' + self.line.remove_word(self) + + def __eq__(self, other: LyricWord): + if isinstance(other, song_pb2.LyricLine.LyricWord): + return ( + self._proto.start_tick == other.start_tick + and self._proto.end_tick == other.end_tick + and self._proto.word == other.word + ) + elif isinstance(other, LyricWord): + return ( + self._proto.start_tick == other._proto.start_tick + and self._proto.end_tick == other._proto.end_tick + and self._proto.word == other._proto.word + ) + return False + + +class LyricLine: + ''' + Lyrics is composed of a list of LyricLine objects + The class is a wrapper of the LyricLine proto object + ''' + + def __init__( + self, + lyrics: Lyrics, + start_tick: int | None = None, + proto: song_pb2.LyricLine | None = None + ): + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine() + + if len(self._proto.words) == 0: + # Create a default placeholder for the empty line + self._proto.words.add( + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + + def is_empty(self) -> bool: + # A line is empty if it only contains a placeholder word + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List[LyricWord]: + for word_proto in self._proto.words: + yield LyricWord(line=self, proto=word_proto) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + @staticmethod + def _get_start_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return line_proto.words[0].start_tick + + @staticmethod + def _get_end_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(line_proto.words, key=lambda word_proto: word_proto.end_tick).end_tick + + def get_start_tick(self) -> int: + return LyricLine._get_start_tick(self._proto) + + def get_end_tick(self) -> int: + return LyricLine._get_end_tick(self._proto) + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = round((end_tick - start_tick) / (original_end - original_start)) + for word in self.get_words(): + word_start_tick = round( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = round( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def create_words_from_string( + self, + input: str, + start_tick: int, + end_tick: int, + tokenizer: Optional[LyricTokenizer] = None, + ) -> None: + words = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(words) == 0: + return + tick_per_word = (end_tick - start_tick) // len(words) + del self._proto.words[:] + for i, word in enumerate(words): + start = start_tick + i * tick_per_word + # Adjust the last word to match the end tick + end = start_tick + (i + 1) * tick_per_word if i < len(words) - 1 else end_tick + self._proto.words.add(word=word, start_tick=start, end_tick=end) + self.sort_words() + + def create_word(self, word: str, start_tick: int, end_tick: int, resolve_order: bool = True): + if self.is_empty(): + del self._proto.words[:] + proto = self._proto.words.add(word=word, start_tick=start_tick, end_tick=end_tick) + if resolve_order: + self.sort_words() + return LyricWord( + line=self, + word=word, + start_tick=start_tick, + end_tick=end_tick, + proto=proto, + ) + + def clear(self): + new_word = self.create_placeholder_word() + del self._proto.words[:] + self._proto.words.append(new_word._proto) + + def create_placeholder_word(self): + return LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=self.get_start_tick(), + end_tick=self.get_start_tick() + DEFAULT_PPQ * 4 * 2, + ) + + def remove_word(self, word: LyricWord): + search_index = lower_equal(self._proto.words, word._proto, key=lambda word: word.start_tick) + while search_index >= 0 and self._proto.words[search_index]: + lyric_word = self._proto.words[search_index] + if lyric_word == word._proto: + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + del self._proto.words[search_index] + search_index -= 1 + + def remove_word_at_index(self, index: int): + if index < 0 or index >= len(self._proto.words): + raise IndexError("Index out of range") + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + del self._proto.words[index] + + def sort_words(self): + self._proto.words.sort(key=lambda word: word.start_tick) + self.lyrics.sort_lines() + + @staticmethod + def default_lyric_tokenizer(input: str) -> List[str]: + """ + Tokenizes the input string based on specific rules. + + Args: + input (str): The input string to be tokenized. + + Returns: + List[str]: A list of tokens generated based on the rules. + """ + tokens = [] + + current_token = '' + for char in input: + if char == ' ': + # Handle spaces + if current_token: + tokens.append(current_token) + current_token = '' + tokens.append(char) + elif re.match(r'[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]', char): + # Handle Japanese, Chinese, Korean characters + if current_token: + tokens.append(current_token) + current_token = '' + tokens.append(char) + elif unicodedata.category(char).startswith('P'): + # Handle punctuation marks + if current_token: + if re.match(r"^[']+$", char) and re.match(r'^[A-Za-z0-9]+$', current_token): + current_token += char + else: + tokens.append(current_token) + tokens.append(char) + current_token = '' + else: + tokens.append(char) + else: + current_token += char + + if current_token: + tokens.append(current_token) + + return tokens + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + ''' + Creates a new empty LyricLine object at the given start_tick. + + Args: + start_tick (int): The starting tick for the new lyric line. + resolve_order (bool, optional): Whether to sort the lyric lines by start_tick. Defaults to True. + + Returns: + LyricLine: The newly created LyricLine object. + ''' + line_proto = self._proto.lines.add() + line = LyricLine(lyrics=self, start_tick=start_tick, proto=line_proto) + if resolve_order: + self.sort_lines() + return line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + """ + Create a Line object from a string of words. + + Args: + input (str): The input string of words. + start_tick (int): The starting tick of the line. + end_tick (int): The ending tick of the line. + tokenizer (Optional[LyricTokenizer], optional): The tokenizer to use for splitting the input string into words. + If None, the default tokenizer will be used. Defaults to None. + + Returns: + Line: The created Line object. + + Raises: + ValueError: If the input string is empty. + """ + line_proto = self._proto.lines.add() + line = LyricLine(lyrics=self, start_tick=start_tick, proto=line_proto) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + @staticmethod + def _get_index_of_line_at_tick(proto: song_pb2.Lyrics, tick: int): + ''' + Internal generator implementation that locates lyrlic line at a given tick. + ''' + if len(proto.lines) == 0: + return -1 + start_search_index = lower_equal( + [LyricLine._get_start_tick(line) for line in proto.lines], + tick, + ) + for index in range(start_search_index, -1, -1): + line = proto.lines[index] + if tick >= LyricLine._get_start_tick(line) and tick <= LyricLine._get_end_tick(line): + yield index + return -1 + + def get_index_of_line_at_tick(self, tick: int): + """ + Yield the index of the line in this proto that contains the given tick, + or -1 if no such line exists. + + Args: + tick (int): The tick to search for. + + Yields: + int: The index of the line that contains the tick, or -1 if not found. + """ + for index in Lyrics._get_index_of_line_at_tick(self._proto, tick): + yield index + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + start_tick=line_proto.words[0].start_tick, + proto=line_proto + ) + + def get_line_at_index(self, index: int): + proto = self._proto.lines[index] + if len(proto.words) == 0: + raise Exception("Lyric line has no words") + return LyricLine( + lyrics=self, + start_tick=proto.words[0].start_tick,
You don't have to provide start_tick if you just need to return a wrapper.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,421 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class LyricWord: + ''' + LyricWord is the primary unit of a LyricLine + The class is a wrapper of the LyricWord proto object + A word is located with start_tick and end_tick + ''' + # The default word placeholer for an empty lyric line + PLACEHOLDER_WORD = "^%%^" + + def __init__( + self, + line: LyricLine, + word: str | None = None, + start_tick: int | None = None, + end_tick: int | None = None, + proto: song_pb2.LyricLine.LyricWord | None = None + ): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + ''' + Set a new start tick for the word. + This might delete the word if the new start tick is greater than or equal to the end tick. + + Args: + start_tick (int): The new start tick of the word. + ''' + if self._proto.start_tick >= self._proto.end_tick and resolve_order: + self.delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def set_end_tick(self, end_tick: int, resolve_order=True): + ''' + Set a new end tick for the word. + This might delete the word if the new end tick is less than or equal to the start tick. + + Args: + end_tick (int): The new end tick of the word. + ''' + if end_tick <= self._proto.start_tick and resolve_order: + self.delete_from_parent() + return + self._proto.end_tick = end_tick + + def move_to(self, start_tick: int, end_tick: int): + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + self.line.sort_words() + + def delete_from_parent(self): + ''' + Delete the word from the parent line. + ''' + self.line.remove_word(self) + + def __eq__(self, other: LyricWord): + if isinstance(other, song_pb2.LyricLine.LyricWord): + return ( + self._proto.start_tick == other.start_tick + and self._proto.end_tick == other.end_tick + and self._proto.word == other.word + ) + elif isinstance(other, LyricWord): + return ( + self._proto.start_tick == other._proto.start_tick + and self._proto.end_tick == other._proto.end_tick + and self._proto.word == other._proto.word + ) + return False + + +class LyricLine: + ''' + Lyrics is composed of a list of LyricLine objects + The class is a wrapper of the LyricLine proto object + ''' + + def __init__( + self, + lyrics: Lyrics, + start_tick: int | None = None, + proto: song_pb2.LyricLine | None = None + ): + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine() + + if len(self._proto.words) == 0: + # Create a default placeholder for the empty line + self._proto.words.add( + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + + def is_empty(self) -> bool: + # A line is empty if it only contains a placeholder word + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List[LyricWord]: + for word_proto in self._proto.words: + yield LyricWord(line=self, proto=word_proto) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + @staticmethod + def _get_start_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return line_proto.words[0].start_tick + + @staticmethod + def _get_end_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(line_proto.words, key=lambda word_proto: word_proto.end_tick).end_tick + + def get_start_tick(self) -> int: + return LyricLine._get_start_tick(self._proto) + + def get_end_tick(self) -> int: + return LyricLine._get_end_tick(self._proto) + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = round((end_tick - start_tick) / (original_end - original_start)) + for word in self.get_words(): + word_start_tick = round( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = round( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def create_words_from_string( + self, + input: str, + start_tick: int, + end_tick: int, + tokenizer: Optional[LyricTokenizer] = None, + ) -> None: + words = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(words) == 0: + return + tick_per_word = (end_tick - start_tick) // len(words) + del self._proto.words[:] + for i, word in enumerate(words): + start = start_tick + i * tick_per_word + # Adjust the last word to match the end tick + end = start_tick + (i + 1) * tick_per_word if i < len(words) - 1 else end_tick + self._proto.words.add(word=word, start_tick=start, end_tick=end) + self.sort_words() + + def create_word(self, word: str, start_tick: int, end_tick: int, resolve_order: bool = True): + if self.is_empty(): + del self._proto.words[:] + proto = self._proto.words.add(word=word, start_tick=start_tick, end_tick=end_tick) + if resolve_order: + self.sort_words() + return LyricWord( + line=self, + word=word, + start_tick=start_tick, + end_tick=end_tick, + proto=proto, + ) + + def clear(self): + new_word = self.create_placeholder_word() + del self._proto.words[:] + self._proto.words.append(new_word._proto) + + def create_placeholder_word(self): + return LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=self.get_start_tick(), + end_tick=self.get_start_tick() + DEFAULT_PPQ * 4 * 2, + ) + + def remove_word(self, word: LyricWord): + search_index = lower_equal(self._proto.words, word._proto, key=lambda word: word.start_tick) + while search_index >= 0 and self._proto.words[search_index]: + lyric_word = self._proto.words[search_index] + if lyric_word == word._proto: + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + del self._proto.words[search_index] + search_index -= 1 + + def remove_word_at_index(self, index: int): + if index < 0 or index >= len(self._proto.words): + raise IndexError("Index out of range") + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + del self._proto.words[index] + + def sort_words(self): + self._proto.words.sort(key=lambda word: word.start_tick) + self.lyrics.sort_lines() + + @staticmethod + def default_lyric_tokenizer(input: str) -> List[str]: + """ + Tokenizes the input string based on specific rules. + + Args: + input (str): The input string to be tokenized. + + Returns: + List[str]: A list of tokens generated based on the rules. + """ + tokens = [] + + current_token = '' + for char in input: + if char == ' ': + # Handle spaces + if current_token: + tokens.append(current_token) + current_token = '' + tokens.append(char) + elif re.match(r'[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]', char): + # Handle Japanese, Chinese, Korean characters + if current_token: + tokens.append(current_token) + current_token = '' + tokens.append(char) + elif unicodedata.category(char).startswith('P'): + # Handle punctuation marks + if current_token: + if re.match(r"^[']+$", char) and re.match(r'^[A-Za-z0-9]+$', current_token): + current_token += char + else: + tokens.append(current_token) + tokens.append(char) + current_token = '' + else: + tokens.append(char) + else: + current_token += char + + if current_token: + tokens.append(current_token) + + return tokens + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + ''' + Creates a new empty LyricLine object at the given start_tick. + + Args: + start_tick (int): The starting tick for the new lyric line. + resolve_order (bool, optional): Whether to sort the lyric lines by start_tick. Defaults to True. + + Returns: + LyricLine: The newly created LyricLine object. + ''' + line_proto = self._proto.lines.add() + line = LyricLine(lyrics=self, start_tick=start_tick, proto=line_proto) + if resolve_order: + self.sort_lines() + return line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + """ + Create a Line object from a string of words. + + Args: + input (str): The input string of words. + start_tick (int): The starting tick of the line. + end_tick (int): The ending tick of the line. + tokenizer (Optional[LyricTokenizer], optional): The tokenizer to use for splitting the input string into words. + If None, the default tokenizer will be used. Defaults to None. + + Returns: + Line: The created Line object. + + Raises: + ValueError: If the input string is empty. + """ + line_proto = self._proto.lines.add() + line = LyricLine(lyrics=self, start_tick=start_tick, proto=line_proto) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + @staticmethod + def _get_index_of_line_at_tick(proto: song_pb2.Lyrics, tick: int): + ''' + Internal generator implementation that locates lyrlic line at a given tick. + ''' + if len(proto.lines) == 0: + return -1 + start_search_index = lower_equal( + [LyricLine._get_start_tick(line) for line in proto.lines], + tick, + ) + for index in range(start_search_index, -1, -1): + line = proto.lines[index] + if tick >= LyricLine._get_start_tick(line) and tick <= LyricLine._get_end_tick(line): + yield index + return -1 + + def get_index_of_line_at_tick(self, tick: int): + """ + Yield the index of the line in this proto that contains the given tick, + or -1 if no such line exists. + + Args: + tick (int): The tick to search for. + + Yields: + int: The index of the line that contains the tick, or -1 if not found. + """ + for index in Lyrics._get_index_of_line_at_tick(self._proto, tick): + yield index + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + start_tick=line_proto.words[0].start_tick,
You don't have to provide start_tick if you just need to return a wrapper.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,421 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class LyricWord: + ''' + LyricWord is the primary unit of a LyricLine + The class is a wrapper of the LyricWord proto object + A word is located with start_tick and end_tick + ''' + # The default word placeholer for an empty lyric line + PLACEHOLDER_WORD = "^%%^" + + def __init__( + self, + line: LyricLine, + word: str | None = None, + start_tick: int | None = None, + end_tick: int | None = None, + proto: song_pb2.LyricLine.LyricWord | None = None + ): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + ''' + Set a new start tick for the word. + This might delete the word if the new start tick is greater than or equal to the end tick. + + Args: + start_tick (int): The new start tick of the word. + ''' + if self._proto.start_tick >= self._proto.end_tick and resolve_order: + self.delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def set_end_tick(self, end_tick: int, resolve_order=True): + ''' + Set a new end tick for the word. + This might delete the word if the new end tick is less than or equal to the start tick. + + Args: + end_tick (int): The new end tick of the word. + ''' + if end_tick <= self._proto.start_tick and resolve_order: + self.delete_from_parent() + return + self._proto.end_tick = end_tick + + def move_to(self, start_tick: int, end_tick: int): + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + self.line.sort_words() + + def delete_from_parent(self): + ''' + Delete the word from the parent line. + ''' + self.line.remove_word(self) + + def __eq__(self, other: LyricWord): + if isinstance(other, song_pb2.LyricLine.LyricWord): + return ( + self._proto.start_tick == other.start_tick + and self._proto.end_tick == other.end_tick + and self._proto.word == other.word + ) + elif isinstance(other, LyricWord): + return ( + self._proto.start_tick == other._proto.start_tick + and self._proto.end_tick == other._proto.end_tick + and self._proto.word == other._proto.word + ) + return False + + +class LyricLine: + ''' + Lyrics is composed of a list of LyricLine objects + The class is a wrapper of the LyricLine proto object + ''' + + def __init__( + self, + lyrics: Lyrics, + start_tick: int | None = None, + proto: song_pb2.LyricLine | None = None + ): + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine() + + if len(self._proto.words) == 0: + # Create a default placeholder for the empty line + self._proto.words.add( + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + + def is_empty(self) -> bool: + # A line is empty if it only contains a placeholder word + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List[LyricWord]: + for word_proto in self._proto.words: + yield LyricWord(line=self, proto=word_proto) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + @staticmethod + def _get_start_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return line_proto.words[0].start_tick + + @staticmethod + def _get_end_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(line_proto.words, key=lambda word_proto: word_proto.end_tick).end_tick + + def get_start_tick(self) -> int: + return LyricLine._get_start_tick(self._proto) + + def get_end_tick(self) -> int: + return LyricLine._get_end_tick(self._proto) + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = round((end_tick - start_tick) / (original_end - original_start)) + for word in self.get_words(): + word_start_tick = round( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = round( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def create_words_from_string( + self, + input: str, + start_tick: int, + end_tick: int, + tokenizer: Optional[LyricTokenizer] = None, + ) -> None: + words = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(words) == 0: + return + tick_per_word = (end_tick - start_tick) // len(words) + del self._proto.words[:] + for i, word in enumerate(words): + start = start_tick + i * tick_per_word + # Adjust the last word to match the end tick + end = start_tick + (i + 1) * tick_per_word if i < len(words) - 1 else end_tick + self._proto.words.add(word=word, start_tick=start, end_tick=end) + self.sort_words() + + def create_word(self, word: str, start_tick: int, end_tick: int, resolve_order: bool = True): + if self.is_empty(): + del self._proto.words[:] + proto = self._proto.words.add(word=word, start_tick=start_tick, end_tick=end_tick) + if resolve_order: + self.sort_words() + return LyricWord( + line=self, + word=word, + start_tick=start_tick, + end_tick=end_tick, + proto=proto, + ) + + def clear(self): + new_word = self.create_placeholder_word() + del self._proto.words[:] + self._proto.words.append(new_word._proto) + + def create_placeholder_word(self): + return LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=self.get_start_tick(), + end_tick=self.get_start_tick() + DEFAULT_PPQ * 4 * 2, + ) + + def remove_word(self, word: LyricWord): + search_index = lower_equal(self._proto.words, word._proto, key=lambda word: word.start_tick) + while search_index >= 0 and self._proto.words[search_index]: + lyric_word = self._proto.words[search_index] + if lyric_word == word._proto: + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + del self._proto.words[search_index] + search_index -= 1 + + def remove_word_at_index(self, index: int): + if index < 0 or index >= len(self._proto.words): + raise IndexError("Index out of range") + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + del self._proto.words[index] + + def sort_words(self): + self._proto.words.sort(key=lambda word: word.start_tick) + self.lyrics.sort_lines() + + @staticmethod + def default_lyric_tokenizer(input: str) -> List[str]: + """ + Tokenizes the input string based on specific rules. + + Args: + input (str): The input string to be tokenized. + + Returns: + List[str]: A list of tokens generated based on the rules. + """ + tokens = [] + + current_token = '' + for char in input: + if char == ' ': + # Handle spaces + if current_token: + tokens.append(current_token) + current_token = '' + tokens.append(char) + elif re.match(r'[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]', char): + # Handle Japanese, Chinese, Korean characters + if current_token: + tokens.append(current_token) + current_token = '' + tokens.append(char) + elif unicodedata.category(char).startswith('P'): + # Handle punctuation marks + if current_token: + if re.match(r"^[']+$", char) and re.match(r'^[A-Za-z0-9]+$', current_token): + current_token += char + else: + tokens.append(current_token) + tokens.append(char) + current_token = '' + else: + tokens.append(char) + else: + current_token += char + + if current_token: + tokens.append(current_token) + + return tokens + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + ''' + Creates a new empty LyricLine object at the given start_tick. + + Args: + start_tick (int): The starting tick for the new lyric line. + resolve_order (bool, optional): Whether to sort the lyric lines by start_tick. Defaults to True. + + Returns: + LyricLine: The newly created LyricLine object. + ''' + line_proto = self._proto.lines.add() + line = LyricLine(lyrics=self, start_tick=start_tick, proto=line_proto) + if resolve_order: + self.sort_lines() + return line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + """ + Create a Line object from a string of words. + + Args: + input (str): The input string of words. + start_tick (int): The starting tick of the line. + end_tick (int): The ending tick of the line. + tokenizer (Optional[LyricTokenizer], optional): The tokenizer to use for splitting the input string into words. + If None, the default tokenizer will be used. Defaults to None. + + Returns: + Line: The created Line object. + + Raises: + ValueError: If the input string is empty. + """ + line_proto = self._proto.lines.add() + line = LyricLine(lyrics=self, start_tick=start_tick, proto=line_proto) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + @staticmethod + def _get_index_of_line_at_tick(proto: song_pb2.Lyrics, tick: int): + ''' + Internal generator implementation that locates lyrlic line at a given tick. + ''' + if len(proto.lines) == 0: + return -1 + start_search_index = lower_equal( + [LyricLine._get_start_tick(line) for line in proto.lines], + tick, + ) + for index in range(start_search_index, -1, -1): + line = proto.lines[index] + if tick >= LyricLine._get_start_tick(line) and tick <= LyricLine._get_end_tick(line): + yield index + return -1 + + def get_index_of_line_at_tick(self, tick: int): + """ + Yield the index of the line in this proto that contains the given tick, + or -1 if no such line exists. + + Args: + tick (int): The tick to search for. + + Yields: + int: The index of the line that contains the tick, or -1 if not found. + """ + for index in Lyrics._get_index_of_line_at_tick(self._proto, tick): + yield index + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + start_tick=line_proto.words[0].start_tick, + proto=line_proto + ) + + def get_line_at_index(self, index: int): + proto = self._proto.lines[index] + if len(proto.words) == 0: + raise Exception("Lyric line has no words") + return LyricLine( + lyrics=self, + start_tick=proto.words[0].start_tick, + proto=self._proto.lines[index] + ) + + def remove_line_at_index(self, index: int): + if index < 0 or index >= len(self._proto.lines): + return + del self._proto.lines[index] + + def clone_line(self, original_line: LyricLine): + new_line = song_pb2.LyricLine() + self._proto.lines.add().CopyFrom(original_line._proto) + self.sort_lines() + return new_line
The wrapper should be returned instead of the proto
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,205 @@ +import unittest +from typing import Dict +from tuneflow_py.models.song import Song +from tuneflow_py.models.lyric import Lyrics, LyricLine, LyricWord + +DEFAULT_PPQ = Song.get_default_resolution() + + +def assert_lyric_lines_equal(expected: Dict, actual: LyricLine): + if expected["sentence"] != actual.get_sentence(): + raise Exception( + f'Lyric lines are not equal. Expected sentence {expected["sentence"]} but got {actual.get_sentence()}' + ) + if expected["start_tick"] != actual.get_start_tick(): + raise Exception( + f'Lyric lines are not equal. Expected start tick {expected["start_tick"]} but got {actual.get_start_tick()}' + ) + if expected["end_tick"] != actual.get_end_tick(): + raise Exception( + f'Lyric lines are not equal. Expected end tick {expected["end_tick"]} but got {actual.get_end_tick()}' + ) + + +def create_lyrics(): + song = Song() + lyrics = Lyrics(song) + lyrics.create_line_from_string("Hello world this is a test.", 10, 50) + lyrics.create_line_from_string("Mixing symbols & numbers 12345, special #%$^characters, LoWeR uPPeR CaSe", 60, 100) + lyrics.create_line_from_string("émphasis on accénts, we also allow overlapping", 50, 110) + # This is an example of Chinese lyrics. + lyrics.create_line_from_string("这是一个中文歌词的例子。", 500, 550) + # This is an example of Japanese lyrics. + lyrics.create_line_from_string("これは日本語の歌詞の例です。", 600, 650) + return lyrics + + +class TestLyrics(unittest.TestCase): + def test_create_line(self): + lyrics = create_lyrics() + line = lyrics.create_line(660) + self.assertEqual(len(lyrics._proto.lines), 6) + self.assertEqual(line.is_empty(), True) + assert_lyric_lines_equal({"sentence": "", "start_tick": 660, "end_tick": 1140}, line) + + def test_create_line_from_string(self): + lyrics = create_lyrics() + line = lyrics.create_line_from_string("Hello world! 你好世界!", 10, 50) + self.assertEqual(len(lyrics._proto.lines), 6) + assert_lyric_lines_equal({ + "sentence": "Hello world! 你好世界!", + "start_tick": 10, + "end_tick": 50 + }, line) + + def test_remove_line_at_index(self): + lyrics = create_lyrics() + lyrics.create_line(11) + lyrics.create_line(20) + self.assertEqual(len(lyrics._proto.lines), 7) + lyrics.remove_line_at_index(5) + self.assertEqual(len(lyrics._proto.lines), 6) + lyrics.remove_line_at_index(4) + lyrics.remove_line_at_index(1) + lyrics.remove_line_at_index(2) + lyrics.remove_line_at_index(1) + self.assertEqual(len(lyrics._proto.lines), 2) + assert_lyric_lines_equal({ + "sentence": "Hello world this is a test.", + "start_tick": 10, + "end_tick": 50 + }, lyrics.get_line_at_index(0)) + + def test_clone_line(self): + lyrics = create_lyrics() + line = lyrics.create_line(300) + new_line = lyrics.clone_line(line) + self.assertEqual(len(lyrics._proto.lines), 7) + # Check the cloned line + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, new_line) + # Check if cloned and sorted properly + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, lyrics.get_line_at_index(3)) + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, lyrics.get_line_at_index(4)) + + def test_clear(self): + lyrics = create_lyrics() + lyrics.create_line(10) + lyrics.clear() + self.assertEqual(len(lyrics._proto.lines), 0) + + +class TestLyricLine(unittest.TestCase):
You also need to provide a method to update the line with a string and test it here.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,205 @@ +import unittest +from typing import Dict +from tuneflow_py.models.song import Song +from tuneflow_py.models.lyric import Lyrics, LyricLine, LyricWord + +DEFAULT_PPQ = Song.get_default_resolution() + + +def assert_lyric_lines_equal(expected: Dict, actual: LyricLine): + if expected["sentence"] != actual.get_sentence(): + raise Exception( + f'Lyric lines are not equal. Expected sentence {expected["sentence"]} but got {actual.get_sentence()}' + ) + if expected["start_tick"] != actual.get_start_tick(): + raise Exception( + f'Lyric lines are not equal. Expected start tick {expected["start_tick"]} but got {actual.get_start_tick()}' + ) + if expected["end_tick"] != actual.get_end_tick(): + raise Exception( + f'Lyric lines are not equal. Expected end tick {expected["end_tick"]} but got {actual.get_end_tick()}' + ) + + +def create_lyrics(): + song = Song() + lyrics = Lyrics(song) + lyrics.create_line_from_string("Hello world this is a test.", 10, 50) + lyrics.create_line_from_string("Mixing symbols & numbers 12345, special #%$^characters, LoWeR uPPeR CaSe", 60, 100) + lyrics.create_line_from_string("émphasis on accénts, we also allow overlapping", 50, 110) + # This is an example of Chinese lyrics. + lyrics.create_line_from_string("这是一个中文歌词的例子。", 500, 550) + # This is an example of Japanese lyrics. + lyrics.create_line_from_string("これは日本語の歌詞の例です。", 600, 650) + return lyrics + + +class TestLyrics(unittest.TestCase): + def test_create_line(self): + lyrics = create_lyrics() + line = lyrics.create_line(660) + self.assertEqual(len(lyrics._proto.lines), 6) + self.assertEqual(line.is_empty(), True) + assert_lyric_lines_equal({"sentence": "", "start_tick": 660, "end_tick": 1140}, line) + + def test_create_line_from_string(self): + lyrics = create_lyrics() + line = lyrics.create_line_from_string("Hello world! 你好世界!", 10, 50) + self.assertEqual(len(lyrics._proto.lines), 6) + assert_lyric_lines_equal({ + "sentence": "Hello world! 你好世界!", + "start_tick": 10, + "end_tick": 50 + }, line) + + def test_remove_line_at_index(self): + lyrics = create_lyrics() + lyrics.create_line(11) + lyrics.create_line(20) + self.assertEqual(len(lyrics._proto.lines), 7) + lyrics.remove_line_at_index(5) + self.assertEqual(len(lyrics._proto.lines), 6) + lyrics.remove_line_at_index(4) + lyrics.remove_line_at_index(1) + lyrics.remove_line_at_index(2) + lyrics.remove_line_at_index(1) + self.assertEqual(len(lyrics._proto.lines), 2) + assert_lyric_lines_equal({ + "sentence": "Hello world this is a test.", + "start_tick": 10, + "end_tick": 50 + }, lyrics.get_line_at_index(0)) + + def test_clone_line(self): + lyrics = create_lyrics() + line = lyrics.create_line(300) + new_line = lyrics.clone_line(line) + self.assertEqual(len(lyrics._proto.lines), 7) + # Check the cloned line + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, new_line) + # Check if cloned and sorted properly + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, lyrics.get_line_at_index(3)) + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, lyrics.get_line_at_index(4)) + + def test_clear(self): + lyrics = create_lyrics() + lyrics.create_line(10) + lyrics.clear() + self.assertEqual(len(lyrics._proto.lines), 0) + + +class TestLyricLine(unittest.TestCase): + def test_create_word(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + line.create_word("first", 15, 20) + line.create_word("second", 30, 50) + self.assertEqual(len(line._proto.words), 2) + self.assertEqual(line._proto.words[0].word, "first") + self.assertEqual(line._proto.words[1].word, "second") + + def test_clear(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + line.create_word("first", 15, 20) + line.create_word("second", 30, 50) + line.clear()
assert before this to check the word count is larger than 1.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,205 @@ +import unittest +from typing import Dict +from tuneflow_py.models.song import Song +from tuneflow_py.models.lyric import Lyrics, LyricLine, LyricWord + +DEFAULT_PPQ = Song.get_default_resolution() + + +def assert_lyric_lines_equal(expected: Dict, actual: LyricLine): + if expected["sentence"] != actual.get_sentence(): + raise Exception( + f'Lyric lines are not equal. Expected sentence {expected["sentence"]} but got {actual.get_sentence()}' + ) + if expected["start_tick"] != actual.get_start_tick(): + raise Exception( + f'Lyric lines are not equal. Expected start tick {expected["start_tick"]} but got {actual.get_start_tick()}' + ) + if expected["end_tick"] != actual.get_end_tick(): + raise Exception( + f'Lyric lines are not equal. Expected end tick {expected["end_tick"]} but got {actual.get_end_tick()}' + ) + + +def create_lyrics(): + song = Song() + lyrics = Lyrics(song) + lyrics.create_line_from_string("Hello world this is a test.", 10, 50) + lyrics.create_line_from_string("Mixing symbols & numbers 12345, special #%$^characters, LoWeR uPPeR CaSe", 60, 100) + lyrics.create_line_from_string("émphasis on accénts, we also allow overlapping", 50, 110) + # This is an example of Chinese lyrics. + lyrics.create_line_from_string("这是一个中文歌词的例子。", 500, 550) + # This is an example of Japanese lyrics. + lyrics.create_line_from_string("これは日本語の歌詞の例です。", 600, 650) + return lyrics + + +class TestLyrics(unittest.TestCase): + def test_create_line(self): + lyrics = create_lyrics() + line = lyrics.create_line(660) + self.assertEqual(len(lyrics._proto.lines), 6) + self.assertEqual(line.is_empty(), True) + assert_lyric_lines_equal({"sentence": "", "start_tick": 660, "end_tick": 1140}, line) + + def test_create_line_from_string(self): + lyrics = create_lyrics() + line = lyrics.create_line_from_string("Hello world! 你好世界!", 10, 50) + self.assertEqual(len(lyrics._proto.lines), 6) + assert_lyric_lines_equal({ + "sentence": "Hello world! 你好世界!", + "start_tick": 10, + "end_tick": 50 + }, line) + + def test_remove_line_at_index(self): + lyrics = create_lyrics() + lyrics.create_line(11) + lyrics.create_line(20) + self.assertEqual(len(lyrics._proto.lines), 7) + lyrics.remove_line_at_index(5) + self.assertEqual(len(lyrics._proto.lines), 6) + lyrics.remove_line_at_index(4) + lyrics.remove_line_at_index(1) + lyrics.remove_line_at_index(2) + lyrics.remove_line_at_index(1) + self.assertEqual(len(lyrics._proto.lines), 2) + assert_lyric_lines_equal({ + "sentence": "Hello world this is a test.", + "start_tick": 10, + "end_tick": 50 + }, lyrics.get_line_at_index(0)) + + def test_clone_line(self): + lyrics = create_lyrics() + line = lyrics.create_line(300) + new_line = lyrics.clone_line(line) + self.assertEqual(len(lyrics._proto.lines), 7) + # Check the cloned line + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, new_line) + # Check if cloned and sorted properly + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, lyrics.get_line_at_index(3)) + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, lyrics.get_line_at_index(4)) + + def test_clear(self): + lyrics = create_lyrics() + lyrics.create_line(10) + lyrics.clear() + self.assertEqual(len(lyrics._proto.lines), 0) + + +class TestLyricLine(unittest.TestCase): + def test_create_word(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + line.create_word("first", 15, 20) + line.create_word("second", 30, 50) + self.assertEqual(len(line._proto.words), 2) + self.assertEqual(line._proto.words[0].word, "first") + self.assertEqual(line._proto.words[1].word, "second") + + def test_clear(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + line.create_word("first", 15, 20) + line.create_word("second", 30, 50) + line.clear() + self.assertEqual(len(line._proto.words), 1) + self.assertEqual(line.is_empty(), True) + + def test_get_index_of_line_at_tick(self): + lyrics = create_lyrics() + lyrics.create_line(10) + lyrics.create_line(20) + index_generator = lyrics.get_index_of_line_at_tick(10) + self.assertEqual(next(index_generator), 1) + self.assertEqual(next(index_generator), 0) + + def test_remove_word_at_index(self): + lyrics = create_lyrics() + line = lyrics.create_line(9) + line.create_word("test", 15, 20) + # Replace the empty word + self.assertEqual(len(line._proto.words), 1) + line.remove_word_at_index(0)
Assert the word content as well.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,205 @@ +import unittest +from typing import Dict +from tuneflow_py.models.song import Song +from tuneflow_py.models.lyric import Lyrics, LyricLine, LyricWord + +DEFAULT_PPQ = Song.get_default_resolution() + + +def assert_lyric_lines_equal(expected: Dict, actual: LyricLine): + if expected["sentence"] != actual.get_sentence(): + raise Exception( + f'Lyric lines are not equal. Expected sentence {expected["sentence"]} but got {actual.get_sentence()}' + ) + if expected["start_tick"] != actual.get_start_tick(): + raise Exception( + f'Lyric lines are not equal. Expected start tick {expected["start_tick"]} but got {actual.get_start_tick()}' + ) + if expected["end_tick"] != actual.get_end_tick(): + raise Exception( + f'Lyric lines are not equal. Expected end tick {expected["end_tick"]} but got {actual.get_end_tick()}' + ) + + +def create_lyrics(): + song = Song() + lyrics = Lyrics(song) + lyrics.create_line_from_string("Hello world this is a test.", 10, 50) + lyrics.create_line_from_string("Mixing symbols & numbers 12345, special #%$^characters, LoWeR uPPeR CaSe", 60, 100) + lyrics.create_line_from_string("émphasis on accénts, we also allow overlapping", 50, 110) + # This is an example of Chinese lyrics. + lyrics.create_line_from_string("这是一个中文歌词的例子。", 500, 550) + # This is an example of Japanese lyrics. + lyrics.create_line_from_string("これは日本語の歌詞の例です。", 600, 650) + return lyrics + + +class TestLyrics(unittest.TestCase): + def test_create_line(self): + lyrics = create_lyrics() + line = lyrics.create_line(660) + self.assertEqual(len(lyrics._proto.lines), 6) + self.assertEqual(line.is_empty(), True) + assert_lyric_lines_equal({"sentence": "", "start_tick": 660, "end_tick": 1140}, line) + + def test_create_line_from_string(self): + lyrics = create_lyrics() + line = lyrics.create_line_from_string("Hello world! 你好世界!", 10, 50) + self.assertEqual(len(lyrics._proto.lines), 6) + assert_lyric_lines_equal({ + "sentence": "Hello world! 你好世界!", + "start_tick": 10, + "end_tick": 50 + }, line) + + def test_remove_line_at_index(self): + lyrics = create_lyrics() + lyrics.create_line(11) + lyrics.create_line(20) + self.assertEqual(len(lyrics._proto.lines), 7) + lyrics.remove_line_at_index(5) + self.assertEqual(len(lyrics._proto.lines), 6) + lyrics.remove_line_at_index(4) + lyrics.remove_line_at_index(1) + lyrics.remove_line_at_index(2) + lyrics.remove_line_at_index(1) + self.assertEqual(len(lyrics._proto.lines), 2) + assert_lyric_lines_equal({ + "sentence": "Hello world this is a test.", + "start_tick": 10, + "end_tick": 50 + }, lyrics.get_line_at_index(0)) + + def test_clone_line(self): + lyrics = create_lyrics() + line = lyrics.create_line(300) + new_line = lyrics.clone_line(line) + self.assertEqual(len(lyrics._proto.lines), 7) + # Check the cloned line + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, new_line) + # Check if cloned and sorted properly + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, lyrics.get_line_at_index(3)) + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, lyrics.get_line_at_index(4)) + + def test_clear(self): + lyrics = create_lyrics() + lyrics.create_line(10) + lyrics.clear() + self.assertEqual(len(lyrics._proto.lines), 0) + + +class TestLyricLine(unittest.TestCase): + def test_create_word(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + line.create_word("first", 15, 20) + line.create_word("second", 30, 50) + self.assertEqual(len(line._proto.words), 2) + self.assertEqual(line._proto.words[0].word, "first") + self.assertEqual(line._proto.words[1].word, "second") + + def test_clear(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + line.create_word("first", 15, 20) + line.create_word("second", 30, 50) + line.clear() + self.assertEqual(len(line._proto.words), 1) + self.assertEqual(line.is_empty(), True) + + def test_get_index_of_line_at_tick(self): + lyrics = create_lyrics() + lyrics.create_line(10) + lyrics.create_line(20) + index_generator = lyrics.get_index_of_line_at_tick(10) + self.assertEqual(next(index_generator), 1) + self.assertEqual(next(index_generator), 0) + + def test_remove_word_at_index(self): + lyrics = create_lyrics() + line = lyrics.create_line(9) + line.create_word("test", 15, 20) + # Replace the empty word + self.assertEqual(len(line._proto.words), 1) + line.remove_word_at_index(0) + # There will be 1 placeholder left + self.assertEqual(len(line._proto.words), 1) + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 15, + "end_tick": 15 + DEFAULT_PPQ * 4 * 2 + }, lyrics.get_line_at_index(1)) + + def test_remove_word(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + word = line.create_word("first", 15, 20) + line.remove_word(word)
Same here, assert both before and after your primary operation, and make sure your assertion captures the difference outcome before and after, so that it's clear that your operation did what you want.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,205 @@ +import unittest +from typing import Dict +from tuneflow_py.models.song import Song +from tuneflow_py.models.lyric import Lyrics, LyricLine, LyricWord + +DEFAULT_PPQ = Song.get_default_resolution() + + +def assert_lyric_lines_equal(expected: Dict, actual: LyricLine): + if expected["sentence"] != actual.get_sentence(): + raise Exception( + f'Lyric lines are not equal. Expected sentence {expected["sentence"]} but got {actual.get_sentence()}' + ) + if expected["start_tick"] != actual.get_start_tick(): + raise Exception( + f'Lyric lines are not equal. Expected start tick {expected["start_tick"]} but got {actual.get_start_tick()}' + ) + if expected["end_tick"] != actual.get_end_tick(): + raise Exception( + f'Lyric lines are not equal. Expected end tick {expected["end_tick"]} but got {actual.get_end_tick()}' + ) + + +def create_lyrics(): + song = Song() + lyrics = Lyrics(song) + lyrics.create_line_from_string("Hello world this is a test.", 10, 50) + lyrics.create_line_from_string("Mixing symbols & numbers 12345, special #%$^characters, LoWeR uPPeR CaSe", 60, 100) + lyrics.create_line_from_string("émphasis on accénts, we also allow overlapping", 50, 110) + # This is an example of Chinese lyrics. + lyrics.create_line_from_string("这是一个中文歌词的例子。", 500, 550) + # This is an example of Japanese lyrics. + lyrics.create_line_from_string("これは日本語の歌詞の例です。", 600, 650) + return lyrics + + +class TestLyrics(unittest.TestCase): + def test_create_line(self): + lyrics = create_lyrics() + line = lyrics.create_line(660) + self.assertEqual(len(lyrics._proto.lines), 6) + self.assertEqual(line.is_empty(), True) + assert_lyric_lines_equal({"sentence": "", "start_tick": 660, "end_tick": 1140}, line) + + def test_create_line_from_string(self): + lyrics = create_lyrics() + line = lyrics.create_line_from_string("Hello world! 你好世界!", 10, 50) + self.assertEqual(len(lyrics._proto.lines), 6) + assert_lyric_lines_equal({ + "sentence": "Hello world! 你好世界!", + "start_tick": 10, + "end_tick": 50 + }, line) + + def test_remove_line_at_index(self): + lyrics = create_lyrics() + lyrics.create_line(11) + lyrics.create_line(20) + self.assertEqual(len(lyrics._proto.lines), 7) + lyrics.remove_line_at_index(5) + self.assertEqual(len(lyrics._proto.lines), 6) + lyrics.remove_line_at_index(4) + lyrics.remove_line_at_index(1) + lyrics.remove_line_at_index(2) + lyrics.remove_line_at_index(1) + self.assertEqual(len(lyrics._proto.lines), 2) + assert_lyric_lines_equal({ + "sentence": "Hello world this is a test.", + "start_tick": 10, + "end_tick": 50 + }, lyrics.get_line_at_index(0)) + + def test_clone_line(self): + lyrics = create_lyrics() + line = lyrics.create_line(300) + new_line = lyrics.clone_line(line) + self.assertEqual(len(lyrics._proto.lines), 7) + # Check the cloned line + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, new_line) + # Check if cloned and sorted properly + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, lyrics.get_line_at_index(3)) + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, lyrics.get_line_at_index(4)) + + def test_clear(self): + lyrics = create_lyrics() + lyrics.create_line(10) + lyrics.clear() + self.assertEqual(len(lyrics._proto.lines), 0) + + +class TestLyricLine(unittest.TestCase): + def test_create_word(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + line.create_word("first", 15, 20) + line.create_word("second", 30, 50) + self.assertEqual(len(line._proto.words), 2) + self.assertEqual(line._proto.words[0].word, "first") + self.assertEqual(line._proto.words[1].word, "second") + + def test_clear(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + line.create_word("first", 15, 20) + line.create_word("second", 30, 50) + line.clear() + self.assertEqual(len(line._proto.words), 1) + self.assertEqual(line.is_empty(), True) + + def test_get_index_of_line_at_tick(self): + lyrics = create_lyrics() + lyrics.create_line(10) + lyrics.create_line(20) + index_generator = lyrics.get_index_of_line_at_tick(10) + self.assertEqual(next(index_generator), 1) + self.assertEqual(next(index_generator), 0) + + def test_remove_word_at_index(self): + lyrics = create_lyrics() + line = lyrics.create_line(9) + line.create_word("test", 15, 20) + # Replace the empty word + self.assertEqual(len(line._proto.words), 1) + line.remove_word_at_index(0) + # There will be 1 placeholder left + self.assertEqual(len(line._proto.words), 1) + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 15, + "end_tick": 15 + DEFAULT_PPQ * 4 * 2 + }, lyrics.get_line_at_index(1)) + + def test_remove_word(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + word = line.create_word("first", 15, 20) + line.remove_word(word) + self.assertEqual(len(line._proto.words), 1) + self.assertEqual(line.is_empty(), True) + + +class TestLyricWord(unittest.TestCase): + def test_set_word(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + word = line._proto.words[0] + word = LyricWord(line, "test", 10, 20, word) + word.set_word("changed") + self.assertEqual(word.get_word(), "changed") + + def test_set_start_tick(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + word = line.create_word("test", 15, 20) + word.set_start_tick(5) + self.assertEqual(word.get_start_tick(), 5) + self.assertEqual(line.get_start_tick(), 5) + + def test_set_end_tick(self): + lyrics = create_lyrics() + line = lyrics.create_line(20) + word = line.create_word("test", 15, 20) + word.set_end_tick(30) + self.assertEqual(word.get_end_tick(), 30) + assert_lyric_lines_equal({ + "sentence": "test", + "start_tick": 15, + "end_tick": 30 + }, lyrics.get_line_at_index(1)) + + def test_move_to(self):
You also need to add a test where moving the word changes the order of lines. I would split the tests into 3: test_move_to_basic, test_move_to_delete_word, test_move_to_changes_line_order
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,205 @@ +import unittest +from typing import Dict +from tuneflow_py.models.song import Song +from tuneflow_py.models.lyric import Lyrics, LyricLine, LyricWord + +DEFAULT_PPQ = Song.get_default_resolution() + + +def assert_lyric_lines_equal(expected: Dict, actual: LyricLine): + if expected["sentence"] != actual.get_sentence(): + raise Exception( + f'Lyric lines are not equal. Expected sentence {expected["sentence"]} but got {actual.get_sentence()}' + ) + if expected["start_tick"] != actual.get_start_tick(): + raise Exception( + f'Lyric lines are not equal. Expected start tick {expected["start_tick"]} but got {actual.get_start_tick()}' + ) + if expected["end_tick"] != actual.get_end_tick(): + raise Exception( + f'Lyric lines are not equal. Expected end tick {expected["end_tick"]} but got {actual.get_end_tick()}' + ) + + +def create_lyrics(): + song = Song() + lyrics = Lyrics(song) + lyrics.create_line_from_string("Hello world this is a test.", 10, 50) + lyrics.create_line_from_string("Mixing symbols & numbers 12345, special #%$^characters, LoWeR uPPeR CaSe", 60, 100) + lyrics.create_line_from_string("émphasis on accénts, we also allow overlapping", 50, 110) + # This is an example of Chinese lyrics. + lyrics.create_line_from_string("这是一个中文歌词的例子。", 500, 550) + # This is an example of Japanese lyrics. + lyrics.create_line_from_string("これは日本語の歌詞の例です。", 600, 650) + return lyrics + + +class TestLyrics(unittest.TestCase): + def test_create_line(self): + lyrics = create_lyrics() + line = lyrics.create_line(660) + self.assertEqual(len(lyrics._proto.lines), 6) + self.assertEqual(line.is_empty(), True) + assert_lyric_lines_equal({"sentence": "", "start_tick": 660, "end_tick": 1140}, line) + + def test_create_line_from_string(self): + lyrics = create_lyrics() + line = lyrics.create_line_from_string("Hello world! 你好世界!", 10, 50) + self.assertEqual(len(lyrics._proto.lines), 6) + assert_lyric_lines_equal({ + "sentence": "Hello world! 你好世界!", + "start_tick": 10, + "end_tick": 50 + }, line) + + def test_remove_line_at_index(self): + lyrics = create_lyrics() + lyrics.create_line(11) + lyrics.create_line(20) + self.assertEqual(len(lyrics._proto.lines), 7) + lyrics.remove_line_at_index(5) + self.assertEqual(len(lyrics._proto.lines), 6) + lyrics.remove_line_at_index(4) + lyrics.remove_line_at_index(1) + lyrics.remove_line_at_index(2) + lyrics.remove_line_at_index(1) + self.assertEqual(len(lyrics._proto.lines), 2) + assert_lyric_lines_equal({ + "sentence": "Hello world this is a test.", + "start_tick": 10, + "end_tick": 50 + }, lyrics.get_line_at_index(0)) + + def test_clone_line(self): + lyrics = create_lyrics() + line = lyrics.create_line(300) + new_line = lyrics.clone_line(line) + self.assertEqual(len(lyrics._proto.lines), 7) + # Check the cloned line + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, new_line) + # Check if cloned and sorted properly + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, lyrics.get_line_at_index(3)) + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, lyrics.get_line_at_index(4)) + + def test_clear(self): + lyrics = create_lyrics() + lyrics.create_line(10) + lyrics.clear() + self.assertEqual(len(lyrics._proto.lines), 0) + + +class TestLyricLine(unittest.TestCase): + def test_create_word(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + line.create_word("first", 15, 20) + line.create_word("second", 30, 50) + self.assertEqual(len(line._proto.words), 2) + self.assertEqual(line._proto.words[0].word, "first") + self.assertEqual(line._proto.words[1].word, "second") + + def test_clear(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + line.create_word("first", 15, 20) + line.create_word("second", 30, 50) + line.clear() + self.assertEqual(len(line._proto.words), 1) + self.assertEqual(line.is_empty(), True) + + def test_get_index_of_line_at_tick(self): + lyrics = create_lyrics() + lyrics.create_line(10) + lyrics.create_line(20) + index_generator = lyrics.get_index_of_line_at_tick(10) + self.assertEqual(next(index_generator), 1) + self.assertEqual(next(index_generator), 0) + + def test_remove_word_at_index(self): + lyrics = create_lyrics() + line = lyrics.create_line(9) + line.create_word("test", 15, 20) + # Replace the empty word + self.assertEqual(len(line._proto.words), 1) + line.remove_word_at_index(0) + # There will be 1 placeholder left + self.assertEqual(len(line._proto.words), 1) + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 15, + "end_tick": 15 + DEFAULT_PPQ * 4 * 2 + }, lyrics.get_line_at_index(1)) + + def test_remove_word(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + word = line.create_word("first", 15, 20) + line.remove_word(word) + self.assertEqual(len(line._proto.words), 1) + self.assertEqual(line.is_empty(), True) + + +class TestLyricWord(unittest.TestCase): + def test_set_word(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + word = line._proto.words[0] + word = LyricWord(line, "test", 10, 20, word) + word.set_word("changed") + self.assertEqual(word.get_word(), "changed") + + def test_set_start_tick(self): + lyrics = create_lyrics()
Add another test for when we delete the word after changing start tick. Same for end tick.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,205 @@ +import unittest +from typing import Dict +from tuneflow_py.models.song import Song +from tuneflow_py.models.lyric import Lyrics, LyricLine, LyricWord + +DEFAULT_PPQ = Song.get_default_resolution() + + +def assert_lyric_lines_equal(expected: Dict, actual: LyricLine): + if expected["sentence"] != actual.get_sentence(): + raise Exception( + f'Lyric lines are not equal. Expected sentence {expected["sentence"]} but got {actual.get_sentence()}' + ) + if expected["start_tick"] != actual.get_start_tick(): + raise Exception( + f'Lyric lines are not equal. Expected start tick {expected["start_tick"]} but got {actual.get_start_tick()}' + ) + if expected["end_tick"] != actual.get_end_tick(): + raise Exception( + f'Lyric lines are not equal. Expected end tick {expected["end_tick"]} but got {actual.get_end_tick()}' + ) + + +def create_lyrics(): + song = Song() + lyrics = Lyrics(song) + lyrics.create_line_from_string("Hello world this is a test.", 10, 50) + lyrics.create_line_from_string("Mixing symbols & numbers 12345, special #%$^characters, LoWeR uPPeR CaSe", 60, 100) + lyrics.create_line_from_string("émphasis on accénts, we also allow overlapping", 50, 110) + # This is an example of Chinese lyrics. + lyrics.create_line_from_string("这是一个中文歌词的例子。", 500, 550) + # This is an example of Japanese lyrics. + lyrics.create_line_from_string("これは日本語の歌詞の例です。", 600, 650) + return lyrics + + +class TestLyrics(unittest.TestCase): + def test_create_line(self): + lyrics = create_lyrics() + line = lyrics.create_line(660) + self.assertEqual(len(lyrics._proto.lines), 6) + self.assertEqual(line.is_empty(), True) + assert_lyric_lines_equal({"sentence": "", "start_tick": 660, "end_tick": 1140}, line) + + def test_create_line_from_string(self): + lyrics = create_lyrics() + line = lyrics.create_line_from_string("Hello world! 你好世界!", 10, 50) + self.assertEqual(len(lyrics._proto.lines), 6) + assert_lyric_lines_equal({ + "sentence": "Hello world! 你好世界!", + "start_tick": 10, + "end_tick": 50 + }, line) + + def test_remove_line_at_index(self): + lyrics = create_lyrics() + lyrics.create_line(11) + lyrics.create_line(20) + self.assertEqual(len(lyrics._proto.lines), 7) + lyrics.remove_line_at_index(5) + self.assertEqual(len(lyrics._proto.lines), 6) + lyrics.remove_line_at_index(4) + lyrics.remove_line_at_index(1) + lyrics.remove_line_at_index(2) + lyrics.remove_line_at_index(1) + self.assertEqual(len(lyrics._proto.lines), 2) + assert_lyric_lines_equal({ + "sentence": "Hello world this is a test.", + "start_tick": 10, + "end_tick": 50 + }, lyrics.get_line_at_index(0)) + + def test_clone_line(self): + lyrics = create_lyrics() + line = lyrics.create_line(300) + new_line = lyrics.clone_line(line) + self.assertEqual(len(lyrics._proto.lines), 7) + # Check the cloned line + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, new_line) + # Check if cloned and sorted properly + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, lyrics.get_line_at_index(3)) + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, lyrics.get_line_at_index(4)) + + def test_clear(self): + lyrics = create_lyrics() + lyrics.create_line(10) + lyrics.clear() + self.assertEqual(len(lyrics._proto.lines), 0) + + +class TestLyricLine(unittest.TestCase): + def test_create_word(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + line.create_word("first", 15, 20) + line.create_word("second", 30, 50) + self.assertEqual(len(line._proto.words), 2) + self.assertEqual(line._proto.words[0].word, "first") + self.assertEqual(line._proto.words[1].word, "second") + + def test_clear(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + line.create_word("first", 15, 20) + line.create_word("second", 30, 50) + line.clear() + self.assertEqual(len(line._proto.words), 1) + self.assertEqual(line.is_empty(), True) + + def test_get_index_of_line_at_tick(self): + lyrics = create_lyrics() + lyrics.create_line(10) + lyrics.create_line(20) + index_generator = lyrics.get_index_of_line_at_tick(10) + self.assertEqual(next(index_generator), 1) + self.assertEqual(next(index_generator), 0) + + def test_remove_word_at_index(self): + lyrics = create_lyrics() + line = lyrics.create_line(9) + line.create_word("test", 15, 20) + # Replace the empty word + self.assertEqual(len(line._proto.words), 1) + line.remove_word_at_index(0) + # There will be 1 placeholder left + self.assertEqual(len(line._proto.words), 1) + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 15, + "end_tick": 15 + DEFAULT_PPQ * 4 * 2 + }, lyrics.get_line_at_index(1)) + + def test_remove_word(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + word = line.create_word("first", 15, 20) + line.remove_word(word) + self.assertEqual(len(line._proto.words), 1) + self.assertEqual(line.is_empty(), True) + + +class TestLyricWord(unittest.TestCase): + def test_set_word(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + word = line._proto.words[0] + word = LyricWord(line, "test", 10, 20, word) + word.set_word("changed") + self.assertEqual(word.get_word(), "changed") + + def test_set_start_tick(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + word = line.create_word("test", 15, 20) + word.set_start_tick(5) + self.assertEqual(word.get_start_tick(), 5) + self.assertEqual(line.get_start_tick(), 5)
You should also check for the change of line order
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,420 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class LyricWord: + ''' + LyricWord is the primary unit of a LyricLine + The class is a wrapper of the LyricWord proto object + A word is located with start_tick and end_tick + ''' + # The default word placeholer for an empty lyric line + PLACEHOLDER_WORD = "^%%^" + + def __init__( + self, + line: LyricLine, + word: str | None = None, + start_tick: int | None = None, + end_tick: int | None = None, + proto: song_pb2.LyricLine.LyricWord | None = None + ): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + ''' + Set a new start tick for the word. + This might delete the word if the new start tick is greater than or equal to the end tick. + + Args: + start_tick (int): The new start tick of the word. + ''' + if self._proto.start_tick >= self._proto.end_tick and resolve_order: + self.delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def set_end_tick(self, end_tick: int, resolve_order=True): + ''' + Set a new end tick for the word. + This might delete the word if the new end tick is less than or equal to the start tick. + + Args: + end_tick (int): The new end tick of the word. + ''' + if end_tick <= self._proto.start_tick and resolve_order: + self.delete_from_parent() + return + self._proto.end_tick = end_tick + + def move_to(self, start_tick: int, end_tick: int): + if start_tick >= end_tick: + self.delete_from_parent() + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + self.line.sort_words() + + def delete_from_parent(self): + ''' + Delete the word from the parent line. + ''' + self.line.remove_word(self) + + def __eq__(self, other: LyricWord): + if isinstance(other, song_pb2.LyricLine.LyricWord): + return ( + self._proto.start_tick == other.start_tick + and self._proto.end_tick == other.end_tick + and self._proto.word == other.word + ) + elif isinstance(other, LyricWord): + return ( + self._proto.start_tick == other._proto.start_tick + and self._proto.end_tick == other._proto.end_tick + and self._proto.word == other._proto.word + ) + return False + + +class LyricLine: + ''' + Lyrics is composed of a list of LyricLine objects + ''' + + def __init__( + self, + lyrics: Lyrics, + start_tick: int | None = None, + proto: song_pb2.LyricLine | None = None + ): + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine() + + if len(self._proto.words) == 0: + # Create a default placeholder for the empty line + self._proto.words.add( + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + + def is_empty(self) -> bool: + # A line is empty if it only contains a placeholder word + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List[LyricWord]:
You probably also want to add a `get_word_at_index` method.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,420 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class LyricWord: + ''' + LyricWord is the primary unit of a LyricLine + The class is a wrapper of the LyricWord proto object + A word is located with start_tick and end_tick + ''' + # The default word placeholer for an empty lyric line + PLACEHOLDER_WORD = "^%%^" + + def __init__( + self, + line: LyricLine, + word: str | None = None, + start_tick: int | None = None, + end_tick: int | None = None, + proto: song_pb2.LyricLine.LyricWord | None = None + ): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + ''' + Set a new start tick for the word. + This might delete the word if the new start tick is greater than or equal to the end tick. + + Args: + start_tick (int): The new start tick of the word. + ''' + if self._proto.start_tick >= self._proto.end_tick and resolve_order: + self.delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def set_end_tick(self, end_tick: int, resolve_order=True): + ''' + Set a new end tick for the word. + This might delete the word if the new end tick is less than or equal to the start tick. + + Args: + end_tick (int): The new end tick of the word. + ''' + if end_tick <= self._proto.start_tick and resolve_order: + self.delete_from_parent() + return + self._proto.end_tick = end_tick + + def move_to(self, start_tick: int, end_tick: int): + if start_tick >= end_tick: + self.delete_from_parent() + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + self.line.sort_words() + + def delete_from_parent(self): + ''' + Delete the word from the parent line. + ''' + self.line.remove_word(self) + + def __eq__(self, other: LyricWord): + if isinstance(other, song_pb2.LyricLine.LyricWord): + return ( + self._proto.start_tick == other.start_tick + and self._proto.end_tick == other.end_tick + and self._proto.word == other.word + ) + elif isinstance(other, LyricWord): + return ( + self._proto.start_tick == other._proto.start_tick + and self._proto.end_tick == other._proto.end_tick + and self._proto.word == other._proto.word + ) + return False + + +class LyricLine: + ''' + Lyrics is composed of a list of LyricLine objects + ''' + + def __init__( + self, + lyrics: Lyrics, + start_tick: int | None = None, + proto: song_pb2.LyricLine | None = None + ): + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine() + + if len(self._proto.words) == 0: + # Create a default placeholder for the empty line + self._proto.words.add( + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + + def is_empty(self) -> bool: + # A line is empty if it only contains a placeholder word + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List[LyricWord]: + for word_proto in self._proto.words: + yield LyricWord(line=self, proto=word_proto) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + @staticmethod + def _get_start_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return line_proto.words[0].start_tick + + @staticmethod + def _get_end_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(line_proto.words, key=lambda word_proto: word_proto.end_tick).end_tick + + def get_start_tick(self) -> int: + return LyricLine._get_start_tick(self._proto) + + def get_end_tick(self) -> int: + return LyricLine._get_end_tick(self._proto) + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = round((end_tick - start_tick) / (original_end - original_start)) + for word in self.get_words(): + word_start_tick = round( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = round( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def create_words_from_string( + self, + input: str, + start_tick: int, + end_tick: int, + tokenizer: Optional[LyricTokenizer] = None, + ) -> None: + words = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(words) == 0: + return + tick_per_word = (end_tick - start_tick) // len(words) + del self._proto.words[:] + for i, word in enumerate(words): + start = start_tick + i * tick_per_word + # Adjust the last word to match the end tick + end = start_tick + (i + 1) * tick_per_word if i < len(words) - 1 else end_tick + self._proto.words.add(word=word, start_tick=start, end_tick=end) + self.sort_words() + + def create_word(self, word: str, start_tick: int, end_tick: int, resolve_order: bool = True): + if self.is_empty(): + del self._proto.words[:] + proto = self._proto.words.add(word=word, start_tick=start_tick, end_tick=end_tick) + if resolve_order: + self.sort_words() + return LyricWord( + line=self, + word=word, + start_tick=start_tick, + end_tick=end_tick, + proto=proto, + ) + + def clear(self): + new_word = self.create_placeholder_word() + del self._proto.words[:] + self._proto.words.append(new_word._proto) + + def create_placeholder_word(self): + return LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=self.get_start_tick(), + end_tick=self.get_start_tick() + DEFAULT_PPQ * 4 * 2, + ) + + def remove_word(self, word: LyricWord): + search_index = lower_equal(self._proto.words, word._proto, key=lambda word: word.start_tick) + while search_index >= 0 and self._proto.words[search_index]: + lyric_word = self._proto.words[search_index] + if lyric_word == word._proto: + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + del self._proto.words[search_index] + search_index -= 1 + + def remove_word_at_index(self, index: int): + if index < 0 or index >= len(self._proto.words): + raise IndexError("Index out of range") + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + del self._proto.words[index] + + def sort_words(self): + self._proto.words.sort(key=lambda word: word.start_tick) + self.lyrics.sort_lines() + + @staticmethod + def default_lyric_tokenizer(input: str) -> List[str]: + """ + Tokenizes the input string based on specific rules. + + Args: + input (str): The input string to be tokenized. + + Returns: + List[str]: A list of tokens generated based on the rules. + """ + tokens = [] + + current_token = '' + for char in input: + if char == ' ': + # Handle spaces + if current_token: + tokens.append(current_token) + current_token = '' + tokens.append(char) + elif re.match(r'[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]', char): + # Handle Japanese, Chinese, Korean characters + if current_token: + tokens.append(current_token) + current_token = '' + tokens.append(char) + elif unicodedata.category(char).startswith('P'): + # Handle punctuation marks + if current_token: + if re.match(r"^[']+$", char) and re.match(r'^[A-Za-z0-9]+$', current_token): + current_token += char + else: + tokens.append(current_token) + tokens.append(char) + current_token = '' + else: + tokens.append(char) + else: + current_token += char + + if current_token: + tokens.append(current_token) + + return tokens + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + ''' + Creates a new empty LyricLine object at the given start_tick. + + Args: + start_tick (int): The starting tick for the new lyric line. + resolve_order (bool, optional): Whether to sort the lyric lines by start_tick. Defaults to True. + + Returns: + LyricLine: The newly created LyricLine object. + ''' + line_proto = self._proto.lines.add() + line = LyricLine(lyrics=self, start_tick=start_tick, proto=line_proto) + if resolve_order: + self.sort_lines() + return line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + """ + Create a Line object from a string of words. + + Args: + input (str): The input string of words. + start_tick (int): The starting tick of the line. + end_tick (int): The ending tick of the line. + tokenizer (Optional[LyricTokenizer], optional): The tokenizer to use for splitting the input string into words. + If None, the default tokenizer will be used. Defaults to None. + + Returns: + Line: The created Line object. + + Raises: + ValueError: If the input string is empty. + """ + line_proto = self._proto.lines.add() + line = LyricLine(lyrics=self, start_tick=start_tick, proto=line_proto) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + @staticmethod + def _get_index_of_line_at_tick(proto: song_pb2.Lyrics, tick: int): + ''' + Internal generator implementation that locates lyrlic line at a given tick. + ''' + if len(proto.lines) == 0: + return -1 + start_search_index = lower_equal( + [LyricLine._get_start_tick(line) for line in proto.lines], + tick, + ) + for index in range(start_search_index, -1, -1): + line = proto.lines[index] + if tick >= LyricLine._get_start_tick(line) and tick <= LyricLine._get_end_tick(line): + yield index + return -1 + + def get_index_of_line_at_tick(self, tick: int): + """ + Yield the index of the line in this proto that contains the given tick, + or -1 if no such line exists. + + Args: + tick (int): The tick to search for. + + Yields: + int: The index of the line that contains the tick, or -1 if not found. + """ + for index in Lyrics._get_index_of_line_at_tick(self._proto, tick): + yield index + + def get_lines(self): + for line_proto in self._proto.lines: + if len(line_proto.words) == 0: + raise Exception("Lyric line has no words") + yield LyricLine( + lyrics=self, + proto=line_proto + ) + + def get_line_at_index(self, index: int): + proto = self._proto.lines[index] + if len(proto.words) == 0: + raise Exception("Lyric line has no words") + return LyricLine( + lyrics=self, + proto=self._proto.lines[index] + ) + + def remove_line_at_index(self, index: int): + if index < 0 or index >= len(self._proto.lines): + return + del self._proto.lines[index] + + def clone_line(self, original_line: LyricLine):
Test this as well.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,420 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class LyricWord: + ''' + LyricWord is the primary unit of a LyricLine + The class is a wrapper of the LyricWord proto object + A word is located with start_tick and end_tick + ''' + # The default word placeholer for an empty lyric line + PLACEHOLDER_WORD = "^%%^" + + def __init__( + self, + line: LyricLine, + word: str | None = None, + start_tick: int | None = None, + end_tick: int | None = None, + proto: song_pb2.LyricLine.LyricWord | None = None + ): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + ''' + Set a new start tick for the word. + This might delete the word if the new start tick is greater than or equal to the end tick. + + Args: + start_tick (int): The new start tick of the word. + ''' + if self._proto.start_tick >= self._proto.end_tick and resolve_order: + self.delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def set_end_tick(self, end_tick: int, resolve_order=True): + ''' + Set a new end tick for the word. + This might delete the word if the new end tick is less than or equal to the start tick. + + Args: + end_tick (int): The new end tick of the word. + ''' + if end_tick <= self._proto.start_tick and resolve_order: + self.delete_from_parent() + return + self._proto.end_tick = end_tick + + def move_to(self, start_tick: int, end_tick: int): + if start_tick >= end_tick: + self.delete_from_parent() + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + self.line.sort_words() + + def delete_from_parent(self): + ''' + Delete the word from the parent line. + ''' + self.line.remove_word(self) + + def __eq__(self, other: LyricWord): + if isinstance(other, song_pb2.LyricLine.LyricWord): + return ( + self._proto.start_tick == other.start_tick + and self._proto.end_tick == other.end_tick + and self._proto.word == other.word + ) + elif isinstance(other, LyricWord): + return ( + self._proto.start_tick == other._proto.start_tick + and self._proto.end_tick == other._proto.end_tick + and self._proto.word == other._proto.word + ) + return False + + +class LyricLine: + ''' + Lyrics is composed of a list of LyricLine objects + ''' + + def __init__( + self, + lyrics: Lyrics, + start_tick: int | None = None, + proto: song_pb2.LyricLine | None = None + ): + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine() + + if len(self._proto.words) == 0: + # Create a default placeholder for the empty line + self._proto.words.add( + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + + def is_empty(self) -> bool: + # A line is empty if it only contains a placeholder word + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> List[LyricWord]: + for word_proto in self._proto.words: + yield LyricWord(line=self, proto=word_proto) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + @staticmethod + def _get_start_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return line_proto.words[0].start_tick + + @staticmethod + def _get_end_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(line_proto.words, key=lambda word_proto: word_proto.end_tick).end_tick + + def get_start_tick(self) -> int: + return LyricLine._get_start_tick(self._proto) + + def get_end_tick(self) -> int: + return LyricLine._get_end_tick(self._proto) + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = round((end_tick - start_tick) / (original_end - original_start)) + for word in self.get_words(): + word_start_tick = round( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = round( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def create_words_from_string( + self, + input: str, + start_tick: int, + end_tick: int, + tokenizer: Optional[LyricTokenizer] = None, + ) -> None: + words = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(words) == 0: + return + tick_per_word = (end_tick - start_tick) // len(words) + del self._proto.words[:] + for i, word in enumerate(words): + start = start_tick + i * tick_per_word + # Adjust the last word to match the end tick + end = start_tick + (i + 1) * tick_per_word if i < len(words) - 1 else end_tick + self._proto.words.add(word=word, start_tick=start, end_tick=end) + self.sort_words() + + def create_word(self, word: str, start_tick: int, end_tick: int, resolve_order: bool = True): + if self.is_empty(): + del self._proto.words[:] + proto = self._proto.words.add(word=word, start_tick=start_tick, end_tick=end_tick) + if resolve_order: + self.sort_words() + return LyricWord( + line=self, + word=word, + start_tick=start_tick, + end_tick=end_tick, + proto=proto, + ) + + def clear(self): + new_word = self.create_placeholder_word() + del self._proto.words[:] + self._proto.words.append(new_word._proto) + + def create_placeholder_word(self): + return LyricWord( + line=self, + word=LyricWord.PLACEHOLDER_WORD, + start_tick=self.get_start_tick(), + end_tick=self.get_start_tick() + DEFAULT_PPQ * 4 * 2, + ) + + def remove_word(self, word: LyricWord): + search_index = lower_equal(self._proto.words, word._proto, key=lambda word: word.start_tick) + while search_index >= 0 and self._proto.words[search_index]: + lyric_word = self._proto.words[search_index] + if lyric_word == word._proto: + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + del self._proto.words[search_index] + search_index -= 1 + + def remove_word_at_index(self, index: int): + if index < 0 or index >= len(self._proto.words): + raise IndexError("Index out of range") + if len(self._proto.words) == 1: + # Words will become empty, insert a default placeholder. + self.clear() + else: + del self._proto.words[index] + + def sort_words(self): + self._proto.words.sort(key=lambda word: word.start_tick) + self.lyrics.sort_lines() + + @staticmethod + def default_lyric_tokenizer(input: str) -> List[str]: + """ + Tokenizes the input string based on specific rules. + + Args: + input (str): The input string to be tokenized. + + Returns: + List[str]: A list of tokens generated based on the rules. + """ + tokens = [] + + current_token = '' + for char in input: + if char == ' ': + # Handle spaces + if current_token: + tokens.append(current_token) + current_token = '' + tokens.append(char) + elif re.match(r'[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]', char): + # Handle Japanese, Chinese, Korean characters + if current_token: + tokens.append(current_token) + current_token = '' + tokens.append(char) + elif unicodedata.category(char).startswith('P'): + # Handle punctuation marks + if current_token: + if re.match(r"^[']+$", char) and re.match(r'^[A-Za-z0-9]+$', current_token): + current_token += char + else: + tokens.append(current_token) + tokens.append(char) + current_token = '' + else: + tokens.append(char) + else: + current_token += char + + if current_token: + tokens.append(current_token) + + return tokens + + +class Lyrics: + def __init__(self, song: Song) -> None: + self.song = song + if song._proto.lyrics is None: + song._proto.lyrics = song_pb2.Lyrics() + self._proto = song._proto.lyrics + + def create_line(self, start_tick: int, resolve_order: bool = True): + ''' + Creates a new empty LyricLine object at the given start_tick. + + Args: + start_tick (int): The starting tick for the new lyric line. + resolve_order (bool, optional): Whether to sort the lyric lines by start_tick. Defaults to True. + + Returns: + LyricLine: The newly created LyricLine object. + ''' + line_proto = self._proto.lines.add() + line = LyricLine(lyrics=self, start_tick=start_tick, proto=line_proto) + if resolve_order: + self.sort_lines() + return line + + def create_line_from_string(self, input: str, start_tick: int, end_tick: int, tokenizer: Optional[LyricTokenizer] = None): + """ + Create a Line object from a string of words. + + Args: + input (str): The input string of words. + start_tick (int): The starting tick of the line. + end_tick (int): The ending tick of the line. + tokenizer (Optional[LyricTokenizer], optional): The tokenizer to use for splitting the input string into words. + If None, the default tokenizer will be used. Defaults to None. + + Returns: + Line: The created Line object. + + Raises: + ValueError: If the input string is empty. + """ + line_proto = self._proto.lines.add() + line = LyricLine(lyrics=self, start_tick=start_tick, proto=line_proto) + if not input: + return line + line.create_words_from_string(input, start_tick, end_tick, tokenizer) + return line + + @staticmethod + def _get_index_of_line_at_tick(proto: song_pb2.Lyrics, tick: int): + ''' + Internal generator implementation that locates lyrlic line at a given tick. + ''' + if len(proto.lines) == 0: + return -1 + start_search_index = lower_equal( + [LyricLine._get_start_tick(line) for line in proto.lines],
This invalidates the whole purpose of this binary search since its complexity is already O(N). You could pass a key function that checks for the type of element and returns tick if it is a number, or LyricLine._get_start_tick(line) otherwise.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -465,6 +469,27 @@ def seconds_to_tick(self, seconds: float): ) return round(base_tempo_change_proto.ticks + time_delta * ticks_per_second_since_last_tempo_change) + def advance_tick_by_bars(original_tick: int, offset_bar: int, offset_beat: int, bar_beats: List[BarBeat]) -> Optional[int]:
If we want to check this in we need to add tests for it.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,503 @@ +from __future__ import annotations +import re +from typing import Callable, List, Optional, Generator +import unicodedata + +from tuneflow_py.utils import lower_equal +from tuneflow_py.models.protos import song_pb2 +from tuneflow_py.models.song import Song + +LyricTokenizer = Callable[[str], List[str]] +DEFAULT_PPQ = Song.get_default_resolution() + + +class LyricWord: + ''' + LyricWord is the primary unit of a LyricLine + The class is a wrapper of the LyricWord proto object + A word is located with start_tick and end_tick + ''' + # The default word placeholer for an empty lyric line + PLACEHOLDER_WORD = "^%%^" + + def __init__( + self, + line: LyricLine, + word: str | None = None, + start_tick: int | None = None, + end_tick: int | None = None, + proto: song_pb2.LyricLine.LyricWord | None = None + ): + self.line = line + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine.LyricWord() + self._proto.word = word + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + + def get_line(self): + return self.line + + def get_word(self): + return self._proto.word + + def set_word(self, word: str): + if not word: + raise ValueError("Word cannot be empty") + self._proto.word = word + + def get_start_tick(self): + return self._proto.start_tick + + def set_start_tick(self, start_tick: int, resolve_order=True): + ''' + Set a new start tick for the word. + This might delete the word if the new start tick is greater than or equal to the end tick. + + Args: + start_tick (int): The new start tick of the word. + ''' + if self._proto.start_tick >= self._proto.end_tick and resolve_order: + self._delete_from_parent() + return + self._proto.start_tick = start_tick + if resolve_order: + self.line.sort_words() + + def get_end_tick(self): + return self._proto.end_tick + + def set_end_tick(self, end_tick: int, resolve_order=True): + ''' + Set a new end tick for the word. + This might delete the word if the new end tick is less than or equal to the start tick. + + Args: + end_tick (int): The new end tick of the word. + ''' + if end_tick <= self._proto.start_tick and resolve_order: + self._delete_from_parent() + return + self._proto.end_tick = end_tick + + def move_to(self, start_tick: int, end_tick: int): + if start_tick >= end_tick: + self._delete_from_parent() + self._proto.start_tick = start_tick + self._proto.end_tick = end_tick + self.line.sort_words() + + def _delete_from_parent(self): + ''' + Delete the word from the parent line. + ''' + self.line.remove_word(self) + + def __eq__(self, other: LyricWord): + return ( + self._proto.start_tick == other._proto.start_tick + and self._proto.end_tick == other._proto.end_tick + and self._proto.word == other._proto.word + ) + + +class LyricLine: + ''' + Lyrics is composed of a list of LyricLine objects + ''' + + def __init__( + self, + lyrics: Lyrics, + start_tick: int | None = None, + proto: song_pb2.LyricLine | None = None + ): + self.lyrics = lyrics + if proto is not None: + self._proto = proto + else: + self._proto = song_pb2.LyricLine() + + if len(self._proto.words) == 0: + # Create a default placeholder for the empty line + self._proto.words.add( + word=LyricWord.PLACEHOLDER_WORD, + start_tick=start_tick, + end_tick=start_tick + DEFAULT_PPQ, + ) + + def __len__(self) -> int: + if self.is_empty(): + return 0 + return len(self._proto.words) + + def __getitem__(self, index: int) -> LyricWord: + return self.get_word_at_index(index) + + def is_empty(self) -> bool: + # A line is empty if it only contains a placeholder word + return len(self._proto.words) == 1 and self._proto.words[0].word == LyricWord.PLACEHOLDER_WORD + + def get_words(self) -> Generator: + for word_proto in self._proto.words: + yield LyricWord(line=self, proto=word_proto) + + def get_sentence(self) -> str: + if self.is_empty(): + return "" + return "".join(word_proto.word for word_proto in self._proto.words) + + @staticmethod + def _get_start_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return line_proto.words[0].start_tick + + @staticmethod + def _get_end_tick(line_proto: song_pb2.LyricLine) -> int: + if len(line_proto.words) == 0: + raise ValueError("Words cannot be empty") + return max(line_proto.words, key=lambda word_proto: word_proto.end_tick).end_tick + + def get_start_tick(self) -> int: + return LyricLine._get_start_tick(self._proto) + + def get_end_tick(self) -> int: + return LyricLine._get_end_tick(self._proto) + + def move_to(self, start_tick: int, end_tick: int) -> None: + original_start = self.get_start_tick() + original_end = self.get_end_tick() + if original_start is None or original_end is None: + return + start_tick = max(start_tick, 0) + end_tick = max(end_tick, start_tick) + ratio = round((end_tick - start_tick) / (original_end - original_start)) + for word in self.get_words(): + word_start_tick = round( + start_tick + (word.get_start_tick() - original_start) * ratio + ) + word_end_tick = round( + start_tick + (word.get_end_tick() - original_start) * ratio + ) + word.move_to(word_start_tick, word_end_tick) + + def _set_words_from_tokens( + self, + tokens: List[str], + start_tick: int, + end_tick: int, + ): + if len(tokens) == 0: + self.clear() + return + tick_per_word = (end_tick - start_tick) // len(tokens) + del self._proto.words[:] + for i, word in enumerate(tokens): + start = start_tick + i * tick_per_word + # Adjust the last word to match the end tick + end = start_tick + (i + 1) * tick_per_word if i < len(tokens) - 1 else end_tick + self._proto.words.add(word=word, start_tick=start, end_tick=end) + self.sort_words() + + def set_words_from_string( + self, + input: str, + start_tick: int | None = None, + end_tick: int | None = None, + tokenizer: Optional[LyricTokenizer] = None, + ): + ''' + Update lyric word objects of the line from a string of words + The string is split into words with a tokenizer if provided + Otherwise, the default tokenizer is used + + Args: + input (str): The string of words + start_tick (int | None): The start tick of the line. Use the original tick if set None + end_tick (int | None): The end tick of the line. Use the original tick if set None + tokenizer (Optional[LyricTokenizer]): The tokenizer to use + ''' + start_tick = self.get_start_tick() if start_tick is None else start_tick + end_tick = self.get_end_tick() if end_tick is None else end_tick + tokens = ( + tokenizer(input) if tokenizer + else LyricLine.default_lyric_tokenizer(input) + ) + if len(tokens) == 0: + self.clear() + self._set_words_from_tokens(tokens, start_tick, end_tick) + + @staticmethod + def _get_index_of_word_at_tick(line: song_pb2.LyricLine, tick: int): + ''' + Internal generator implementation that locates word at a given tick. + ''' + if len(line.words) == 0 or tick < LyricLine._get_start_tick(line) or tick >= LyricLine._get_end_tick(line): + return -1 + index = lower_equal( + line.words, + tick, + key=lambda item: item if isinstance(item, int) else item.start_tick + ) + if index in range(len(line.words)): + return index + return -1 + + def get_index_of_word_at_tick(self, tick: int): + ''' + Return the index of the word in this proto that contains the given tick, + or -1 if no such word exists. + + Args: + tick (int): The tick to search for. + + Return: + int: The index of the line that contains the tick, or -1 if not found. + ''' + return LyricLine._get_index_of_word_at_tick(self._proto, tick) + + def create_word(self, word: str, start_tick: int, end_tick: int, resolve_order: bool = True): + if self.is_empty(): + # Remove the placeholder + del self._proto.words[:] + proto = self._proto.words.add(word=word, start_tick=start_tick, end_tick=end_tick) + if resolve_order: + self.sort_words() + return LyricWord(
I think the principle here is that you don't need to provide more params if you already provided the proto and the parent
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -12,7 +12,8 @@ from miditoolkit.midi import MidiFile, TempoChange as ToolkitTempoChange, TimeSignature as ToolkitTimeSignature, \ Instrument, Note as ToolkitNote from types import SimpleNamespace -from typing import List +from typing import List, List, Optional +from dataclasses import dataclass
Is this used?
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -12,7 +12,8 @@ from miditoolkit.midi import MidiFile, TempoChange as ToolkitTempoChange, TimeSignature as ToolkitTimeSignature, \ Instrument, Note as ToolkitNote from types import SimpleNamespace -from typing import List +from typing import List, List, Optional
List imported twice
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,397 @@ +import unittest +from typing import Dict +from tuneflow_py.models.song import Song +from tuneflow_py.models.lyric import Lyrics, LyricLine, LyricWord + +DEFAULT_PPQ = Song.get_default_resolution() + + +def assert_lyric_lines_equal(expected: Dict, actual: LyricLine): + if expected["sentence"] != actual.get_sentence(): + raise Exception( + f'Lyric lines are not equal. Expected sentence {expected["sentence"]} but got {actual.get_sentence()}' + ) + if expected["start_tick"] != actual.get_start_tick(): + raise Exception( + f'Lyric lines are not equal. Expected start tick {expected["start_tick"]} but got {actual.get_start_tick()}' + ) + if expected["end_tick"] != actual.get_end_tick(): + raise Exception( + f'Lyric lines are not equal. Expected end tick {expected["end_tick"]} but got {actual.get_end_tick()}' + ) + + +def assert_lyric_words_equal(expected: Dict, actual: LyricWord): + if expected["word"] != actual.get_word(): + raise Exception( + f'Lyric words are not equal. Expected word {expected["word"]} but got {actual.get_word()}' + ) + if expected["start_tick"] != actual.get_start_tick(): + raise Exception( + f'Lyric words are not equal. Expected start tick {expected["start_tick"]} but got {actual.get_start_tick()}' + ) + if expected["end_tick"] != actual.get_end_tick(): + raise Exception( + f'Lyric words are not equal. Expected end tick {expected["end_tick"]} but got {actual.get_end_tick()}' + ) + + +def create_lyrics(): + song = Song() + lyrics = Lyrics(song) + lyrics.create_line_from_string("Hello world this is a test.", 10, 50) + lyrics.create_line_from_string("Mixing symbols & numbers 12345, special #%$^characters, LoWeR uPPeR CaSe", 60, 100) + lyrics.create_line_from_string("émphasis on accénts, we also allow overlapping", 50, 110) + # This is an example of Chinese lyrics. + lyrics.create_line_from_string("这是一个中文歌词的例子。", 500, 550) + # This is an example of Japanese lyrics. + lyrics.create_line_from_string("これは日本語の歌詞の例です。", 600, 650) + return lyrics + + +class TestLyrics(unittest.TestCase): + def test_create_line(self): + lyrics = create_lyrics() + self.assertEqual(len(lyrics), 5) + line = lyrics.create_line(660) + self.assertEqual(len(lyrics), 6) + self.assertEqual(line.is_empty(), True) + assert_lyric_lines_equal({"sentence": "", "start_tick": 660, "end_tick": 1140}, line) + + def test_create_line_from_string(self): + lyrics = create_lyrics() + self.assertEqual(len(lyrics), 5) + line = lyrics.create_line_from_string("Hello world! 你好世界!", 10, 50)
We also need to test the words in it, making sure the tokenizer is working intended and the timespan of the words are assigned correctly.
tuneflow-py
github_2023
python
3
tuneflow
andantei
@@ -0,0 +1,397 @@ +import unittest +from typing import Dict +from tuneflow_py.models.song import Song +from tuneflow_py.models.lyric import Lyrics, LyricLine, LyricWord + +DEFAULT_PPQ = Song.get_default_resolution() + + +def assert_lyric_lines_equal(expected: Dict, actual: LyricLine): + if expected["sentence"] != actual.get_sentence(): + raise Exception( + f'Lyric lines are not equal. Expected sentence {expected["sentence"]} but got {actual.get_sentence()}' + ) + if expected["start_tick"] != actual.get_start_tick(): + raise Exception( + f'Lyric lines are not equal. Expected start tick {expected["start_tick"]} but got {actual.get_start_tick()}' + ) + if expected["end_tick"] != actual.get_end_tick(): + raise Exception( + f'Lyric lines are not equal. Expected end tick {expected["end_tick"]} but got {actual.get_end_tick()}' + ) + + +def assert_lyric_words_equal(expected: Dict, actual: LyricWord): + if expected["word"] != actual.get_word(): + raise Exception( + f'Lyric words are not equal. Expected word {expected["word"]} but got {actual.get_word()}' + ) + if expected["start_tick"] != actual.get_start_tick(): + raise Exception( + f'Lyric words are not equal. Expected start tick {expected["start_tick"]} but got {actual.get_start_tick()}' + ) + if expected["end_tick"] != actual.get_end_tick(): + raise Exception( + f'Lyric words are not equal. Expected end tick {expected["end_tick"]} but got {actual.get_end_tick()}' + ) + + +def create_lyrics(): + song = Song() + lyrics = Lyrics(song) + lyrics.create_line_from_string("Hello world this is a test.", 10, 50) + lyrics.create_line_from_string("Mixing symbols & numbers 12345, special #%$^characters, LoWeR uPPeR CaSe", 60, 100) + lyrics.create_line_from_string("émphasis on accénts, we also allow overlapping", 50, 110) + # This is an example of Chinese lyrics. + lyrics.create_line_from_string("这是一个中文歌词的例子。", 500, 550) + # This is an example of Japanese lyrics. + lyrics.create_line_from_string("これは日本語の歌詞の例です。", 600, 650) + return lyrics + + +class TestLyrics(unittest.TestCase): + def test_create_line(self): + lyrics = create_lyrics() + self.assertEqual(len(lyrics), 5) + line = lyrics.create_line(660) + self.assertEqual(len(lyrics), 6) + self.assertEqual(line.is_empty(), True) + assert_lyric_lines_equal({"sentence": "", "start_tick": 660, "end_tick": 1140}, line) + + def test_create_line_from_string(self): + lyrics = create_lyrics() + self.assertEqual(len(lyrics), 5) + line = lyrics.create_line_from_string("Hello world! 你好世界!", 10, 50) + self.assertEqual(len(lyrics), 6) + assert_lyric_lines_equal({ + "sentence": "Hello world! 你好世界!", + "start_tick": 10, + "end_tick": 50 + }, line) + + def test_set_words(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 10, + "end_tick": 10 + DEFAULT_PPQ, + }, lyrics[1]) + # Test updating words without changing the start and end tick + line.set_words_from_string("Set words from string without movement") + assert_lyric_lines_equal({ + "sentence": "Set words from string without movement", + "start_tick": 10, + "end_tick": 10 + DEFAULT_PPQ, + }, line) + # Test updating words and changing the start and end tick + line.set_words_from_string("Set words from string with movement", 10, 12) + self.assertEqual(len(line), 11) + assert_lyric_lines_equal({ + "sentence": "Set words from string with movement", + "start_tick": 10, + "end_tick": 12, + }, line) + # Test setting words to none + line.set_words_from_string("") + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 10, + "end_tick": 10 + DEFAULT_PPQ * 4 * 2, + }, line) + + def test_remove_line_at_index(self): + lyrics = create_lyrics() + self.assertEqual(len(lyrics), 5) + lyrics.create_line(11) + lyrics.create_line(20) + self.assertEqual(len(lyrics), 7) + lyrics.remove_line_at_index(5) + self.assertEqual(len(lyrics), 6) + lyrics.remove_line_at_index(4) + lyrics.remove_line_at_index(1) + lyrics.remove_line_at_index(2) + lyrics.remove_line_at_index(1) + self.assertEqual(len(lyrics), 2) + assert_lyric_lines_equal({ + "sentence": "Hello world this is a test.", + "start_tick": 10, + "end_tick": 50 + }, lyrics[0]) + + def test_remove_line(self): + lyrics = create_lyrics() + self.assertEqual(len(lyrics), 5) + line = lyrics.create_line(50) + self.assertEqual(len(lyrics), 6) + lyrics.remove_line(line) + self.assertEqual(len(lyrics), 5) + lyrics.remove_line(lyrics[4]) + lyrics.remove_line(lyrics[3]) + lyrics.remove_line(lyrics[2]) + lyrics.remove_line(lyrics[1]) + self.assertEqual(len(lyrics), 1) + assert_lyric_lines_equal({ + "sentence": "Hello world this is a test.", + "start_tick": 10, + "end_tick": 50 + }, lyrics[0]) + + def test_clone_line(self): + lyrics = create_lyrics() + self.assertEqual(len(lyrics), 5) + line = lyrics.create_line(300) + new_line = lyrics.clone_line(line) + self.assertEqual(len(lyrics), 7) + # Check the cloned line + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, new_line) + # Check if cloned and sorted properly + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, lyrics[3]) + assert_lyric_lines_equal({ + "sentence": "", + "start_tick": 300, + "end_tick": 780 + }, lyrics[4]) + + def test_create_word(self): + lyrics = create_lyrics() + line = lyrics.create_line(300) + self.assertEqual(line.is_empty(), True) + line.create_word("second", 15, 20) + line.create_word(" ", 13, 15) + line.create_word("first", 10, 12) + assert_lyric_lines_equal({ + "sentence": "first second", + "start_tick": 10, + "end_tick": 20, + }, line) + assert_lyric_words_equal({"word": "first", "start_tick": 10, "end_tick": 12}, line[0]) + assert_lyric_words_equal({"word": " ", "start_tick": 13, "end_tick": 15}, line[1]) + assert_lyric_words_equal({"word": "second", "start_tick": 15, "end_tick": 20}, line[2]) + + def test_get_word_at_index(self): + lyrics = create_lyrics() + line = lyrics.create_line_from_string("first second", 10, 20) + assert_lyric_lines_equal({ + "sentence": "first second", + "start_tick": 10, + "end_tick": 20, + }, line) + assert_lyric_words_equal({"word": "first", "start_tick": 10, "end_tick": 13}, line[0]) + assert_lyric_words_equal({"word": " ", "start_tick": 13, "end_tick": 16}, line[1]) + assert_lyric_words_equal({"word": "second", "start_tick": 16, "end_tick": 20}, line[2]) + assert_lyric_words_equal({"word": "first", "start_tick": 10, "end_tick": 13}, line.get_word_at_index(0)) + assert_lyric_words_equal({"word": " ", "start_tick": 13, "end_tick": 16}, line.get_word_at_index(1)) + assert_lyric_words_equal({"word": "second", "start_tick": 16, "end_tick": 20}, line.get_word_at_index(2)) + + def test_get_index_of_word_at_tick(self): + lyrics = create_lyrics() + line = lyrics.create_line_from_string("testing get word", 10, 15) + assert_lyric_lines_equal({ + "sentence": "testing get word", + "start_tick": 10, + "end_tick": 15, + }, line) + self.assertEqual(line.get_index_of_word_at_tick(10), 0) + self.assertEqual(line.get_index_of_word_at_tick(11), 1) + self.assertEqual(line.get_index_of_word_at_tick(12), 2) + self.assertEqual(line.get_index_of_word_at_tick(13), 3) + self.assertEqual(line.get_index_of_word_at_tick(14), 4) + + def test_clear(self): + lyrics = create_lyrics() + lyrics.create_line(10) + self.assertEqual(len(lyrics), 6) + lyrics.clear() + self.assertEqual(len(lyrics), 0) + + +class TestLyricLine(unittest.TestCase): + def test_create_word(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + self.assertEqual(len(line), 0) + line.create_word("first", 15, 20) + line.create_word("second", 30, 50) + line.create_word(" ", 28, 29) + self.assertEqual(len(line), 3) + assert_lyric_words_equal({"word": "first", "start_tick": 15, "end_tick": 20}, line[0]) + assert_lyric_words_equal({"word": " ", "start_tick": 28, "end_tick": 29}, line[1]) + assert_lyric_words_equal({"word": "second", "start_tick": 30, "end_tick": 50}, line[2]) + assert_lyric_lines_equal({ + "sentence": "first second", + "start_tick": 15, + "end_tick": 50, + }, line) + + def test_clear(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + line.create_word("first", 15, 20) + line.create_word("second", 30, 50) + line.clear() + self.assertEqual(len(line), 0) + self.assertEqual(line.is_empty(), True) + + def test_get_index_of_line_at_tick(self): + lyrics = create_lyrics() + lyrics.create_line(10) + lyrics.create_line(20) + index_generator = lyrics.get_index_of_line_at_tick(10) + self.assertEqual(next(index_generator), 1) + self.assertEqual(next(index_generator), 0) + + def test_remove_word_at_index(self): + lyrics = create_lyrics() + line = lyrics.create_line(9) + line.create_word("test", 15, 20) + line.create_word("word", 20, 30) + # Replace the empty word + self.assertEqual(len(line), 2) + assert_lyric_words_equal({ + "word": "test", + "start_tick": 15, + "end_tick": 20, + }, line[0]) + assert_lyric_words_equal({ + "word": "word", + "start_tick": 20, + "end_tick": 30, + }, line[1]) + line.remove_word_at_index(0) + # There will be 1 placeholder left + self.assertEqual(len(line), 1) + assert_lyric_words_equal({ + "word": "word", + "start_tick": 20, + "end_tick": 30, + }, line[0]) + # Test changed order of lines + assert_lyric_lines_equal({ + "sentence": "word", + "start_tick": 20, + "end_tick": 30, + }, lyrics[1]) + + def test_remove_word(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + word = line.create_word("first", 15, 20) + line.create_word("second", 30, 50) + assert_lyric_words_equal({"word": "first", "start_tick": 15, "end_tick": 20}, line[0]) + line.remove_word(word) + assert_lyric_words_equal({"word": "second", "start_tick": 30, "end_tick": 50}, line[0]) + assert_lyric_lines_equal({ + "sentence": "second", + "start_tick": 30, + "end_tick": 50, + }, lyrics[1]) + self.assertEqual(len(line), 1) + + +class TestLyricWord(unittest.TestCase): + def test_set_word(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + word = line[0] + word = LyricWord(line, "test", 10, 20, word) + word.set_word("changed") + self.assertEqual(word.get_word(), "changed") + + def test_set_start_tick(self): + lyrics = create_lyrics() + line = lyrics.create_line(10) + word = line.create_word("test", 15, 20) + line.create_word("tick", 30, 50) + assert_lyric_lines_equal({ + "sentence": "testtick", + "start_tick": 15, + "end_tick": 50, + }, lyrics[1]) + word.set_start_tick(5) + self.assertEqual(word.get_start_tick(), 5) + self.assertEqual(line.get_start_tick(), 5) + # Test if lines are sorted + assert_lyric_lines_equal({ + "sentence": "testtick", + "start_tick": 5, + "end_tick": 50, + }, lyrics[0]) + # Test removing the updated word + lyrics[0].remove_word(word)
I meant setting a start tick or end tick that could delete the word, for example here if you set start tick to be >= end tick we should delete the word from the line. This is not tested currently.
tuneflow-py
github_2023
python
2
tuneflow
andantei
@@ -0,0 +1,29 @@ +from __future__ import annotations +from tuneflow_py.models.protos import song_pb2 + +StructureType = song_pb2.StructureType
`StructureType = song_pb2.StructureMarker.StructureType`
tuneflow-py
github_2023
python
2
tuneflow
andantei
@@ -244,7 +244,7 @@ serialized_end=2705, ) _sym_db.RegisterEnumDescriptor(_STRUCTUREMARKER_STRUCTURETYPE) - +StructureType = enum_type_wrapper.EnumTypeWrapper(_STRUCTUREMARKER_STRUCTURETYPE)
This is an auto-generated file, which will be overwritten every time the proto recompiles. We should not manually edit this file.
tuneflow-py
github_2023
python
2
tuneflow
andantei
@@ -83,6 +84,95 @@ def remove_track(self, track_id: str): dep_track.remove_output() return track + def get_structures(self): + return self._proto.structures + + def get_structure_at_index(self, index: int): + return self._proto.structures[index] + + def get_structure_at_tick(self, tick: int): + def tickToStructureFn(tick): + return StructureMarker(song=self,tick=tick, type=StructureType.UNKNOWN)._proto + + def structureToTickFn(structure): + return structure.tick + + index = Song.get_structure_at_tick_impl( + tick, self._proto.structures, tickToStructureFn, structureToTickFn + ) + + if index < 0: + index = 0 + + if index >= len(self._proto.structures): + index = len(self._proto.structures) - 1 + + return self._proto.structures[index] + + @staticmethod + def get_structure_at_tick_impl(
You can combine this function and `get_structure_at_tick` into one method, since there is only one usage. The TS version has separate methods because the impl method was used elsewhere.
tuneflow-py
github_2023
python
2
tuneflow
andantei
@@ -83,6 +84,95 @@ def remove_track(self, track_id: str): dep_track.remove_output() return track + def get_structures(self): + return self._proto.structures
You probably want to wrap the protos with StructureMarker class: ``` for structure_proto in self._proto.structures: yield StructureMarker(proto=structure_proto) ```
tuneflow-py
github_2023
python
2
tuneflow
andantei
@@ -83,6 +84,95 @@ def remove_track(self, track_id: str): dep_track.remove_output() return track + def get_structures(self): + return self._proto.structures + + def get_structure_at_index(self, index: int): + return self._proto.structures[index]
Same here, you probably want to wrap it in `StructureMarker`
tuneflow-py
github_2023
python
2
tuneflow
andantei
@@ -83,6 +84,95 @@ def remove_track(self, track_id: str): dep_track.remove_output() return track + def get_structures(self): + return self._proto.structures + + def get_structure_at_index(self, index: int): + return self._proto.structures[index] + + def get_structure_at_tick(self, tick: int): + def tickToStructureFn(tick): + return StructureMarker(song=self,tick=tick, type=StructureType.UNKNOWN)._proto + + def structureToTickFn(structure): + return structure.tick + + index = Song.get_structure_at_tick_impl( + tick, self._proto.structures, tickToStructureFn, structureToTickFn + ) + + if index < 0: + index = 0 + + if index >= len(self._proto.structures): + index = len(self._proto.structures) - 1 + + return self._proto.structures[index] + + @staticmethod + def get_structure_at_tick_impl( + tick: int, + structures: List, + tickToStructureFn, + structureToTickFn, + ): + index = lower_equal( + structures, + tickToStructureFn(tick), + key=lambda s: structureToTickFn(s), + ) + + if index < 0: + index = 0 + + if index >= len(structures): + index = len(structures) - 1 + + return index + + def create_structure(self, tick: int, type: StructureType): + structure = StructureMarker(song=self,tick=tick,type=type)
Please format the files before submitting (preferred formatter autopep8)
tuneflow-py
github_2023
python
2
tuneflow
andantei
@@ -83,6 +84,95 @@ def remove_track(self, track_id: str): dep_track.remove_output() return track + def get_structures(self): + return self._proto.structures + + def get_structure_at_index(self, index: int): + return self._proto.structures[index] + + def get_structure_at_tick(self, tick: int): + def tickToStructureFn(tick): + return StructureMarker(song=self,tick=tick, type=StructureType.UNKNOWN)._proto + + def structureToTickFn(structure): + return structure.tick + + index = Song.get_structure_at_tick_impl( + tick, self._proto.structures, tickToStructureFn, structureToTickFn + ) + + if index < 0: + index = 0 + + if index >= len(self._proto.structures): + index = len(self._proto.structures) - 1 + + return self._proto.structures[index] + + @staticmethod + def get_structure_at_tick_impl( + tick: int, + structures: List, + tickToStructureFn, + structureToTickFn, + ): + index = lower_equal( + structures, + tickToStructureFn(tick), + key=lambda s: structureToTickFn(s), + ) + + if index < 0: + index = 0 + + if index >= len(structures): + index = len(structures) - 1 + + return index + + def create_structure(self, tick: int, type: StructureType): + structure = StructureMarker(song=self,tick=tick,type=type) + if len(self._proto.structures) == 1: + # If there is only 1 structure, move it to the start. + structure.set_tick(0) + self._proto.structures.append(structure._proto)
Proto's append/insert/... methods creates a copy of your original proto instance, so you need to update your input wrapper's `_proto` to the newly inserted proto if you want to use your wrapper instance later. ``` self._proto.structures.append(structure._proto) structure._proto = self._proto.structures[-1] ``` https://protobuf.dev/reference/python/python-generated/#repeated-message-fields
tuneflow-py
github_2023
python
2
tuneflow
andantei
@@ -83,6 +84,95 @@ def remove_track(self, track_id: str): dep_track.remove_output() return track + def get_structures(self): + return self._proto.structures + + def get_structure_at_index(self, index: int): + return self._proto.structures[index] + + def get_structure_at_tick(self, tick: int): + def tickToStructureFn(tick): + return StructureMarker(song=self,tick=tick, type=StructureType.UNKNOWN)._proto + + def structureToTickFn(structure): + return structure.tick + + index = Song.get_structure_at_tick_impl( + tick, self._proto.structures, tickToStructureFn, structureToTickFn + ) + + if index < 0: + index = 0 + + if index >= len(self._proto.structures): + index = len(self._proto.structures) - 1 + + return self._proto.structures[index] + + @staticmethod + def get_structure_at_tick_impl( + tick: int, + structures: List, + tickToStructureFn, + structureToTickFn, + ): + index = lower_equal( + structures, + tickToStructureFn(tick), + key=lambda s: structureToTickFn(s), + ) + + if index < 0: + index = 0 + + if index >= len(structures): + index = len(structures) - 1 + + return index + + def create_structure(self, tick: int, type: StructureType): + structure = StructureMarker(song=self,tick=tick,type=type) + if len(self._proto.structures) == 1: + # If there is only 1 structure, move it to the start. + structure.set_tick(0) + self._proto.structures.append(structure._proto) + self._proto.structures.sort(key=lambda x: x.tick) + + def move_structure(self, structureIndex: int, moveToTick: int): + structure = self.get_structures()[structureIndex]
get_structure_at_index
tuneflow-py
github_2023
python
2
tuneflow
andantei
@@ -83,6 +84,95 @@ def remove_track(self, track_id: str): dep_track.remove_output() return track + def get_structures(self): + return self._proto.structures + + def get_structure_at_index(self, index: int): + return self._proto.structures[index] + + def get_structure_at_tick(self, tick: int): + def tickToStructureFn(tick): + return StructureMarker(song=self,tick=tick, type=StructureType.UNKNOWN)._proto + + def structureToTickFn(structure): + return structure.tick + + index = Song.get_structure_at_tick_impl( + tick, self._proto.structures, tickToStructureFn, structureToTickFn + ) + + if index < 0: + index = 0 + + if index >= len(self._proto.structures): + index = len(self._proto.structures) - 1 + + return self._proto.structures[index] + + @staticmethod + def get_structure_at_tick_impl( + tick: int, + structures: List, + tickToStructureFn, + structureToTickFn, + ): + index = lower_equal( + structures, + tickToStructureFn(tick), + key=lambda s: structureToTickFn(s), + ) + + if index < 0: + index = 0 + + if index >= len(structures): + index = len(structures) - 1 + + return index + + def create_structure(self, tick: int, type: StructureType): + structure = StructureMarker(song=self,tick=tick,type=type) + if len(self._proto.structures) == 1: + # If there is only 1 structure, move it to the start. + structure.set_tick(0) + self._proto.structures.append(structure._proto) + self._proto.structures.sort(key=lambda x: x.tick) + + def move_structure(self, structureIndex: int, moveToTick: int): + structure = self.get_structures()[structureIndex] + if not structure: + return + if structureIndex <= 0: + return + prevStructure = self.get_structures()[structureIndex - 1]
get_structure_at_index
tuneflow-py
github_2023
python
2
tuneflow
andantei
@@ -83,6 +84,95 @@ def remove_track(self, track_id: str): dep_track.remove_output() return track + def get_structures(self): + return self._proto.structures + + def get_structure_at_index(self, index: int): + return self._proto.structures[index] + + def get_structure_at_tick(self, tick: int): + def tickToStructureFn(tick): + return StructureMarker(song=self,tick=tick, type=StructureType.UNKNOWN)._proto + + def structureToTickFn(structure): + return structure.tick + + index = Song.get_structure_at_tick_impl( + tick, self._proto.structures, tickToStructureFn, structureToTickFn + ) + + if index < 0: + index = 0 + + if index >= len(self._proto.structures): + index = len(self._proto.structures) - 1 + + return self._proto.structures[index] + + @staticmethod + def get_structure_at_tick_impl( + tick: int, + structures: List, + tickToStructureFn, + structureToTickFn, + ): + index = lower_equal( + structures, + tickToStructureFn(tick), + key=lambda s: structureToTickFn(s), + ) + + if index < 0: + index = 0 + + if index >= len(structures): + index = len(structures) - 1 + + return index + + def create_structure(self, tick: int, type: StructureType): + structure = StructureMarker(song=self,tick=tick,type=type) + if len(self._proto.structures) == 1: + # If there is only 1 structure, move it to the start. + structure.set_tick(0) + self._proto.structures.append(structure._proto) + self._proto.structures.sort(key=lambda x: x.tick) + + def move_structure(self, structureIndex: int, moveToTick: int):
Use snake_case, here: structure_index and move_to_tick, same below
tuneflow-py
github_2023
python
2
tuneflow
andantei
@@ -83,6 +84,95 @@ def remove_track(self, track_id: str): dep_track.remove_output() return track + def get_structures(self): + return self._proto.structures + + def get_structure_at_index(self, index: int): + return self._proto.structures[index] + + def get_structure_at_tick(self, tick: int): + def tickToStructureFn(tick): + return StructureMarker(song=self,tick=tick, type=StructureType.UNKNOWN)._proto + + def structureToTickFn(structure): + return structure.tick + + index = Song.get_structure_at_tick_impl( + tick, self._proto.structures, tickToStructureFn, structureToTickFn + ) + + if index < 0: + index = 0 + + if index >= len(self._proto.structures): + index = len(self._proto.structures) - 1 + + return self._proto.structures[index] + + @staticmethod + def get_structure_at_tick_impl( + tick: int, + structures: List, + tickToStructureFn, + structureToTickFn, + ): + index = lower_equal( + structures, + tickToStructureFn(tick), + key=lambda s: structureToTickFn(s), + ) + + if index < 0: + index = 0 + + if index >= len(structures): + index = len(structures) - 1 + + return index + + def create_structure(self, tick: int, type: StructureType): + structure = StructureMarker(song=self,tick=tick,type=type) + if len(self._proto.structures) == 1: + # If there is only 1 structure, move it to the start. + structure.set_tick(0) + self._proto.structures.append(structure._proto) + self._proto.structures.sort(key=lambda x: x.tick) + + def move_structure(self, structureIndex: int, moveToTick: int): + structure = self.get_structures()[structureIndex] + if not structure: + return + if structureIndex <= 0: + return + prevStructure = self.get_structures()[structureIndex - 1] + if prevStructure.tick == moveToTick: + # Moved to another structure, delete it. + self.remove_structure(structureIndex - 1) + elif structureIndex < len(self.get_structures()) - 1: + nextStructure = self.get_structures()[structureIndex + 1] + if nextStructure and nextStructure.tick == moveToTick: + # Moved to another time signature, delete it. + self.remove_structure(structureIndex + 1) + structure.tick = moveToTick + self._proto.structures.sort(key=lambda x: x.tick) + + def update_structure_at_tick(self, tick: int, type: StructureType): + existinStructure = self.get_structure_at_tick(tick) + if existinStructure: + existinStructure.type = type + else: + self.create_structure(tick, type) + + def remove_structure(self, index: int): + if index < 0 or index >= len(self._proto.structures): + return + self.get_structures().pop(index)
self._proto.structures.pop(index)
tuneflow-py
github_2023
python
2
tuneflow
andantei
@@ -83,6 +85,89 @@ def remove_track(self, track_id: str): dep_track.remove_output() return track + def get_structures(self): + return [StructureMarker(song=self, proto=structure_proto) for structure_proto in self._proto.structures] + + def get_structure_at_index(self, index: int): + if index < 0: + index = 0 + + if index >= len(self._proto.structures): + index = len(self._proto.structures) - 1
The above two checks are probably error-prone, the user might provide an out of range index (e.g. 999) and still get some structure which can lead to potential errors. Note that this is different from get structure at tick since the index is more specific here.
tuneflow-py
github_2023
python
2
tuneflow
andantei
@@ -83,6 +85,89 @@ def remove_track(self, track_id: str): dep_track.remove_output() return track + def get_structures(self): + return [StructureMarker(song=self, proto=structure_proto) for structure_proto in self._proto.structures] + + def get_structure_at_index(self, index: int): + if index < 0: + index = 0 + + if index >= len(self._proto.structures): + index = len(self._proto.structures) - 1 + + if index == -1: + return None + + return StructureMarker(song=self, proto=self._proto.structures[index]) + + def get_structure_at_tick(self, tick: int): + def tick_to_structure_fn(tick): + return StructureMarker(song=self, tick=tick, type=StructureType.UNKNOWN) + + def structure_to_tick_fn(structure): + return structure.get_tick() + + index = lower_equal( + self.get_structures(), + tick_to_structure_fn(tick), + key=lambda s: structure_to_tick_fn(s), + ) + + if index < 0: + index = 0 + + if index >= len(self._proto.structures): + index = len(self._proto.structures) - 1 + + if index == -1: + return None + + return StructureMarker(song=self, proto=self._proto.structures[index]) + + def create_structure(self, tick: int, type: StructureType): + structure = StructureMarker(song=self, tick=tick, type=type) + self._proto.structures.append(structure._proto) + structure._proto = self._proto.structures[-1] + if len(self._proto.structures) == 1: + # If there is only 1 structure, move it to the start. + structure.set_tick(0) + self._proto.structures.sort(key=lambda x: x.tick) + + def move_structure(self, structure_index: int, move_to_tick: int): + structure = self.get_structure_at_index(structure_index) + if not structure:
For example here, if structure_index is set to 9999 and get_structure_at_index still returns the last structure, this if check would not be able catch that.
ai-pr-reviewer
github_2023
typescript
524
coderabbitai
github-actions[bot]
@@ -6,19 +6,30 @@ export class TokenLimits { constructor(model = 'gpt-3.5-turbo') { this.knowledgeCutOff = '2021-09-01' - if (model === 'gpt-4-32k') { - this.maxTokens = 32600 - this.responseTokens = 4000 - } else if (model === 'gpt-3.5-turbo-16k') { - this.maxTokens = 16300 - this.responseTokens = 3000 - } else if (model === 'gpt-4') { - this.maxTokens = 8000 - this.responseTokens = 2000 - } else { - this.maxTokens = 4000 - this.responseTokens = 1000 + switch (model) { + case 'gpt-4-32k': + this.maxTokens = 32600 + this.responseTokens = 4000 + break + case 'gpt-3.5-turbo-16k': + this.maxTokens = 16300 + this.responseTokens = 3000 + break + case 'gpt-4': + this.maxTokens = 8000 + this.responseTokens = 2000 + break + case 'gpt-4-turbo-preview': + this.maxTokens = 128000 + this.responseTokens = 4000 + this.knowledgeCutOff = '2023-12-01' + break + default: + this.maxTokens = 4000 + this.responseTokens = 1000 + break }
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit The switch-case structure is a good improvement over the previous if-else chain for readability and maintainability. However, there's no handling for when an unsupported model is passed to the constructor. This could lead to unexpected behavior if a user passes an unsupported model name. Consider throwing an error in the default case to alert the user that they've provided an unsupported model. ```diff default: this.maxTokens = 4000 this.responseTokens = 1000 + throw new Error(`Unsupported model: ${model}`); break ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->
ai-pr-reviewer
github_2023
others
524
coderabbitai
github-actions[bot]
@@ -136,6 +134,8 @@ inputs: !**/*.min.js.css !**/*.tfstate !**/*.tfstate.backup + !**/vault.yml + !**/vault.yaml
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit The exclusion of `vault.yml` and `vault.yaml` files might have security implications. If these files contain sensitive data like secrets or passwords, they should not be part of the repository in the first place. However, if they are necessary for the project, consider encrypting them or using a secure method to share these files. <!-- This is an auto-generated comment by OSS CodeRabbit -->
ai-pr-reviewer
github_2023
others
524
coderabbitai
github-actions[bot]
@@ -156,7 +156,7 @@ inputs: openai_heavy_model: required: false description: 'Model to use for complex tasks such as code reviews.' - default: 'gpt-4' + default: 'gpt-4-turbo-preview'
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit Switching from 'gpt-4' to 'gpt-4-turbo-preview' as the default model for complex tasks is a significant change. Ensure that this new model has been thoroughly tested and validated for all use cases it will encounter in this application. Also, make sure to update any relevant documentation to reflect this change. ```diff - default: 'gpt-4' + default: 'gpt-4-turbo-preview' ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->
ai-pr-reviewer
github_2023
others
524
coderabbitai
github-actions[bot]
@@ -212,9 +212,6 @@ inputs: specific files within 80 words. - **Changes**: A markdown table of files and their summaries. Group files with similar changes together into a single row to save space. - - **Poem**: Below the changes, include a whimsical, short poem written by - a rabbit to celebrate the changes. Format the poem as a quote using - the ">" symbol and feel free to use emojis where relevant. Avoid additional commentary as this summary will be added as a comment on the GitHub pull request. Use the titles "Walkthrough" and "Changes" and they must be H2.
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit Removing the "Poem" section simplifies the PR template and makes it more focused on the code changes. This is a good move for clarity and professionalism. However, ensure that all contributors are aware of this change so they can adjust their PR submissions accordingly. ```diff - - **Poem**: Below the changes, include a whimsical, short poem written by - a rabbit to celebrate the changes. Format the poem as a quote using - the ">" symbol and feel free to use emojis where relevant. + (No equivalent lines in the new hunk) ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->
ai-pr-reviewer
github_2023
others
521
coderabbitai
github-actions[bot]
@@ -28,9 +28,11 @@ "@actions/core": "^1.10.0", "@actions/github": "^5.1.1", "@dqbd/tiktoken": "^1.0.7", + "@langchain/openai": "^0.0.14", "@octokit/action": "^6.0.4",
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit The new dependencies `@langchain/openai` and `langchain` have been added. Please ensure that these packages are reliable, well-maintained, and do not introduce any security vulnerabilities. It's also important to check if their licenses are compatible with the project. ```diff + "@langchain/openai": "^0.0.14", + "langchain": "^0.1.17", ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->
ai-pr-reviewer
github_2023
typescript
521
coderabbitai
github-actions[bot]
@@ -10,14 +10,9 @@ import { } from 'chatgpt' import pRetry from 'p-retry' import {OpenAIOptions, Options} from './options' +import {BotProtocol, Ids} from './bot-interface' -// define type to save parentMessageId and conversationId -export interface Ids { - parentMessageId?: string - conversationId?: string -} - -export class Bot { +export class Bot implements BotProtocol {
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit The changes made here are good. The `BotProtocol` and `Ids` interfaces have been moved to a separate file, which improves the modularity of the code. Now, the `Bot` class implements the `BotProtocol` interface, which is a good practice as it ensures that any class implementing this interface will have certain methods and properties. This makes the code more maintainable and easier to understand. ```diff - // define type to save parentMessageId and conversationId - export interface Ids { - parentMessageId?: string - conversationId?: string - } - - export class Bot { + import {BotProtocol, Ids} from './bot-interface' + + export class Bot implements BotProtocol { private readonly api: ChatGPTAPI | null = null // not free private readonly options: Options ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->