zip_geo_jp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5c0cf6a7e4040b5b4a9de002da9c20698cb393d9150de4b7c0f6d89e147b4ecf
4
+ data.tar.gz: 35560c128241a19d896e96d2451ab46b943d314e3d866f4bec30c19a27e45af5
5
+ SHA512:
6
+ metadata.gz: 3dd9d53bdb6e23bb268136d016168184f84b00323e4f7cfa80d79f45246cdfe29ccc83ff94136c86a4fd407476c2fed79ee79ff564127565f7ddbe7ba07ca2c5
7
+ data.tar.gz: 9042dfa85b1ac8012b207b89ecea0627bd409f3b3a566b92d61f31365bbb39c6e577716c39558fce9b12350aa5153dd11f59b34e04ad28bc2b6e666fe3353db9
data/.gitattributes ADDED
@@ -0,0 +1 @@
1
+ data/zip_geo_jp.sqlite3 filter=lfs diff=lfs merge=lfs -text
data/.gitignore ADDED
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ /.idea/
10
+ Gemfile.lock
11
+
12
+ # rspec failure tracking
13
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.5.3
6
+ before_install: gem install bundler -v 2.1.4
@@ -0,0 +1,74 @@
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 toshiya.horie@gree.net. 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 [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ source "https://rubygems.org"
2
+
3
+ gemspec
4
+
5
+ gem 'rake', '~> 12.0'
6
+ gem 'rspec', '~> 3.0'
7
+ gem 'rubyzip'
8
+ gem 'nokogiri'
9
+ gem 'ruby-progressbar'
10
+ gem 'parallel'
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Toshiya Horie
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.
data/README.md ADDED
@@ -0,0 +1,46 @@
1
+ # ZipGeoJp
2
+
3
+ Convert Japanese zip code to latitude/longitude.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'zip_geo_jp'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install zip_geo_jp
20
+
21
+ ## Usage
22
+
23
+ ```
24
+ > ZipGeoJa['167-0021']
25
+ => #<ZipGeoJp::Record:0x00007f941588c920 @zip_code="167-0021", @prefecture="東京都", @city="杉並区", @latitude=35.7276542, @longitude=139.6158849, @block="井草">
26
+ ```
27
+
28
+
29
+ ## Development
30
+
31
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
32
+
33
+ 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).
34
+
35
+ ## Contributing
36
+
37
+ Bug reports and pull requests are welcome on GitHub at https://github.com/toshiya-horie/zip_geo_jp. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/toshiya-horie/zip_geo_jp/blob/main/CODE_OF_CONDUCT.md).
38
+
39
+
40
+ ## License
41
+
42
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
43
+
44
+ ## Code of Conduct
45
+
46
+ Everyone interacting in the ZipGeoJp project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/toshiya-horie/zip_geo_jp/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,9 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rspec/core/rake_task'
3
+
4
+
5
+ RSpec::Core::RakeTask.new(:spec)
6
+
7
+ task :default => :spec
8
+
9
+ Dir.glob('lib/tasks/*.rake').each { |r| load r }
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "zip_geo_jp"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
Binary file
@@ -0,0 +1,13 @@
1
+ require_relative '../../lib/zip_geo_jp/rake_helper'
2
+
3
+ namespace :zip_geo_ja do
4
+ desc 'Update zip_geo_ja records'
5
+ task :update do
6
+ ZipGeoJp::RakeHelper.update
7
+ end
8
+
9
+ desc 'Clean zip_geo_ja records'
10
+ task :reset do
11
+ ZipGeoJp::RakeHelper.reset
12
+ end
13
+ end
data/lib/zip_geo_jp.rb ADDED
@@ -0,0 +1,17 @@
1
+ require 'zip_geo_jp/version'
2
+ require 'zip_geo_jp/record'
3
+
4
+ module ZipGeoJp
5
+
6
+ class << self
7
+
8
+ # Convert zip code to latitude/longitude
9
+ #
10
+ # @param [String] zip_code
11
+ # @return [Record]
12
+ def [](zip_code)
13
+ ZipGeoJp::Record[zip_code.unicode_normalize(:nfkc).sub('-', '')]
14
+ end
15
+
16
+ end
17
+ end
@@ -0,0 +1,38 @@
1
+ require 'open-uri'
2
+
3
+ module ZipGeoJp
4
+ class Downloader
5
+
6
+ attr_accessor :url, :local_dir
7
+
8
+ def initialize(url, local_dir)
9
+ @url = url
10
+ @local_dir = local_dir
11
+ end
12
+
13
+ def filename
14
+ @filename ||= URI.parse(url).path.to_s.split('/').last
15
+ end
16
+
17
+ def local
18
+ File.join(@local_dir, filename)
19
+ end
20
+
21
+ def remove
22
+ FileUtils.remove_file local if File.exist? local
23
+ end
24
+
25
+ def downloaded?
26
+ File.exist? local
27
+ end
28
+
29
+ def download
30
+ FileUtils.mkdir_p(@local_dir)
31
+ open(@url) do |stream|
32
+ open(local, 'w+b') do |file|
33
+ file.write(stream.read)
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,73 @@
1
+ require 'parallel'
2
+ require 'zip'
3
+ require 'csv'
4
+ require 'uri'
5
+ require 'open-uri'
6
+ require 'nokogiri'
7
+ require_relative 'downloader'
8
+ require_relative 'record'
9
+
10
+ module ZipGeoJp
11
+ module RakeHelper
12
+
13
+ DOWNLOAD_URL_ENDPOINT = 'https://www.post.japanpost.jp/zipcode/dl/oogaki/zip/'.freeze
14
+ DOWNLOAD_URL_SUFFIX = ['ken_all.zip'].freeze
15
+ GOOGLE_MAP_CRAWLING_DURATION = (ENV['GOOGLE_MAP_CRAWLING_DURATION'] || 1).to_f.freeze
16
+ GOOGLE_MAP_CRAWLING_CONCURRENCY = (ENV['GOOGLE_MAP_CRAWLING_CONCURRENCY'] || 1).to_i.freeze
17
+
18
+ class << self
19
+ def update
20
+ DOWNLOAD_URL_SUFFIX.map do |suffix|
21
+ download_url = DOWNLOAD_URL_ENDPOINT + suffix
22
+ records = extract_zip_code(download_url)
23
+ Parallel.each(records, in_threads: GOOGLE_MAP_CRAWLING_CONCURRENCY) do |zip_code, pref, city, block|
24
+ puts "Item: #{zip_code} #{pref}#{city}#{block}, Worker: #{Parallel.worker_number}"
25
+ unless ZipGeoJp::Record[zip_code]
26
+ coordinates = coordinates_from_google_map(zip_code)
27
+ ZipGeoJp::Record[zip_code] = {
28
+ prefecture: pref,
29
+ city: city,
30
+ block: block,
31
+ latitude: coordinates[0],
32
+ longitude: coordinates[1],
33
+ }
34
+ sleep(GOOGLE_MAP_CRAWLING_DURATION)
35
+ end
36
+ end
37
+ end
38
+ end
39
+
40
+ def reset
41
+ ZipGeoJp::Record.reset
42
+ end
43
+
44
+ private
45
+
46
+ def extract_zip_code(download_url)
47
+ downloader = ZipGeoJp::Downloader.new(download_url, 'tmp')
48
+ downloader.download unless downloader.downloaded?
49
+
50
+ records = []
51
+ Zip::File.open(downloader.local) do |zip_file|
52
+ entry = zip_file.glob('*.CSV').first
53
+ CSV.parse(
54
+ entry.get_input_stream.read.encode(Encoding::UTF_8, Encoding::Shift_JIS),
55
+ ).each do |rows|
56
+ zipcode = rows[2]
57
+ pref, city, block = rows.slice(6, 3).map { |r| r.unicode_normalize(:nfkc) }
58
+ records.push([zipcode, pref, city, block])
59
+ end
60
+ end
61
+
62
+ records
63
+ end
64
+
65
+ def coordinates_from_google_map(zip_code)
66
+ google_map_url = "https://www.google.com/maps/place/%E3%80%92#{zip_code.gsub(/^(\d{3})(\d{4})$/, '\1-\2')}/"
67
+ image_url = Nokogiri::HTML(open(google_map_url).read).at('meta[itemprop="image"]')['content']
68
+ coordinates_str = URI.parse(image_url).query.split('&').map { |kv| kv.split('=') }.to_h['center']
69
+ URI.decode(coordinates_str).split(',').map(&:to_f)
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,61 @@
1
+ require 'sqlite3'
2
+
3
+ module ZipGeoJp
4
+ class Record
5
+ attr_reader :zip_code, :prefecture, :city, :block, :latitude, :longitude
6
+
7
+ def initialize(values)
8
+ @zip_code = values.shift.gsub(/^(\d{3})(\d{4})$/, '\1-\2')
9
+ @prefecture, @city, @block, @latitude, @longitude = values
10
+ end
11
+
12
+ class << self
13
+ def [] (key)
14
+ row = db.execute('SELECT * FROM zip_codes WHERE zip_code = ? LIMIT 1', key).first
15
+ row ? from_row(row) : nil
16
+ end
17
+
18
+ def []= (key, values)
19
+ values[:zip_code] = key
20
+ db.execute(
21
+ 'REPLACE INTO zip_codes(zip_code, prefecture, city, block, latitude, longitude) VALUES(:zip_code, :prefecture, :city, :block, :latitude, :longitude)',
22
+ values
23
+ )
24
+ values
25
+ end
26
+
27
+ def reset
28
+ File.delete(file) if File.exists?(file)
29
+ end
30
+
31
+ def from_row(row)
32
+ new(row.values)
33
+ end
34
+
35
+ private
36
+
37
+ def db
38
+ @@db ||= begin
39
+ db = SQLite3::Database.new(file)
40
+ db.results_as_hash = true
41
+ db.execute(<<_EOF_
42
+ CREATE TABLE IF NOT EXISTS zip_codes (
43
+ zip_code TEXT NOT NULL PRIMARY KEY,
44
+ prefecture TEXT NOT NULL,
45
+ city TEXT NOT NULL,
46
+ block TEXT,
47
+ latitude REAL,
48
+ longitude REAL
49
+ )
50
+ _EOF_
51
+ )
52
+ db
53
+ end
54
+ end
55
+
56
+ def file
57
+ File.join(__dir__, '../../data/zip_geo_jp.sqlite3')
58
+ end
59
+ end
60
+ end # Data
61
+ end # Zipja
@@ -0,0 +1,3 @@
1
+ module ZipGeoJp
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,20 @@
1
+ require_relative 'lib/zip_geo_jp/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = 'zip_geo_jp'
5
+ spec.version = ZipGeoJp::VERSION
6
+ spec.authors = ['Toshiya Horie']
7
+ spec.email = ['toshiya.horie@gmail.com']
8
+
9
+ spec.summary = 'Convert Japanese zip code to coordinates.'
10
+ spec.description = spec.summary
11
+ spec.license = 'MIT'
12
+ spec.required_ruby_version = Gem::Requirement.new('>= 2.3.0')
13
+ spec.homepage = 'https://github.com/toshiya-horie/zip_geo_jp'
14
+
15
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
16
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
17
+ end
18
+ spec.require_paths = ['lib']
19
+ spec.add_dependency 'sqlite3'
20
+ end
metadata ADDED
@@ -0,0 +1,77 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: zip_geo_jp
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Toshiya Horie
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2021-03-24 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: sqlite3
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ description: Convert Japanese zip code to coordinates.
28
+ email:
29
+ - toshiya.horie@gmail.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".gitattributes"
35
+ - ".gitignore"
36
+ - ".rspec"
37
+ - ".travis.yml"
38
+ - CODE_OF_CONDUCT.md
39
+ - Gemfile
40
+ - LICENSE.txt
41
+ - README.md
42
+ - Rakefile
43
+ - bin/console
44
+ - bin/setup
45
+ - data/zip_geo_jp.sqlite3
46
+ - lib/tasks/zip_geo_ja.rake
47
+ - lib/zip_geo_jp.rb
48
+ - lib/zip_geo_jp/downloader.rb
49
+ - lib/zip_geo_jp/rake_helper.rb
50
+ - lib/zip_geo_jp/record.rb
51
+ - lib/zip_geo_jp/version.rb
52
+ - tmp/.gitkeep
53
+ - zip_geo_jp.gemspec
54
+ homepage: https://github.com/toshiya-horie/zip_geo_jp
55
+ licenses:
56
+ - MIT
57
+ metadata: {}
58
+ post_install_message:
59
+ rdoc_options: []
60
+ require_paths:
61
+ - lib
62
+ required_ruby_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: 2.3.0
67
+ required_rubygems_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: '0'
72
+ requirements: []
73
+ rubygems_version: 3.0.6
74
+ signing_key:
75
+ specification_version: 4
76
+ summary: Convert Japanese zip code to coordinates.
77
+ test_files: []