├── Rakefile ├── lib ├── tx_translate │ ├── version.rb │ ├── md_process.rb │ ├── sbv_process.rb │ ├── parallel_array.rb │ ├── srt_process.rb │ ├── helper │ │ └── config_helper.rb │ ├── cli.rb │ └── tencent_fy.rb └── tx_translate.rb ├── templates └── settings.yml.tt ├── exe └── tx_translate ├── .gitignore ├── Gemfile ├── Gemfile.lock ├── LICENSE.txt ├── tx_translate.gemspec ├── README.md └── CODE_OF_CONDUCT.md /Rakefile: -------------------------------------------------------------------------------- 1 | require 'bundler/gem_tasks' 2 | task default: :spec 3 | -------------------------------------------------------------------------------- /lib/tx_translate/version.rb: -------------------------------------------------------------------------------- 1 | module TxTranslate 2 | VERSION = '0.0.6'.freeze 3 | end 4 | -------------------------------------------------------------------------------- /templates/settings.yml.tt: -------------------------------------------------------------------------------- 1 | --- 2 | :secret_key: "" 3 | :secret_id: "" 4 | :region: "ap-beijing" 5 | :process_amount: 5 6 | -------------------------------------------------------------------------------- /exe/tx_translate: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require 'bundler/setup' 4 | require 'tx_translate/cli' 5 | 6 | TxTranslate::CLI.start 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle/ 2 | /.yardoc 3 | /_yardoc/ 4 | /coverage/ 5 | /doc/ 6 | /pkg/ 7 | /spec/reports/ 8 | /tmp/ 9 | *.sbv 10 | *.srt 11 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'http://rubygems.org' 2 | 3 | git_source(:github) { |repo_name| "https://github.com/#{repo_name}" } 4 | 5 | # Specify your gem's dependencies in tx_translate.gemspec 6 | gemspec 7 | -------------------------------------------------------------------------------- /lib/tx_translate.rb: -------------------------------------------------------------------------------- 1 | require 'tx_translate/version' 2 | require 'tx_translate/cli' 3 | require 'tx_translate/tencent_fy' 4 | require 'tx_translate/parallel_array' 5 | require 'tx_translate/sbv_process' 6 | require 'tx_translate/md_process' 7 | require 'tx_translate/srt_process' 8 | require 'tx_translate/helper/config_helper' 9 | 10 | module TxTranslate 11 | # Your code goes here... 12 | end 13 | -------------------------------------------------------------------------------- /lib/tx_translate/md_process.rb: -------------------------------------------------------------------------------- 1 | module TxTranslate 2 | class MdProcess 3 | include Singleton 4 | 5 | def self.run(filename) 6 | file = File.open(filename, "r") 7 | basename = File.basename(filename, "md") 8 | contents = file.read 9 | new_contents = "" 10 | 11 | 12 | old_content_array = contents.split("\n\n") 13 | 14 | 15 | new_content_array = ParallelArray.new(old_content_array).parallel_process 16 | 17 | old_content_array.each_with_index do |item,i| 18 | new_contents += old_content_array[i] + "\n\n" + new_content_array[i] + "\n\n" 19 | end 20 | 21 | file = File.open("#{basename}zh-si.md", "w") { |f| f.write(new_contents) } 22 | end 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | PATH 2 | remote: . 3 | specs: 4 | tx_translate (0.0.6) 5 | activesupport 6 | httparty 7 | json 8 | thor 9 | typhoeus 10 | 11 | GEM 12 | remote: http://rubygems.org/ 13 | specs: 14 | activesupport (5.2.2) 15 | concurrent-ruby (~> 1.0, >= 1.0.2) 16 | i18n (>= 0.7, < 2) 17 | minitest (~> 5.1) 18 | tzinfo (~> 1.1) 19 | concurrent-ruby (1.1.5) 20 | ethon (0.12.0) 21 | ffi (>= 1.3.0) 22 | ffi (1.10.0) 23 | httparty (0.16.4) 24 | mime-types (~> 3.0) 25 | multi_xml (>= 0.5.2) 26 | i18n (1.1.1) 27 | concurrent-ruby (~> 1.0) 28 | json (2.3.1) 29 | mime-types (3.2.2) 30 | mime-types-data (~> 3.2015) 31 | mime-types-data (3.2018.0812) 32 | minitest (5.11.3) 33 | multi_xml (0.6.0) 34 | rake (13.0.1) 35 | thor (0.20.3) 36 | thread_safe (0.3.6) 37 | typhoeus (1.3.1) 38 | ethon (>= 0.9.0) 39 | tzinfo (1.2.5) 40 | thread_safe (~> 0.1) 41 | 42 | PLATFORMS 43 | ruby 44 | 45 | DEPENDENCIES 46 | bundler (~> 1.16) 47 | rake (~> 13.0) 48 | tx_translate! 49 | 50 | BUNDLED WITH 51 | 1.17.3 52 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 xdite 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /lib/tx_translate/sbv_process.rb: -------------------------------------------------------------------------------- 1 | module TxTranslate 2 | class SbvProcess 3 | include Singleton 4 | 5 | def self.run(filename) 6 | file = File.open(filename, 'r') 7 | basename = File.basename(filename, "sbv") 8 | contents = file.read + "\n\n" 9 | contents.gsub!("\r\n", "\n") # 处理 CRLF 转 LF 问题 10 | 11 | subbed = '' 12 | 13 | original_content_array = [] 14 | timeline_content_array = [] 15 | context_content_array = [] 16 | 17 | # 先切段 18 | contents.gsub(/(\d:\d{2}:\d{2}.\d{3}),(\d:\d{2}:\d{2}\.\d{3})\n((?:^.*$\n)*?)\n/).with_index do |m, i| 19 | original_content_array[i] = m # 旧内容 20 | 21 | timeline_content_array[i] = "#{Regexp.last_match(1)},#{Regexp.last_match(2)}" 22 | context_content_array[i] = Regexp.last_match(3).to_s 23 | end 24 | 25 | context_content_array = TxTranslate::ParallelArray.new(context_content_array).parallel_process 26 | 27 | original_content_array.each_with_index do |_item, i| 28 | subbed += timeline_content_array[i] + "\n" + context_content_array[i] + "\n\n" 29 | end 30 | 31 | file = File.open("#{basename}zh-si.sbv", 'w') { |f| f.write(subbed) } 32 | end 33 | 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /lib/tx_translate/parallel_array.rb: -------------------------------------------------------------------------------- 1 | require 'json' 2 | require 'typhoeus' 3 | require 'cgi' 4 | 5 | module TxTranslate 6 | class ParallelArray 7 | 8 | 9 | def process_amount 10 | TxTranslate.config[:process_amount] || 5 11 | end 12 | 13 | # 平行处理 14 | def initialize(array) 15 | @content_array = array 16 | @result_array = [] 17 | @hydra = Typhoeus::Hydra.new 18 | end 19 | 20 | def parallel_process 21 | 22 | @content_array.each_with_index do |item, i| 23 | text = '' 24 | request = Typhoeus::Request.new(TxTranslate::TencentFy.new(item).full_request_url.to_s, followlocation: true) 25 | 26 | request.on_complete do |response| 27 | json = JSON.parse(response.body) 28 | 29 | text = if json['Response']['Error'] 30 | TxTranslate::TencentFy.new(item).full_request_url 31 | else 32 | json['Response']['TargetText'] 33 | end 34 | puts text 35 | @result_array[i] = text 36 | end 37 | 38 | @hydra.queue(request) 39 | sleep(1.0/process_amount) 40 | @hydra.run 41 | end 42 | 43 | @result_array 44 | end 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /lib/tx_translate/srt_process.rb: -------------------------------------------------------------------------------- 1 | module TxTranslate 2 | class SrtProcess 3 | include Singleton 4 | 5 | def self.run(filename) 6 | file = File.open(filename, 'r') 7 | basename = File.basename(filename, "srt") 8 | 9 | contents = file.read + "\n\n" 10 | contents.gsub!("\r\n", "\n") # 处理 CRLF 转 LF 问题 11 | 12 | 13 | subbed = '' 14 | 15 | original_content_array = [] 16 | timeline_content_array = [] 17 | context_content_array = [] 18 | 19 | # 先切段 20 | contents.gsub(/(.+)\n(\d{2}:\d{2}:\d{2},\d{3} --> \d{2}:\d{2}:\d{2},\d{3})\n((?:^.*$\n)*?)\n/).with_index do |m, i| 21 | original_content_array[i] = m # 旧内容 22 | 23 | timeline_content_array[i] = "#{Regexp.last_match(2)}" 24 | context_content_array[i] = Regexp.last_match(3).to_s 25 | end 26 | 27 | puts original_content_array.size 28 | 29 | context_content_array = TxTranslate::ParallelArray.new(context_content_array).parallel_process 30 | 31 | original_content_array.each_with_index do |_item, i| 32 | subbed += "#{i}\n" + timeline_content_array[i] + "\n" + context_content_array[i] + "\n\n" 33 | end 34 | 35 | file = File.open("#{basename}zh-si.srt", 'w') { |f| f.write(subbed) } 36 | end 37 | 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /lib/tx_translate/helper/config_helper.rb: -------------------------------------------------------------------------------- 1 | require 'fileutils' 2 | require 'yaml' 3 | require 'psych' 4 | 5 | module TxTranslate 6 | # Configuration defaults 7 | @config = { 8 | name: 'default' 9 | } 10 | @valid_config_keys = @config.keys 11 | 12 | # Configure through hash 13 | def self.configure(opts = {}) 14 | config 15 | opts.each do |k, v| 16 | @config[k.to_sym] = v if @valid_config_keys.include? k.to_sym 17 | end 18 | save_config 19 | end 20 | 21 | def self.get_config_path 22 | config_path = Dir.home + '/.tx_translate' 23 | if Dir.exist?(config_path) 24 | # use user settings 25 | config_path 26 | else 27 | raise "Can't find config directory. please init by command: 'mygem config'.'" 28 | end 29 | end 30 | 31 | # configをyamlから@cofigに取得 32 | def self.config 33 | yml_path = get_config_path + '/settings.yml' 34 | yml_file = YAML.load_file(yml_path) 35 | if yml_file 36 | @config = yml_file 37 | else 38 | File.open(yml_path, 'w') { |f| YAML.dump(@config, f) } 39 | end 40 | end 41 | 42 | # 現在の@configをyamlに保存 43 | def self.save_config 44 | yml_path = get_config_path + '/settings.yml' 45 | if File.exist?(yml_path) 46 | File.open(yml_path, 'w') { |f| YAML.dump(@config, f) } 47 | else 48 | raise "Can't find #{yml_path}. please set configure." 49 | end 50 | end 51 | end 52 | -------------------------------------------------------------------------------- /tx_translate.gemspec: -------------------------------------------------------------------------------- 1 | lib = File.expand_path('lib', __dir__) 2 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) 3 | require 'tx_translate/version' 4 | 5 | Gem::Specification.new do |spec| 6 | spec.name = 'tx_translate' 7 | spec.version = TxTranslate::VERSION 8 | spec.authors = ['xdite'] 9 | spec.email = ['xdite@otcbtc.com'] 10 | 11 | spec.summary = 'Quick Gitbook Generator ' 12 | spec.description = 'Quick Gitbook Generator ' 13 | spec.homepage = 'https://github.com/xdite/tx_translate' 14 | spec.license = 'MIT' 15 | spec.executables << 'tx_translate' 16 | 17 | # Specify which files should be added to the gem when it is released. 18 | # The `git ls-files -z` loads the files in the RubyGem that have been added into git. 19 | spec.files = Dir.chdir(File.expand_path(__dir__)) do 20 | `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } 21 | end 22 | spec.bindir = 'exe' 23 | spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } 24 | spec.require_paths = ['lib'] 25 | 26 | spec.add_development_dependency 'bundler', '~> 1.16' 27 | spec.add_development_dependency 'rake', '~> 13.0' 28 | spec.add_dependency 'activesupport' 29 | spec.add_dependency 'httparty' 30 | spec.add_dependency 'json' 31 | spec.add_dependency 'thor' 32 | spec.add_dependency 'typhoeus' 33 | end 34 | -------------------------------------------------------------------------------- /lib/tx_translate/cli.rb: -------------------------------------------------------------------------------- 1 | require 'thor' 2 | require 'active_support/core_ext/string' 3 | require 'tx_translate' 4 | 5 | module TxTranslate 6 | class CLI < Thor 7 | include Thor::Actions 8 | 9 | def self.source_root 10 | File.expand_path('../..', __dir__) 11 | end 12 | 13 | desc 'config', 'change settings' 14 | def config 15 | # 初回起動時に設定ファイルを作成 16 | config_path = Dir.home + '/.tx_translate' 17 | if Dir.exist?(config_path) 18 | puts "Your current name is [#{TxTranslate.config[:name]}]." 19 | else 20 | template 'templates/settings.yml.tt', "#{config_path}/settings.yml" 21 | end 22 | end 23 | 24 | desc 'word STRING', '翻译句子' 25 | def word(word, _number = 10) 26 | if ARGV.length < 2 27 | puts TxTranslate::TencentFy.new(word).result 28 | else 29 | ARGV.delete_at(0) 30 | str = ARGV.join(' ') 31 | puts TxTranslate::TencentFy.new(str).result 32 | end 33 | end 34 | 35 | desc 'sbv FILENAME', '翻译 sbv 档' 36 | def sbv(filename) 37 | TxTranslate::SbvProcess.run(filename) 38 | end 39 | 40 | desc 'srt FILENAME', '翻译 srt 档' 41 | def srt(filename) 42 | TxTranslate::SrtProcess.run(filename) 43 | end 44 | 45 | desc 'md FILENAME', '翻译 markdown 档' 46 | def md(filename) 47 | TxTranslate::MdProcess.run(filename) 48 | end 49 | 50 | private 51 | 52 | def display_name(name) 53 | puts name 54 | end 55 | end 56 | end 57 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TxTranslate 腾讯翻译 2 | 3 | 这是一个可以调用腾讯 API 的命令列工具 4 | 5 | ## Installation 6 | 7 | Add this line to your application's Gemfile: 8 | 9 | ```ruby 10 | gem 'tx_translate' 11 | ``` 12 | 13 | ## Setting 产生设定 14 | 15 | `tx_translate config` 16 | 17 | * 这个命列会产生 ~/.tx_translate/settings.yml 18 | * 密钥至 申请 19 | 20 | ``` 21 | --- 22 | :secret_key: "" 23 | :secret_id: "" 24 | :region: "ap-beijing" 25 | 26 | ``` 27 | 28 | 29 | ## Usage 使用方式 30 | 31 | * tx_translate word "This is a book" # 翻译一句话 32 | * tx_translate sbv FILENAME # 翻译字幕 33 | * tx_translate srt FILENAME # 翻译字幕 34 | * tx_translate md FILENAME # 翻译中英对照文档 35 | 36 | 37 | ## Other 其他说明 38 | 39 | 这个软件目前为自用,所以写得很简陋。有问题请自行修复,并拉 pull request。 40 | 41 | ## Development 42 | 43 | After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment. 44 | 45 | To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). 46 | 47 | ## Contributing 48 | 49 | Bug reports and pull requests are welcome on GitHub at https://github.com/xdite/tx_translate. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct. 50 | 51 | ## License 52 | 53 | The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). 54 | 55 | ## Code of Conduct 56 | 57 | Everyone interacting in the TxTranslate project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/tx_translate/blob/master/CODE_OF_CONDUCT.md). 58 | -------------------------------------------------------------------------------- /lib/tx_translate/tencent_fy.rb: -------------------------------------------------------------------------------- 1 | require 'httparty' 2 | require 'json' 3 | require 'typhoeus' 4 | require 'cgi' 5 | 6 | module TxTranslate 7 | class TencentFy 8 | def initialize(text) 9 | @encode_text = text.tr("\n", ' ') 10 | @escape_text = CGI.escape(@encode_text) 11 | end 12 | 13 | def region 14 | TxTranslate.config[:region] 15 | end 16 | 17 | def host 18 | "tmt.tencentcloudapi.com" 19 | end 20 | 21 | def url 22 | "https://#{host}" 23 | end 24 | 25 | def nonce 26 | rand(2323) 27 | end 28 | 29 | def secret_id 30 | TxTranslate.config[:secret_id] 31 | end 32 | 33 | def secret_key 34 | TxTranslate.config[:secret_key] 35 | end 36 | 37 | def orginal_parameters 38 | 'Action=TextTranslate' + '&Nonce=1234' + '&ProjectId=1257710951' + "&Region=#{region}" \ 39 | "&SecretId=#{secret_id}" + '&Source=en' + '&SourceText=' + 40 | @encode_text + '&Target=zh' + '&Timestamp=' + timestamp + '&Version=2018-03-21' 41 | end 42 | 43 | def encode_parameters 44 | 'Action=TextTranslate' + '&Nonce=1234' + '&ProjectId=1257710951' + "&Region=#{region}" \ 45 | "&SecretId=#{secret_id}" + '&Source=en' + '&SourceText=' + 46 | @escape_text + '&Target=zh' + '&Timestamp=' + timestamp + '&Version=2018-03-21' 47 | end 48 | 49 | def timestamp 50 | timestamp = Time.now.to_i.to_s 51 | end 52 | 53 | def sign_str 54 | "GET#{host}/?" 55 | end 56 | 57 | def data 58 | sign_str + orginal_parameters 59 | end 60 | 61 | def code 62 | digest = OpenSSL::Digest.new('sha1') 63 | hmac = OpenSSL::HMAC.digest(digest, secret_key, data) 64 | encrypt = Base64.encode64(hmac).delete("\n") 65 | encrypt.gsub('+', '%2B') # 处理 + 号 66 | end 67 | 68 | def request_params 69 | "/?#{encode_parameters}&Signature=#{code}" 70 | end 71 | 72 | def full_request_url 73 | url + request_params 74 | end 75 | 76 | def request_object 77 | HTTParty.get(url + request_params) 78 | end 79 | 80 | def json 81 | JSON.parse(request_object.body) 82 | end 83 | 84 | def result 85 | if json['Response']['Error'] 86 | json 87 | else 88 | json['Response']['TargetText'] 89 | end 90 | end 91 | end 92 | end 93 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at xdite@otcbtc.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | --------------------------------------------------------------------------------