Anaconda (Python)をSDカードに移動

スティックPCのCドライブは32GBしかないので、Anaconda をDドライブの16GB SDカードへ逃がすことにした。SDカードはexFATでフォーマットしてあるが、デフォルトではアロケーションユニットサイズは32 KBとなり、Anaconda のように小さなファイルが多い場合には余計に容量が必要になる。

Anaconda 2 (32ビット)では、以下のコードで調べると平均37.13 KBのファイルが36908個インストールされている。

d = []
conda_default_env = os.getenv('CONDA_DEFAULT_ENV')
for dirpath, dirnames, filenames in os.walk(conda_default_env):
    for filename in filenames:
        filepath = os.path.join(dirpath, filename)
        filesize = os.path.getsize(filepath)
        d.append((filepath, filesize))
d = pd.DataFrame(d, columns = [ 'filepath', 'filesize' ])

block_size = 32 * 1024
average_filesize = d['filesize'].mean()
file_count = len(d)
waste_rate = float(file_count) * block_size / 2 / average_filesize
print 'Number of files: %d' % (file_count)
print 'Average file size: %.2f KB' % (average_filesize / 1024.0)

ファイルのサイズを32 KBで割った余りは一様分布していると仮定すると、1ファイルあたり平均で16 KBがオーバーヘッドになる。これは平均ファイルサイズから計算するとファイルサイズの43%だ。Anaconda 2のインストールのファイルサイズの合計が1.30 GBなので、577 MBがオーバーヘッドで使用されるストレージの容量は1.86 GB程度になるはずだが、実際には2.19 GBが使われている。

どうも、アロケーションユニットサイズがファイルサイズと比較して大きいため、「一様分布」の仮定が正しくないようだ。

anaconda_filesize_hist

ヒストグラムを見ると多くのファイルは512バイト程度なのがわかる。

(block_size - d['filesize'] % block_size).sum() / (1024.0 * 1024.0)

より、919 MBがオーバーヘッドで使用されるストレージの容量は2.20 GBと計算できる。

ちなみにMP3ファイルは平均5.6 MB程度なのでオーバーヘッドは0.2%程度で、効率がよい。

また、64 GBのSDカードではアロケーションユニットサイズは128 KBとなるので、Anacondaの場合、4.13 GB程度がオーバーヘッドとなる。容量が4倍になってもアロケーションユニットサイズが4倍になっているため、ファイルサイズが小さい場合、保存できるファイルの数という点では変わらない。

結局、SDカードに移すことでPythonの起動が遅くなるデメリットもあるのでAnacondaはCドライブに入れることにした。

Visual Studio 2015でMeCab-Python 0.996をビルド

MeCabはオープンソースの形態素解析エンジンで、以下のページで公開されている。

このサイトでダウンロードでは32-bit Windows用のバイナリを公開しているが、64-bitのPythonのバインディングが使いたかったので自分でビルドすることにした。MeCab-Pythonのビルドに方法に関してはいろいろな場所で公開されているて、微妙に使っているソフトやアプリのバージョンが異なる。ここでは、

  • Python 2.7.10 [Anaconda (2.3.0 64-bit)] MSC v.1500 (AMD64)
  • MeCab 0.996 Win32 バイナリ(辞書のため)
  • MeCab 0.996 ソース
  • MeCab-Python 0.996 ソース
  • MSC v.1900 (Visual Studio 2015) またはMSC v.1800 (Visual Studio 2013)

の組み合わせを使った。Python 2.7はMSC v.1500 (Visual Studio 2008)でビルドされているので、Microsoft Visual C++ Compiler for Python 2.7など同じバージョンのコンパイラーを使ったほうがいいのだが、テキストマイニングとかは何となく動いていればまぁいい場合が多いのであまり気にしないことにした。

MeCabのビルド

まず、MeCabのビルドだが、3か所に修正が必要だ。とりあえず、feature_index.cppとwriter.cppの2か所は

に従う。MeCabはビルドにconfigureを使用している。Win32ではsrc/Makefile.msvc.inからsrc/Makefile.msvcを生成する必要がある。MinGWやCygwinがあれば、configureを実行できるが、なくても、自分でコピーして@VERSION@@DIC_VERSION@を置換してやればよい。また、X64でビルドしたいので/MACHINE:X86を書き換えてある。

diff --git a/src/Makefile.msvc b/src/Makefile.msvc
index 7d10a5e..8ba6383 100644
--- a/src/Makefile.msvc
+++ b/src/Makefile.msvc
@@ -3,7 +3,7 @@ CXXC = cl.exe
 LINK=link.exe

 CFLAGS = /EHsc /O2 /GL /GA /Ob2 /nologo /W3 /MT /Zi /wd4800 /wd4305 /wd4244
-LDFLAGS = /nologo /OPT:REF /OPT:ICF /LTCG /NXCOMPAT /DYNAMICBASE /MACHINE:X86 A
+LDFLAGS = /nologo /OPT:REF /OPT:ICF /LTCG /NXCOMPAT /DYNAMICBASE /MACHINE:X64 A
 DEFS =  -D_CRT_SECURE_NO_DEPRECATE -DMECAB_USE_THREAD \
-        -DDLL_EXPORT -DHAVE_GETENV -DHAVE_WINDOWS_H -DDIC_VERSION=@DIC_VERSION@
-        -DVERSION="\"@VERSION@\"" -DPACKAGE="\"mecab\"" \
+        -DDLL_EXPORT -DHAVE_GETENV -DHAVE_WINDOWS_H -DDIC_VERSION=102
+        -DVERSION="\"0.996\"" -DPACKAGE="\"mecab\"" \

ビルドするには、VS2015 x64 Native Tools Command Promptなどを起動して、

> cd mecab-0.996\src
> nmake -f Makefile.msvc

本来なら、make.batを実行するところだが、make.batはMSC v.900 (Visual Studio 2008)を使おうとするので、VS2016 x64 Native Toolsコマンドプロンプトから直接、nmakeを実行する。

うまくビルドができたら、

libmecab.dll          mecab-dict-gen.exe    mecab-system-eval.exe  mecab.exe
mecab-cost-train.exe  mecab-dict-index.exe  mecab-test-gen.exe

C:\local\MeCab\binへコピーし、

libmecab.lib          mecab.h

C:\local\MeCab\sdkへコピーする。

MeCabの辞書

次に、辞書ファイルだが、ソースから生成せずにバイナリに付属するものを使う。ソースのCSVファイルとDEFファイルはEUC-JPのテキストファイルだが、WindowsではDEFファイルはShift-JISである必要があるようだ。

Win32のインストーラーでMeCabをインストールし、UTF-8としてインデックスを生成する。

この時点でC:\local\MeCab\bin\mecab.exeが実行できるはずだ。mecab.exeの実行にはmecabrcmecabrcが参照している辞書ファイルが必要だ。パスはレジストリーのHKEY_CURRENT_USER\SOFTWARE\MeCab\mecabrcのパスに設定されているC:\Program Files (x86)\MeCab\etc\mecabrcが読み込まれる。

このままでもいいが、辞書ファイルはいろいろ変更したいので、

C:\Program Files (x86)\MeCab\etcC:\Program Files (x86)\MeCab\dicC:\local\MeCabにコピーしておく。環境変数MECABRCでもmecabrcのパスは変えられる。

> set MECABRC=C:\local\MeCab\etc\mecabrc

MeCab-Pythonのビルド

Win32用にmecab-configがないのでsetup.pyを以下のように変更。

diff --git a/setup.py b/setup.py
index 61c28d9..eae8c28 100644
--- a/setup.py
+++ b/setup.py
@@ -15,7 +15,7 @@
         setup(name = "mecab-python",
-        version = cmd1("mecab-config --version"),
+        version = "0.996",
         ext_modules = [
                 Extension("_MeCab",
                         ["MeCab_wrap.cxx",],
-                        include_dirs=cmd2("mecab-config --inc-dir"),
-                        library_dirs=cmd2("mecab-config --libs-only-L"),
-                        libraries=cmd2("mecab-config --libs-only-l"))
+                        include_dirs=[r"C:\local\MeCab\sdk"],
+                        library_dirs=[r"C:\local\MeCab\sdk"],
+                        libraries=["libmecab"])
                         ])

PythonのdistutilsはMSC v.900を使おうとするが、MSC v.1900を使わせるためにVS90COMNTOOLSを書き換えてごまかす。VS2015 x64 Native Tools Command Promptを起動して、

> cd mecab-python-0.996
> set VS90COMNTOOLS=%VS140COMNTOOLS%
> python setup.py build
> python setup.py install

を実行する。

> python setup.py bdist_wininst

を実行してインストーラーを作ってもよい。

> set MECABRC=C:\local\MeCab\etc\mecabrc
> set PATH=C:\local\MeCab\bin;%PATH%
> python test.py > test.log
> notepad test.log

でうまくいったかテストできる。PATHmecab.dllのために必要だが、mecab.dll%ANACONDA%にコピーしてもよいだろう。

0.996
太郎	名詞,固有名詞,人名,名,*,*,太郎,タロウ,タロー
は	助詞,係助詞,*,*,*,*,は,ハ,ワ
この	連体詞,*,*,*,*,*,この,コノ,コノ
本	名詞,一般,*,*,*,*,本,ホン,ホン
を	助詞,格助詞,一般,*,*,*,を,ヲ,ヲ
二	名詞,数,*,*,*,*,二,ニ,ニ
郎	名詞,一般,*,*,*,*,郎,ロウ,ロー
を	助詞,格助詞,一般,*,*,*,を,ヲ,ヲ
見	動詞,自立,*,*,一段,連用形,見る,ミ,ミ
た	助動詞,*,*,*,特殊・タ,基本形,た,タ,タ
女性	名詞,一般,*,*,*,*,女性,ジョセイ,ジョセイ
に	助詞,格助詞,一般,*,*,*,に,ニ,ニ
渡し	動詞,自立,*,*,五段・サ行,連用形,渡す,ワタシ,ワタシ
た	助動詞,*,*,*,特殊・タ,基本形,た,タ,タ
。	記号,句点,*,*,*,*,。,。,。
EOS

 	BOS/EOS,*,*,*,*,*,*,*,*
太郎 	名詞,固有名詞,人名,名,*,*,太郎,タロウ,タロー
は 	助詞,係助詞,*,*,*,*,は,ハ,ワ
この 	連体詞,*,*,*,*,*,この,コノ,コノ
本 	名詞,一般,*,*,*,*,本,ホン,ホン
を 	助詞,格助詞,一般,*,*,*,を,ヲ,ヲ
二 	名詞,数,*,*,*,*,二,ニ,ニ
郎 	名詞,一般,*,*,*,*,郎,ロウ,ロー
を 	助詞,格助詞,一般,*,*,*,を,ヲ,ヲ
見 	動詞,自立,*,*,一段,連用形,見る,ミ,ミ
た 	助動詞,*,*,*,特殊・タ,基本形,た,タ,タ
女性 	名詞,一般,*,*,*,*,女性,ジョセイ,ジョセイ
に 	助詞,格助詞,一般,*,*,*,に,ニ,ニ
渡し 	動詞,自立,*,*,五段・サ行,連用形,渡す,ワタシ,ワタシ
た 	助動詞,*,*,*,特殊・タ,基本形,た,タ,タ
。 	記号,句点,*,*,*,*,。,。,。
 	BOS/EOS,*,*,*,*,*,*,*,*
EOS
EOS
filename: C:\local\MeCab\etc\..\dic\ipadic\sys.dic
charset: UTF-8
size: 392126
type: 0
lsize: 1316
rsize: 1316
version: 102

おまけ

辞書のインデックスを生成するために以下を実行。

> cd C:\local\MeCab\dic\ipadic
> mecab-dict-index -t shift-jis -c utf-8

参考:MeCab辞書へ単語の追加してみた

Setting up Mercurial repository on Windows

On Linux and Mac OS, setting up a Mercurial repository is easy. You can just place repository files under your home directory and use it via SSH. However, on Windows, there’s no straightforward way to set up an SSH server.

I’m going to use IIS 8.0 on Windows 8 64 bit, Python 2.7.3 and Mercurial 2.3.

Setting up Python 2.7.3 and Mercurial 2.3

Installing Python and Mercurial is easy. You need to choose the right combination of versions and installation types. Download Python 2.7.3 Windows Installer from http://www.python.org/ and Mercurial MSI installer – x86 Windows – requires admin rights from http://mercurial.selenic.com/. Both installer is for x86. Probably 64-bit Python and Mercurial works, but I use some x86 programs which use Python DLL and want to share it.

First double-click python-2.7.3.msi and choose the default settings. Then doubleclick mercurial-2.3.win32-py2.7.exe and choose the default settings. Mercurial installer automatically detects Python installation.

Testing installation

If the installation is successful, you can use Mercurial API from Python. Launch Command Prompt and move to an empty directory. Type c:\Python27\python.exe to launch Python installer. Then type

from mercurial import hg,ui,commands
commands.init(ui.ui())

You’ll see an .hg directory just created.

Setting up IIS 8.0

IIS is not installed by default. Go to the Control Panel, Program, Enable and disable Windows features. Select Internet Information Service and CGI and Basic Authentication.

image

Enable SSL

To enable SSL, you need a security certificate. A self-signed certificate doesn’t cost and works on a small organization. IIS Manager can create a self-signed certificate, however, Python doesn’t like a certificate created by IIS Manager. You need to use OpenSSL to make one. There’re many web site that explain how to make a certificate with OpenSSL. I don’t explain details here. I used these commands

openssl genrsa -des3 -out privkey.pem 2048
openssl req -new -x509 -key privkey.pem -days 365 -out cacert.cer
openssl pkcs12 -keypbe PBE-SHA1-3DES -certpbe PBE-SHA1-3DES -export -in cacert.cer -inkey privkey.pem -out privkey.pfx -name "IIS Certificate"

Select the root node and double-click Server Certificate. Then import the certificate.

image

Right-click Default Web Site and select Edit Bindings and choose the certificate just created.

image

Set up Mercurial application

Create a directory for the application c:\WebApps\Mercurial, then make a python script c:\WebApps\Mercurial\bin\Mercurial.py.

import cgitb, os, sys
from mercurial import hgweb

cgitb.enable()
f = open(sys.argv[1], "r")
path = f.readline().strip()
name = f.readline().strip()
f.close()

h = hgweb.hgweb(path, name)
h.run()

Right click on Default Web Site and select Add Application and name its alias Mercurial.

image

Select Mercurial and double-click Authorization. Enable Basic Authorization and disable Anonymous Authorization

image

Double-click SSL Settings and check SSL is required.

image

Create a text file c:\WebApps\Mercurial\test.

c:\Code\Mercurial\test
Test repository

Replace the first line with your Mercurial repository path and the second line with its description.

Testing your repository

You are done. It is time to use your repository. I use TortoiseHG for Windows. Prepare an empty directory c:\Build\test. Right-click it and select TortoiseHG, Create Repository Here.

Setting up Certificate

To let TortoiseHG to accept the certificate. You need to edit the configuration file. Open c:\Build\test\.hg\hgrc with your favourite editor and add these lines.

[web]
cacerts = c:\Users\Katsuya\magnesium.cer

[paths]
default = https://magnesium/Mercurial/test

Of course, you need to modify the path and the URL.

You are ready now. You can use HG Workbench to push to and pull from the repository. You need your Windows user and password to access the repository.