first
This commit is contained in:
@@ -0,0 +1,5 @@
|
|||||||
|
.build/
|
||||||
|
build/
|
||||||
|
.swiftpm/
|
||||||
|
*.xcodeproj/xcuserdata/
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
// swift-tools-version:5.9
|
||||||
|
import PackageDescription
|
||||||
|
|
||||||
|
let package = Package(
|
||||||
|
name: "AutoZhuyin",
|
||||||
|
platforms: [.macOS(.v13)],
|
||||||
|
products: [
|
||||||
|
.executable(name: "AutoZhuyin", targets: ["AutoZhuyin"]),
|
||||||
|
.library(name: "AutoZhuyinCore", targets: ["AutoZhuyinCore"]),
|
||||||
|
],
|
||||||
|
targets: [
|
||||||
|
// Pure logic: Zhuyin parsing, English/Zhuyin classification, conversion.
|
||||||
|
// No AppKit dependency, so it can be unit-tested with `swift test`.
|
||||||
|
.target(name: "AutoZhuyinCore"),
|
||||||
|
// The InputMethodKit server process (packaged into a .app by scripts/build.sh).
|
||||||
|
.executableTarget(
|
||||||
|
name: "AutoZhuyin",
|
||||||
|
dependencies: ["AutoZhuyinCore"],
|
||||||
|
linkerSettings: [.linkedFramework("InputMethodKit"), .linkedFramework("Cocoa")]
|
||||||
|
),
|
||||||
|
.testTarget(
|
||||||
|
name: "AutoZhuyinCoreTests",
|
||||||
|
dependencies: ["AutoZhuyinCore"]
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
# 自動注音 AutoZhuyin
|
||||||
|
|
||||||
|
macOS 繁體中文輸入法:**不用按切換鍵**,直接用大千注音鍵盤打字,輸入法會自動判斷你打的是注音還是英文。
|
||||||
|
|
||||||
|
```
|
||||||
|
按鍵: ji3 hello world su3cl3␣
|
||||||
|
輸出: 我hello world 你好
|
||||||
|
```
|
||||||
|
|
||||||
|
## 運作方式
|
||||||
|
|
||||||
|
每按一個鍵,`Classifier` 會同時用兩種解讀幫目前的按鍵序列打分:
|
||||||
|
|
||||||
|
| 注音分數 | 英文分數 |
|
||||||
|
|---|---|
|
||||||
|
| 是否能拆成合法注音音節(`SyllableTable`) | 是否為常用英文字(`english-common.txt`) |
|
||||||
|
| 每個音節有沒有聲調鍵(3 4 6 7 空白) | 是否在系統字典 `/usr/share/dict/words` |
|
||||||
|
| 讀音是否存在於詞庫 | 字母 bigram 模型判斷「像不像英文」 |
|
||||||
|
| 前一段是中文 → 加分(語境) | 前一段是英文 → 加分(語境) |
|
||||||
|
| 使用者過去的修正(學習) | 有大寫字母 → 一定是英文 |
|
||||||
|
|
||||||
|
分數高的一方勝出。組字區即時顯示結果(英文以藍字顯示)。
|
||||||
|
|
||||||
|
## 按鍵
|
||||||
|
|
||||||
|
| 按鍵 | 作用 |
|
||||||
|
|---|---|
|
||||||
|
| 空白 | 注音:一聲;音節已完成時送出中文。英文:送出單字加空白 |
|
||||||
|
| Enter | 送出目前組字 |
|
||||||
|
| **Tab** | 判斷錯了?按 Tab 在中/英之間翻轉,輸入法會**記住**這次修正 |
|
||||||
|
| ↓ | 開啟候選字(選最後一個字或詞),數字鍵 1–9 選字 |
|
||||||
|
| Esc | 取消組字 |
|
||||||
|
| Shift + 字母 | 強制英文 |
|
||||||
|
| `< > ? ! :` | 中文語境下自動轉成全形 `,。?!:` |
|
||||||
|
|
||||||
|
## 建置與安裝
|
||||||
|
|
||||||
|
需要 Xcode(使用 `/Applications/Xcode.app` 的工具鏈)。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
swift test # 執行單元測試(需 DEVELOPER_DIR 指向 Xcode)
|
||||||
|
scripts/build.sh # 產生 build/AutoZhuyin.app
|
||||||
|
scripts/install.sh # 安裝到 ~/Library/Input Methods 並重啟輸入法
|
||||||
|
```
|
||||||
|
|
||||||
|
第一次安裝後:系統設定 → 鍵盤 → 文字輸入 → 編輯… → + → 繁體中文 → **自動注音**。
|
||||||
|
如果清單裡沒出現,登出再登入一次。
|
||||||
|
|
||||||
|
## 詞庫
|
||||||
|
|
||||||
|
`Resources/lexicon.txt` 由開源的小麥注音原始資料轉換而來(MIT 授權,約 17 萬筆),
|
||||||
|
後面再接上手寫的入門詞庫 `Resources/lexicon-seed.txt`。轉換只讀取資料檔,不執行小麥注音的程式碼。
|
||||||
|
要更新到小麥注音最新資料:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
scripts/import-mcbopomofo.sh
|
||||||
|
scripts/install.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
自訂詞:`~/Library/Application Support/AutoZhuyin/user-phrases.txt`,格式同 `lexicon.txt`:
|
||||||
|
`ㄗˋ-ㄉㄨㄥˋ-ㄓㄨˋ-ㄧㄣ 自動注音 -4`
|
||||||
|
|
||||||
|
## 專案結構
|
||||||
|
|
||||||
|
```
|
||||||
|
Sources/AutoZhuyinCore/ 純邏輯,可單元測試
|
||||||
|
Bopomofo.swift 大千鍵盤對應、音節結構
|
||||||
|
SyllableTable.swift 合法注音音節表
|
||||||
|
ZhuyinParser.swift 按鍵 → 音節
|
||||||
|
Lexicon.swift 詞庫
|
||||||
|
Converter.swift 音節 → 中文(Viterbi)
|
||||||
|
EnglishModel.swift 英文判斷
|
||||||
|
Classifier.swift 中英判斷 + 學習
|
||||||
|
CompositionEngine.swift 輸入法狀態機
|
||||||
|
Sources/AutoZhuyin/ InputMethodKit 外殼
|
||||||
|
Tests/ 單元測試
|
||||||
|
```
|
||||||
|
|
||||||
|
## 下一步(Roadmap)
|
||||||
|
|
||||||
|
- [ ] 匯入完整詞庫,並用真實打字資料調整判斷權重
|
||||||
|
- [ ] 已送出的英文單字若判斷錯誤,可以「事後翻轉」
|
||||||
|
- [ ] 用 Core ML 小模型取代手調分數,參考整句語境
|
||||||
|
- [ ] 使用者詞頻學習(選過的候選字優先)
|
||||||
|
- [ ] 偏好設定視窗
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>CFBundleDevelopmentRegion</key>
|
||||||
|
<string>zh_TW</string>
|
||||||
|
<key>CFBundleExecutable</key>
|
||||||
|
<string>AutoZhuyin</string>
|
||||||
|
<key>CFBundleIdentifier</key>
|
||||||
|
<string>com.autozhuyin.inputmethod.AutoZhuyin</string>
|
||||||
|
<key>CFBundleName</key>
|
||||||
|
<string>AutoZhuyin</string>
|
||||||
|
<key>CFBundleDisplayName</key>
|
||||||
|
<string>自動注音</string>
|
||||||
|
<key>CFBundlePackageType</key>
|
||||||
|
<string>APPL</string>
|
||||||
|
<key>CFBundleShortVersionString</key>
|
||||||
|
<string>0.1.0</string>
|
||||||
|
<key>CFBundleVersion</key>
|
||||||
|
<string>1</string>
|
||||||
|
<key>LSMinimumSystemVersion</key>
|
||||||
|
<string>13.0</string>
|
||||||
|
<key>LSBackgroundOnly</key>
|
||||||
|
<true/>
|
||||||
|
<key>LSUIElement</key>
|
||||||
|
<true/>
|
||||||
|
<key>NSPrincipalClass</key>
|
||||||
|
<string>NSApplication</string>
|
||||||
|
<key>InputMethodConnectionName</key>
|
||||||
|
<string>com.autozhuyin.inputmethod.AutoZhuyin_Connection</string>
|
||||||
|
<key>InputMethodServerControllerClass</key>
|
||||||
|
<string>AutoZhuyinInputController</string>
|
||||||
|
<key>TISInputSourceID</key>
|
||||||
|
<string>com.autozhuyin.inputmethod.AutoZhuyin</string>
|
||||||
|
<key>TISIntendedLanguage</key>
|
||||||
|
<string>zh-Hant</string>
|
||||||
|
<key>tsInputMethodIconFileKey</key>
|
||||||
|
<string>icon.tiff</string>
|
||||||
|
<key>tsInputMethodCharacterRepertoireKey</key>
|
||||||
|
<array>
|
||||||
|
<string>Hant</string>
|
||||||
|
<string>Latn</string>
|
||||||
|
</array>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
@@ -0,0 +1,368 @@
|
|||||||
|
# Common English words (strong evidence for English). One per line; add your own.
|
||||||
|
a
|
||||||
|
about
|
||||||
|
above
|
||||||
|
access
|
||||||
|
account
|
||||||
|
add
|
||||||
|
after
|
||||||
|
again
|
||||||
|
against
|
||||||
|
age
|
||||||
|
ago
|
||||||
|
ai
|
||||||
|
air
|
||||||
|
all
|
||||||
|
also
|
||||||
|
always
|
||||||
|
am
|
||||||
|
an
|
||||||
|
and
|
||||||
|
android
|
||||||
|
another
|
||||||
|
answer
|
||||||
|
any
|
||||||
|
api
|
||||||
|
app
|
||||||
|
apple
|
||||||
|
apps
|
||||||
|
are
|
||||||
|
area
|
||||||
|
around
|
||||||
|
as
|
||||||
|
ask
|
||||||
|
at
|
||||||
|
away
|
||||||
|
back
|
||||||
|
bad
|
||||||
|
bank
|
||||||
|
be
|
||||||
|
because
|
||||||
|
been
|
||||||
|
before
|
||||||
|
being
|
||||||
|
best
|
||||||
|
better
|
||||||
|
between
|
||||||
|
big
|
||||||
|
blog
|
||||||
|
book
|
||||||
|
both
|
||||||
|
boy
|
||||||
|
bug
|
||||||
|
build
|
||||||
|
business
|
||||||
|
but
|
||||||
|
buy
|
||||||
|
by
|
||||||
|
call
|
||||||
|
came
|
||||||
|
can
|
||||||
|
car
|
||||||
|
case
|
||||||
|
cat
|
||||||
|
change
|
||||||
|
chat
|
||||||
|
check
|
||||||
|
city
|
||||||
|
class
|
||||||
|
click
|
||||||
|
close
|
||||||
|
cloud
|
||||||
|
code
|
||||||
|
coffee
|
||||||
|
come
|
||||||
|
company
|
||||||
|
computer
|
||||||
|
could
|
||||||
|
data
|
||||||
|
day
|
||||||
|
debug
|
||||||
|
deploy
|
||||||
|
design
|
||||||
|
did
|
||||||
|
do
|
||||||
|
docs
|
||||||
|
does
|
||||||
|
dog
|
||||||
|
done
|
||||||
|
down
|
||||||
|
each
|
||||||
|
email
|
||||||
|
end
|
||||||
|
error
|
||||||
|
even
|
||||||
|
every
|
||||||
|
eye
|
||||||
|
face
|
||||||
|
fact
|
||||||
|
family
|
||||||
|
far
|
||||||
|
feel
|
||||||
|
file
|
||||||
|
find
|
||||||
|
first
|
||||||
|
fix
|
||||||
|
for
|
||||||
|
found
|
||||||
|
free
|
||||||
|
friend
|
||||||
|
from
|
||||||
|
game
|
||||||
|
get
|
||||||
|
git
|
||||||
|
github
|
||||||
|
give
|
||||||
|
go
|
||||||
|
good
|
||||||
|
google
|
||||||
|
got
|
||||||
|
great
|
||||||
|
group
|
||||||
|
had
|
||||||
|
hand
|
||||||
|
happy
|
||||||
|
has
|
||||||
|
have
|
||||||
|
he
|
||||||
|
hello
|
||||||
|
help
|
||||||
|
her
|
||||||
|
here
|
||||||
|
hi
|
||||||
|
high
|
||||||
|
him
|
||||||
|
his
|
||||||
|
home
|
||||||
|
how
|
||||||
|
html
|
||||||
|
http
|
||||||
|
https
|
||||||
|
i
|
||||||
|
id
|
||||||
|
idea
|
||||||
|
if
|
||||||
|
image
|
||||||
|
in
|
||||||
|
info
|
||||||
|
input
|
||||||
|
into
|
||||||
|
iphone
|
||||||
|
is
|
||||||
|
issue
|
||||||
|
it
|
||||||
|
its
|
||||||
|
java
|
||||||
|
job
|
||||||
|
json
|
||||||
|
just
|
||||||
|
keep
|
||||||
|
key
|
||||||
|
kind
|
||||||
|
know
|
||||||
|
last
|
||||||
|
late
|
||||||
|
later
|
||||||
|
learn
|
||||||
|
left
|
||||||
|
let
|
||||||
|
life
|
||||||
|
like
|
||||||
|
line
|
||||||
|
link
|
||||||
|
list
|
||||||
|
little
|
||||||
|
live
|
||||||
|
login
|
||||||
|
long
|
||||||
|
look
|
||||||
|
lot
|
||||||
|
love
|
||||||
|
mac
|
||||||
|
macos
|
||||||
|
made
|
||||||
|
mail
|
||||||
|
make
|
||||||
|
man
|
||||||
|
many
|
||||||
|
may
|
||||||
|
me
|
||||||
|
meet
|
||||||
|
meeting
|
||||||
|
merge
|
||||||
|
might
|
||||||
|
mind
|
||||||
|
money
|
||||||
|
more
|
||||||
|
most
|
||||||
|
move
|
||||||
|
much
|
||||||
|
must
|
||||||
|
my
|
||||||
|
name
|
||||||
|
need
|
||||||
|
never
|
||||||
|
new
|
||||||
|
news
|
||||||
|
next
|
||||||
|
nice
|
||||||
|
night
|
||||||
|
no
|
||||||
|
not
|
||||||
|
note
|
||||||
|
now
|
||||||
|
number
|
||||||
|
of
|
||||||
|
off
|
||||||
|
office
|
||||||
|
ok
|
||||||
|
okay
|
||||||
|
old
|
||||||
|
on
|
||||||
|
once
|
||||||
|
one
|
||||||
|
online
|
||||||
|
only
|
||||||
|
open
|
||||||
|
or
|
||||||
|
order
|
||||||
|
other
|
||||||
|
our
|
||||||
|
out
|
||||||
|
over
|
||||||
|
own
|
||||||
|
page
|
||||||
|
part
|
||||||
|
password
|
||||||
|
people
|
||||||
|
phone
|
||||||
|
place
|
||||||
|
play
|
||||||
|
please
|
||||||
|
point
|
||||||
|
post
|
||||||
|
problem
|
||||||
|
project
|
||||||
|
pull
|
||||||
|
push
|
||||||
|
put
|
||||||
|
python
|
||||||
|
question
|
||||||
|
quite
|
||||||
|
read
|
||||||
|
real
|
||||||
|
really
|
||||||
|
release
|
||||||
|
repo
|
||||||
|
right
|
||||||
|
room
|
||||||
|
run
|
||||||
|
said
|
||||||
|
same
|
||||||
|
save
|
||||||
|
saw
|
||||||
|
say
|
||||||
|
school
|
||||||
|
search
|
||||||
|
second
|
||||||
|
see
|
||||||
|
seem
|
||||||
|
send
|
||||||
|
server
|
||||||
|
set
|
||||||
|
she
|
||||||
|
should
|
||||||
|
show
|
||||||
|
side
|
||||||
|
since
|
||||||
|
small
|
||||||
|
so
|
||||||
|
some
|
||||||
|
something
|
||||||
|
soon
|
||||||
|
sorry
|
||||||
|
start
|
||||||
|
still
|
||||||
|
stop
|
||||||
|
story
|
||||||
|
such
|
||||||
|
sure
|
||||||
|
swift
|
||||||
|
system
|
||||||
|
take
|
||||||
|
talk
|
||||||
|
team
|
||||||
|
tell
|
||||||
|
test
|
||||||
|
text
|
||||||
|
than
|
||||||
|
thank
|
||||||
|
thanks
|
||||||
|
that
|
||||||
|
the
|
||||||
|
their
|
||||||
|
them
|
||||||
|
then
|
||||||
|
there
|
||||||
|
these
|
||||||
|
they
|
||||||
|
thing
|
||||||
|
think
|
||||||
|
this
|
||||||
|
those
|
||||||
|
thought
|
||||||
|
three
|
||||||
|
through
|
||||||
|
time
|
||||||
|
to
|
||||||
|
today
|
||||||
|
together
|
||||||
|
too
|
||||||
|
took
|
||||||
|
try
|
||||||
|
turn
|
||||||
|
two
|
||||||
|
under
|
||||||
|
until
|
||||||
|
up
|
||||||
|
update
|
||||||
|
url
|
||||||
|
us
|
||||||
|
use
|
||||||
|
user
|
||||||
|
very
|
||||||
|
video
|
||||||
|
want
|
||||||
|
was
|
||||||
|
water
|
||||||
|
way
|
||||||
|
we
|
||||||
|
web
|
||||||
|
week
|
||||||
|
well
|
||||||
|
went
|
||||||
|
were
|
||||||
|
what
|
||||||
|
when
|
||||||
|
where
|
||||||
|
which
|
||||||
|
while
|
||||||
|
who
|
||||||
|
why
|
||||||
|
wifi
|
||||||
|
will
|
||||||
|
with
|
||||||
|
word
|
||||||
|
work
|
||||||
|
world
|
||||||
|
would
|
||||||
|
write
|
||||||
|
www
|
||||||
|
xcode
|
||||||
|
yeah
|
||||||
|
year
|
||||||
|
yes
|
||||||
|
yet
|
||||||
|
you
|
||||||
|
your
|
||||||
|
youtube
|
||||||
@@ -0,0 +1,545 @@
|
|||||||
|
# AutoZhuyin starter lexicon: <reading> <phrase> <log10 score>
|
||||||
|
# Syllables are joined by "-". First tone has no mark; neutral tone is a "˙" suffix.
|
||||||
|
# This is a small seed so the input method works out of the box. Run
|
||||||
|
# scripts/import-mcbopomofo.sh to replace it with a full open-source lexicon.
|
||||||
|
|
||||||
|
# --- single characters ---
|
||||||
|
ㄉㄜ˙ 的 -1.8
|
||||||
|
ㄧ 一 -2.2
|
||||||
|
ㄕˋ 是 -2.2
|
||||||
|
ㄕˋ 事 -3.0
|
||||||
|
ㄕˋ 市 -3.2
|
||||||
|
ㄕˋ 試 -3.3
|
||||||
|
ㄕˋ 室 -3.5
|
||||||
|
ㄕˋ 世 -3.3
|
||||||
|
ㄅㄨˋ 不 -2.3
|
||||||
|
ㄅㄨˋ 部 -3.0
|
||||||
|
ㄅㄨˋ 步 -3.6
|
||||||
|
ㄌㄜ˙ 了 -2.3
|
||||||
|
ㄌㄧㄠˇ 了 -3.6
|
||||||
|
ㄖㄣˊ 人 -2.4
|
||||||
|
ㄨㄛˇ 我 -2.4
|
||||||
|
ㄗㄞˋ 在 -2.4
|
||||||
|
ㄗㄞˋ 再 -3.2
|
||||||
|
ㄧㄡˇ 有 -2.4
|
||||||
|
ㄧㄡˋ 又 -3.2
|
||||||
|
ㄧㄡˋ 右 -3.8
|
||||||
|
ㄊㄚ 他 -2.5
|
||||||
|
ㄊㄚ 她 -2.9
|
||||||
|
ㄊㄚ 它 -3.2
|
||||||
|
ㄓㄜˋ 這 -2.5
|
||||||
|
ㄓㄜ˙ 著 -3.0
|
||||||
|
ㄓㄨㄥ 中 -2.6
|
||||||
|
ㄓㄨㄥ 鐘 -3.9
|
||||||
|
ㄓㄨㄥˋ 重 -3.1
|
||||||
|
ㄓㄨㄥˋ 種 -3.4
|
||||||
|
ㄓㄨㄥˇ 種 -3.2
|
||||||
|
ㄉㄚˋ 大 -2.6
|
||||||
|
ㄌㄞˊ 來 -2.6
|
||||||
|
ㄕㄤˋ 上 -2.6
|
||||||
|
ㄍㄜˋ 個 -2.6
|
||||||
|
ㄍㄜˋ 各 -3.4
|
||||||
|
ㄍㄨㄛˊ 國 -2.7
|
||||||
|
ㄉㄠˋ 到 -2.7
|
||||||
|
ㄉㄠˋ 道 -3.0
|
||||||
|
ㄕㄨㄛ 說 -2.7
|
||||||
|
ㄇㄣ˙ 們 -2.7
|
||||||
|
ㄇㄣˊ 門 -3.5
|
||||||
|
ㄨㄟˋ 為 -2.8
|
||||||
|
ㄨㄟˋ 位 -3.2
|
||||||
|
ㄨㄟˋ 未 -3.6
|
||||||
|
ㄨㄟˊ 為 -3.0
|
||||||
|
ㄗˇ 子 -2.8
|
||||||
|
ㄏㄜˊ 和 -2.8
|
||||||
|
ㄏㄜˊ 合 -3.4
|
||||||
|
ㄏㄜˊ 何 -3.6
|
||||||
|
ㄋㄧˇ 你 -2.8
|
||||||
|
ㄋㄧˇ 妳 -3.6
|
||||||
|
ㄉㄧˋ 地 -2.8
|
||||||
|
ㄉㄧˋ 第 -3.0
|
||||||
|
ㄉㄧˋ 弟 -3.7
|
||||||
|
ㄔㄨ 出 -2.8
|
||||||
|
ㄔㄨ 初 -3.6
|
||||||
|
ㄧㄠˋ 要 -2.8
|
||||||
|
ㄧㄠˋ 藥 -3.9
|
||||||
|
ㄧˇ 以 -2.9
|
||||||
|
ㄧˇ 已 -3.3
|
||||||
|
ㄕˊ 時 -2.9
|
||||||
|
ㄕˊ 十 -3.1
|
||||||
|
ㄕˊ 實 -3.2
|
||||||
|
ㄕˊ 食 -3.6
|
||||||
|
ㄕˊ 識 -3.7
|
||||||
|
ㄏㄨㄟˋ 會 -2.9
|
||||||
|
ㄏㄨㄟˊ 回 -3.2
|
||||||
|
ㄎㄜˇ 可 -2.9
|
||||||
|
ㄒㄧㄚˋ 下 -2.9
|
||||||
|
ㄏㄡˋ 後 -2.9
|
||||||
|
ㄏㄡˋ 候 -3.4
|
||||||
|
ㄗˋ 自 -3.0
|
||||||
|
ㄗˋ 字 -3.3
|
||||||
|
ㄋㄥˊ 能 -3.0
|
||||||
|
ㄇㄟˊ 沒 -3.0
|
||||||
|
ㄇㄟˇ 每 -3.3
|
||||||
|
ㄇㄟˇ 美 -3.2
|
||||||
|
ㄋㄚˋ 那 -3.0
|
||||||
|
ㄋㄚˇ 哪 -3.3
|
||||||
|
ㄉㄨㄛ 多 -3.0
|
||||||
|
ㄒㄧㄣ 心 -3.0
|
||||||
|
ㄒㄧㄣ 新 -3.0
|
||||||
|
ㄒㄧㄣˋ 信 -3.3
|
||||||
|
ㄒㄧㄤˇ 想 -3.0
|
||||||
|
ㄒㄧㄤˋ 向 -3.3
|
||||||
|
ㄒㄧㄤˋ 像 -3.3
|
||||||
|
ㄒㄧㄤˋ 項 -3.6
|
||||||
|
ㄑㄩˋ 去 -3.0
|
||||||
|
ㄑㄧˇ 起 -3.0
|
||||||
|
ㄑㄧ 七 -3.4
|
||||||
|
ㄑㄧ 期 -3.3
|
||||||
|
ㄑㄧˋ 氣 -3.2
|
||||||
|
ㄑㄧˋ 器 -3.6
|
||||||
|
ㄐㄧ 機 -3.1
|
||||||
|
ㄐㄧ 雞 -3.9
|
||||||
|
ㄐㄧ 基 -3.4
|
||||||
|
ㄐㄧˇ 幾 -3.2
|
||||||
|
ㄐㄧˇ 己 -3.3
|
||||||
|
ㄐㄧˊ 及 -3.4
|
||||||
|
ㄐㄧˊ 極 -3.6
|
||||||
|
ㄐㄧˋ 記 -3.4
|
||||||
|
ㄐㄧˋ 計 -3.4
|
||||||
|
ㄐㄧㄚ 家 -3.0
|
||||||
|
ㄐㄧㄚ 加 -3.3
|
||||||
|
ㄐㄧㄚˋ 價 -3.6
|
||||||
|
ㄐㄧㄢˋ 見 -3.2
|
||||||
|
ㄐㄧㄢˋ 件 -3.3
|
||||||
|
ㄐㄧㄢ 間 -3.1
|
||||||
|
ㄐㄧㄣ 今 -3.3
|
||||||
|
ㄐㄧㄣ 金 -3.4
|
||||||
|
ㄐㄧㄣˋ 進 -3.2
|
||||||
|
ㄐㄧㄣˋ 近 -3.5
|
||||||
|
ㄐㄧㄥ 經 -3.1
|
||||||
|
ㄐㄧㄥˋ 境 -3.7
|
||||||
|
ㄐㄧㄡˋ 就 -2.9
|
||||||
|
ㄐㄧㄡˇ 九 -3.5
|
||||||
|
ㄐㄧㄡˇ 久 -3.6
|
||||||
|
ㄐㄧㄠˋ 叫 -3.4
|
||||||
|
ㄐㄧㄠˋ 教 -3.4
|
||||||
|
ㄐㄧㄠ 交 -3.5
|
||||||
|
ㄐㄧㄝˇ 解 -3.4
|
||||||
|
ㄐㄧㄝˊ 結 -3.4
|
||||||
|
ㄐㄧㄝ 接 -3.5
|
||||||
|
ㄐㄧㄝ 街 -3.9
|
||||||
|
ㄐㄧㄝˋ 界 -3.5
|
||||||
|
ㄐㄩˋ 句 -3.8
|
||||||
|
ㄐㄩˋ 具 -3.6
|
||||||
|
ㄑㄧㄢˊ 前 -3.0
|
||||||
|
ㄑㄧㄢˊ 錢 -3.4
|
||||||
|
ㄑㄧㄥˇ 請 -3.2
|
||||||
|
ㄑㄧㄥ 清 -3.4
|
||||||
|
ㄑㄧㄥ 輕 -3.7
|
||||||
|
ㄑㄧㄥˊ 情 -3.2
|
||||||
|
ㄑㄩㄢˊ 全 -3.3
|
||||||
|
ㄒㄧㄝˋ 謝 -3.5
|
||||||
|
ㄒㄧㄝˇ 寫 -3.4
|
||||||
|
ㄒㄧˇ 喜 -3.5
|
||||||
|
ㄒㄧˇ 洗 -3.9
|
||||||
|
ㄒㄧ 西 -3.3
|
||||||
|
ㄒㄧ 希 -3.6
|
||||||
|
ㄒㄧˊ 習 -3.6
|
||||||
|
ㄒㄧˋ 系 -3.4
|
||||||
|
ㄒㄧㄠˇ 小 -3.0
|
||||||
|
ㄒㄧㄠˋ 笑 -3.5
|
||||||
|
ㄒㄧㄠˋ 校 -3.7
|
||||||
|
ㄒㄧㄢˋ 現 -3.1
|
||||||
|
ㄒㄧㄢ 先 -3.2
|
||||||
|
ㄒㄧㄥˊ 行 -3.1
|
||||||
|
ㄒㄧㄥˋ 性 -3.3
|
||||||
|
ㄒㄩㄝˊ 學 -3.1
|
||||||
|
ㄒㄩ 需 -3.4
|
||||||
|
ㄏㄠˇ 好 -2.8
|
||||||
|
ㄏㄠˋ 號 -3.6
|
||||||
|
ㄏㄣˇ 很 -3.0
|
||||||
|
ㄏㄞˊ 還 -3.0
|
||||||
|
ㄏㄨㄢˊ 還 -3.4
|
||||||
|
ㄏㄨㄚˋ 話 -3.2
|
||||||
|
ㄏㄨㄚˋ 化 -3.3
|
||||||
|
ㄏㄨㄚˋ 畫 -3.6
|
||||||
|
ㄏㄨㄛˊ 活 -3.4
|
||||||
|
ㄏㄨㄛˋ 或 -3.4
|
||||||
|
ㄏㄨㄛˇ 火 -3.7
|
||||||
|
ㄏㄨㄥˊ 紅 -3.7
|
||||||
|
ㄍㄨㄛˋ 過 -2.9
|
||||||
|
ㄍㄨㄥ 工 -3.2
|
||||||
|
ㄍㄨㄥ 公 -3.2
|
||||||
|
ㄍㄨㄢ 關 -3.2
|
||||||
|
ㄍㄠ 高 -3.2
|
||||||
|
ㄍㄠˋ 告 -3.6
|
||||||
|
ㄍㄣ 跟 -3.2
|
||||||
|
ㄍㄣ 根 -3.7
|
||||||
|
ㄍㄟˇ 給 -3.2
|
||||||
|
ㄍㄢˋ 幹 -3.7
|
||||||
|
ㄍㄢˇ 感 -3.4
|
||||||
|
ㄍㄢˇ 趕 -3.9
|
||||||
|
ㄎㄢˋ 看 -3.0
|
||||||
|
ㄎㄞ 開 -3.1
|
||||||
|
ㄎㄨㄞˋ 快 -3.4
|
||||||
|
ㄎㄨㄞˋ 塊 -3.8
|
||||||
|
ㄎㄜˋ 課 -3.6
|
||||||
|
ㄎㄜˋ 客 -3.6
|
||||||
|
ㄎㄡˇ 口 -3.5
|
||||||
|
ㄉㄨㄟˋ 對 -3.0
|
||||||
|
ㄉㄨㄥ 東 -3.3
|
||||||
|
ㄉㄨㄥˋ 動 -3.2
|
||||||
|
ㄉㄨㄥˇ 懂 -3.6
|
||||||
|
ㄉㄨㄢˇ 短 -3.8
|
||||||
|
ㄉㄨˊ 讀 -3.6
|
||||||
|
ㄉㄨ 都 -3.0
|
||||||
|
ㄉㄡ 都 -2.9
|
||||||
|
ㄉㄜˊ 得 -3.0
|
||||||
|
ㄉㄜ˙ 得 -3.2
|
||||||
|
ㄉㄟˇ 得 -3.6
|
||||||
|
ㄉㄤ 當 -3.2
|
||||||
|
ㄉㄢˋ 但 -3.1
|
||||||
|
ㄉㄢ 單 -3.5
|
||||||
|
ㄉㄧㄢˇ 點 -3.1
|
||||||
|
ㄉㄧㄢˋ 電 -3.1
|
||||||
|
ㄉㄧㄥˋ 定 -3.2
|
||||||
|
ㄉㄚˇ 打 -3.3
|
||||||
|
ㄉㄚˊ 答 -3.6
|
||||||
|
ㄊㄧˊ 題 -3.4
|
||||||
|
ㄊㄧˊ 提 -3.5
|
||||||
|
ㄊㄧㄢ 天 -3.0
|
||||||
|
ㄊㄧㄥ 聽 -3.4
|
||||||
|
ㄊㄨㄥˊ 同 -3.2
|
||||||
|
ㄊㄨㄥ 通 -3.4
|
||||||
|
ㄊㄡˊ 頭 -3.3
|
||||||
|
ㄊㄞˋ 太 -3.3
|
||||||
|
ㄊㄜˋ 特 -3.5
|
||||||
|
ㄋㄢˊ 南 -3.5
|
||||||
|
ㄋㄢˊ 男 -3.6
|
||||||
|
ㄋㄢˊ 難 -3.4
|
||||||
|
ㄋㄧㄢˊ 年 -3.0
|
||||||
|
ㄋㄩˇ 女 -3.4
|
||||||
|
ㄋㄟˋ 內 -3.4
|
||||||
|
ㄋㄜ˙ 呢 -3.2
|
||||||
|
ㄌㄧˇ 裡 -3.0
|
||||||
|
ㄌㄧˇ 理 -3.1
|
||||||
|
ㄌㄧˋ 力 -3.2
|
||||||
|
ㄌㄧˋ 立 -3.4
|
||||||
|
ㄌㄧˋ 利 -3.4
|
||||||
|
ㄌㄧㄤˇ 兩 -3.2
|
||||||
|
ㄌㄧㄤˋ 量 -3.4
|
||||||
|
ㄌㄧㄤˊ 涼 -3.9
|
||||||
|
ㄌㄧㄡˋ 六 -3.5
|
||||||
|
ㄌㄠˇ 老 -3.2
|
||||||
|
ㄌㄜˋ 樂 -3.5
|
||||||
|
ㄌㄨˋ 路 -3.4
|
||||||
|
ㄌㄨˋ 錄 -3.7
|
||||||
|
ㄌㄧㄢˊ 連 -3.6
|
||||||
|
ㄇㄚ 媽 -3.5
|
||||||
|
ㄇㄚ˙ 嗎 -3.0
|
||||||
|
ㄇㄚˇ 馬 -3.4
|
||||||
|
ㄇㄚˊ 麻 -3.8
|
||||||
|
ㄇㄚˋ 罵 -4.2
|
||||||
|
ㄇㄧㄥˊ 名 -3.2
|
||||||
|
ㄇㄧㄥˊ 明 -3.2
|
||||||
|
ㄇㄧㄢˋ 面 -3.2
|
||||||
|
ㄇㄧㄢˇ 免 -3.8
|
||||||
|
ㄇㄨˋ 目 -3.5
|
||||||
|
ㄇㄞˇ 買 -3.6
|
||||||
|
ㄇㄞˋ 賣 -3.8
|
||||||
|
ㄇㄢˋ 慢 -3.8
|
||||||
|
ㄇㄤˊ 忙 -3.7
|
||||||
|
ㄇㄠ 貓 -4.0
|
||||||
|
ㄈㄚ 發 -3.1
|
||||||
|
ㄈㄚˇ 法 -3.1
|
||||||
|
ㄈㄤ 方 -3.1
|
||||||
|
ㄈㄤˋ 放 -3.4
|
||||||
|
ㄈㄣ 分 -3.1
|
||||||
|
ㄈㄣˋ 份 -3.6
|
||||||
|
ㄈㄟ 飛 -3.7
|
||||||
|
ㄈㄟ 非 -3.4
|
||||||
|
ㄈㄨˋ 父 -3.7
|
||||||
|
ㄈㄨˋ 付 -3.8
|
||||||
|
ㄅㄚ 八 -3.5
|
||||||
|
ㄅㄚ 吧 -3.3
|
||||||
|
ㄅㄚ˙ 吧 -3.1
|
||||||
|
ㄅㄚˇ 把 -3.1
|
||||||
|
ㄅㄚˋ 爸 -3.6
|
||||||
|
ㄅㄞˊ 白 -3.4
|
||||||
|
ㄅㄞˇ 百 -3.5
|
||||||
|
ㄅㄟˋ 被 -3.2
|
||||||
|
ㄅㄟˇ 北 -3.4
|
||||||
|
ㄅㄠˋ 報 -3.4
|
||||||
|
ㄅㄢ 班 -3.6
|
||||||
|
ㄅㄢ 般 -3.6
|
||||||
|
ㄅㄢˋ 半 -3.6
|
||||||
|
ㄅㄢˋ 辦 -3.4
|
||||||
|
ㄅㄣˇ 本 -3.1
|
||||||
|
ㄅㄧˇ 比 -3.2
|
||||||
|
ㄅㄧˋ 必 -3.5
|
||||||
|
ㄅㄧㄢˋ 變 -3.3
|
||||||
|
ㄅㄧㄢˋ 便 -3.5
|
||||||
|
ㄅㄧㄢ 邊 -3.3
|
||||||
|
ㄅㄧㄠˇ 表 -3.4
|
||||||
|
ㄆㄧㄢˋ 片 -3.6
|
||||||
|
ㄆㄧㄢˊ 便 -3.9
|
||||||
|
ㄆㄥˊ 朋 -3.6
|
||||||
|
ㄆㄠˇ 跑 -3.7
|
||||||
|
ㄓ 之 -3.0
|
||||||
|
ㄓ 知 -3.0
|
||||||
|
ㄓ 隻 -3.6
|
||||||
|
ㄓˇ 只 -3.1
|
||||||
|
ㄓˇ 紙 -3.9
|
||||||
|
ㄓˋ 至 -3.6
|
||||||
|
ㄓˋ 制 -3.4
|
||||||
|
ㄓˋ 治 -3.5
|
||||||
|
ㄓㄥˋ 正 -3.2
|
||||||
|
ㄓㄥˋ 政 -3.4
|
||||||
|
ㄓㄨˇ 主 -3.2
|
||||||
|
ㄓㄨˋ 住 -3.5
|
||||||
|
ㄓㄨˋ 注 -3.6
|
||||||
|
ㄓㄠˇ 找 -3.4
|
||||||
|
ㄓㄢˋ 站 -3.6
|
||||||
|
ㄓㄣ 真 -3.2
|
||||||
|
ㄔ 吃 -3.4
|
||||||
|
ㄔㄤˊ 長 -3.2
|
||||||
|
ㄔㄤˊ 常 -3.2
|
||||||
|
ㄔㄤˇ 場 -3.4
|
||||||
|
ㄔㄥˊ 成 -3.1
|
||||||
|
ㄔㄥˊ 城 -3.6
|
||||||
|
ㄔㄜ 車 -3.4
|
||||||
|
ㄔㄨㄢˊ 傳 -3.6
|
||||||
|
ㄕㄥ 生 -2.9
|
||||||
|
ㄕㄥ 聲 -3.4
|
||||||
|
ㄕㄣˊ 什 -3.0
|
||||||
|
ㄕㄣˊ 神 -3.5
|
||||||
|
ㄕㄣ 身 -3.3
|
||||||
|
ㄕㄣ 深 -3.6
|
||||||
|
ㄕㄡˇ 手 -3.2
|
||||||
|
ㄕㄡˋ 受 -3.5
|
||||||
|
ㄕㄠˇ 少 -3.3
|
||||||
|
ㄕㄨ 書 -3.4
|
||||||
|
ㄕㄨˋ 數 -3.3
|
||||||
|
ㄕㄨㄟˇ 水 -3.3
|
||||||
|
ㄕㄨㄟˋ 睡 -3.8
|
||||||
|
ㄕㄨㄟˊ 誰 -3.4
|
||||||
|
ㄕㄢ 山 -3.5
|
||||||
|
ㄖˋ 日 -3.0
|
||||||
|
ㄖㄢˊ 然 -3.0
|
||||||
|
ㄖㄨˊ 如 -3.2
|
||||||
|
ㄖㄤˋ 讓 -3.3
|
||||||
|
ㄗㄨㄛˋ 做 -3.1
|
||||||
|
ㄗㄨㄛˋ 作 -3.1
|
||||||
|
ㄗㄨㄛˋ 坐 -3.7
|
||||||
|
ㄗㄨㄟˋ 最 -3.2
|
||||||
|
ㄗㄡˇ 走 -3.4
|
||||||
|
ㄗㄠˇ 早 -3.5
|
||||||
|
ㄗㄣˇ 怎 -3.3
|
||||||
|
ㄘㄞˊ 才 -3.2
|
||||||
|
ㄘㄞˋ 菜 -3.8
|
||||||
|
ㄘˋ 次 -3.2
|
||||||
|
ㄘㄨㄥˊ 從 -3.2
|
||||||
|
ㄙ 思 -3.4
|
||||||
|
ㄙ 司 -3.5
|
||||||
|
ㄙˇ 死 -3.6
|
||||||
|
ㄙˋ 四 -3.4
|
||||||
|
ㄙㄢ 三 -3.2
|
||||||
|
ㄙㄨㄛˇ 所 -3.0
|
||||||
|
ㄙㄨㄟ 雖 -3.6
|
||||||
|
ㄙㄨㄟˋ 歲 -3.8
|
||||||
|
ㄦˊ 而 -3.1
|
||||||
|
ㄦˊ 兒 -3.4
|
||||||
|
ㄦˋ 二 -3.3
|
||||||
|
ㄦˇ 耳 -3.9
|
||||||
|
ㄧˋ 意 -3.1
|
||||||
|
ㄧˋ 議 -3.6
|
||||||
|
ㄧˋ 易 -3.6
|
||||||
|
ㄧ 衣 -3.9
|
||||||
|
ㄧ 醫 -3.7
|
||||||
|
ㄧㄝˇ 也 -2.9
|
||||||
|
ㄧㄝˋ 業 -3.3
|
||||||
|
ㄧㄝˋ 夜 -3.7
|
||||||
|
ㄧㄝ˙ 耶 -4.0
|
||||||
|
ㄧㄚ 呀 -3.8
|
||||||
|
ㄧㄤˋ 樣 -3.1
|
||||||
|
ㄧㄢˊ 言 -3.5
|
||||||
|
ㄧㄢˊ 研 -3.6
|
||||||
|
ㄧㄢˇ 眼 -3.6
|
||||||
|
ㄧㄣ 因 -3.2
|
||||||
|
ㄧㄣ 音 -3.5
|
||||||
|
ㄧㄥ 應 -3.2
|
||||||
|
ㄧㄥ 英 -3.6
|
||||||
|
ㄧㄥˇ 影 -3.6
|
||||||
|
ㄧㄡˊ 由 -3.4
|
||||||
|
ㄧㄡˊ 遊 -3.7
|
||||||
|
ㄧㄡˊ 游 -3.8
|
||||||
|
ㄧㄡˇ 友 -3.7
|
||||||
|
ㄨˇ 五 -3.4
|
||||||
|
ㄨˇ 午 -3.8
|
||||||
|
ㄨˋ 物 -3.3
|
||||||
|
ㄨˋ 務 -3.5
|
||||||
|
ㄨㄣˋ 問 -3.2
|
||||||
|
ㄨㄣˊ 文 -3.2
|
||||||
|
ㄨㄢˇ 晚 -3.5
|
||||||
|
ㄨㄢˊ 完 -3.4
|
||||||
|
ㄨㄢˊ 玩 -3.7
|
||||||
|
ㄨㄤˇ 往 -3.6
|
||||||
|
ㄨㄤˋ 望 -3.6
|
||||||
|
ㄨㄤˋ 忘 -3.8
|
||||||
|
ㄩˇ 與 -3.3
|
||||||
|
ㄩˇ 語 -3.5
|
||||||
|
ㄩˇ 雨 -3.8
|
||||||
|
ㄩㄢˊ 元 -3.4
|
||||||
|
ㄩㄢˊ 原 -3.3
|
||||||
|
ㄩㄢˋ 願 -3.8
|
||||||
|
ㄩㄢˇ 遠 -3.7
|
||||||
|
ㄩㄝˋ 月 -3.2
|
||||||
|
ㄩㄝˋ 越 -3.6
|
||||||
|
ㄩㄥˋ 用 -3.0
|
||||||
|
ㄚ 啊 -3.3
|
||||||
|
ㄚ˙ 啊 -3.2
|
||||||
|
ㄛ 喔 -3.6
|
||||||
|
ㄜˋ 餓 -4.2
|
||||||
|
ㄞˋ 愛 -3.3
|
||||||
|
ㄢ 安 -3.5
|
||||||
|
ㄣ 嗯 -3.7
|
||||||
|
ㄟ 欸 -3.9
|
||||||
|
|
||||||
|
# --- phrases ---
|
||||||
|
ㄋㄧˇ-ㄏㄠˇ 你好 -3.6
|
||||||
|
ㄨㄛˇ-ㄇㄣ˙ 我們 -3.2
|
||||||
|
ㄋㄧˇ-ㄇㄣ˙ 你們 -3.6
|
||||||
|
ㄊㄚ-ㄇㄣ˙ 他們 -3.4
|
||||||
|
ㄕˊ-ㄏㄡˋ 時候 -3.4
|
||||||
|
ㄕˊ-ㄐㄧㄢ 時間 -3.5
|
||||||
|
ㄒㄧㄢˋ-ㄗㄞˋ 現在 -3.4
|
||||||
|
ㄐㄧㄣ-ㄊㄧㄢ 今天 -3.6
|
||||||
|
ㄇㄧㄥˊ-ㄊㄧㄢ 明天 -3.8
|
||||||
|
ㄗㄨㄛˊ-ㄊㄧㄢ 昨天 -3.9
|
||||||
|
ㄕㄣˊ-ㄇㄜ˙ 什麼 -3.3
|
||||||
|
ㄗㄣˇ-ㄇㄜ˙ 怎麼 -3.4
|
||||||
|
ㄨㄟˋ-ㄕㄣˊ-ㄇㄜ˙ 為什麼 -3.8
|
||||||
|
ㄎㄜˇ-ㄧˇ 可以 -3.4
|
||||||
|
ㄒㄧㄤˇ-ㄧㄠˋ 想要 -4.0
|
||||||
|
ㄓ-ㄉㄠˋ 知道 -3.5
|
||||||
|
ㄒㄧㄝˋ-ㄒㄧㄝ˙ 謝謝 -3.7
|
||||||
|
ㄅㄨˋ-ㄏㄠˇ-ㄧˋ-ㄙ˙ 不好意思 -4.3
|
||||||
|
ㄉㄨㄟˋ-ㄅㄨˋ-ㄑㄧˇ 對不起 -4.2
|
||||||
|
ㄇㄟˊ-ㄍㄨㄢ-ㄒㄧˋ 沒關係 -4.3
|
||||||
|
ㄇㄟˊ-ㄧㄡˇ 沒有 -3.4
|
||||||
|
ㄧㄡˇ-ㄇㄟˊ-ㄧㄡˇ 有沒有 -4.3
|
||||||
|
ㄏㄞˊ-ㄕˋ 還是 -3.7
|
||||||
|
ㄉㄢˋ-ㄕˋ 但是 -3.6
|
||||||
|
ㄙㄨㄛˇ-ㄧˇ 所以 -3.5
|
||||||
|
ㄧㄣ-ㄨㄟˋ 因為 -3.5
|
||||||
|
ㄖㄨˊ-ㄍㄨㄛˇ 如果 -3.7
|
||||||
|
ㄖㄢˊ-ㄏㄡˋ 然後 -3.6
|
||||||
|
ㄧˇ-ㄐㄧㄥ 已經 -3.6
|
||||||
|
ㄧ-ㄧㄤˋ 一樣 -4.0
|
||||||
|
ㄧ-ㄒㄧㄚˋ 一下 -3.8
|
||||||
|
ㄧˊ-ㄒㄧㄚˋ 一下 -3.8
|
||||||
|
ㄧ-ㄑㄧˇ 一起 -3.8
|
||||||
|
ㄧ-ㄉㄧㄢˇ 一點 -3.9
|
||||||
|
ㄧ-ㄉㄧㄥˋ 一定 -3.9
|
||||||
|
ㄧˊ-ㄉㄧㄥˋ 一定 -3.8
|
||||||
|
ㄧ-ㄍㄜˋ 一個 -3.6
|
||||||
|
ㄧˊ-ㄍㄜˋ 一個 -3.5
|
||||||
|
ㄓㄜˋ-ㄍㄜˋ 這個 -3.5
|
||||||
|
ㄋㄚˋ-ㄍㄜˋ 那個 -3.6
|
||||||
|
ㄋㄚˇ-ㄍㄜˋ 哪個 -4.2
|
||||||
|
ㄓㄜˋ-ㄧㄤˋ 這樣 -3.7
|
||||||
|
ㄋㄚˋ-ㄧㄤˋ 那樣 -4.4
|
||||||
|
ㄓㄜˋ-ㄌㄧˇ 這裡 -4.1
|
||||||
|
ㄋㄚˋ-ㄌㄧˇ 那裡 -4.3
|
||||||
|
ㄋㄚˇ-ㄌㄧˇ 哪裡 -4.2
|
||||||
|
ㄗˋ-ㄐㄧˇ 自己 -3.6
|
||||||
|
ㄆㄥˊ-ㄧㄡˇ 朋友 -3.9
|
||||||
|
ㄍㄨㄥ-ㄗㄨㄛˋ 工作 -3.7
|
||||||
|
ㄍㄨㄥ-ㄙ 公司 -3.7
|
||||||
|
ㄨㄣˋ-ㄊㄧˊ 問題 -3.6
|
||||||
|
ㄉㄧㄢˋ-ㄋㄠˇ 電腦 -4.0
|
||||||
|
ㄉㄧㄢˋ-ㄏㄨㄚˋ 電話 -4.1
|
||||||
|
ㄕㄡˇ-ㄐㄧ 手機 -4.0
|
||||||
|
ㄓㄨㄥ-ㄨㄣˊ 中文 -4.1
|
||||||
|
ㄧㄥ-ㄨㄣˊ 英文 -4.1
|
||||||
|
ㄊㄞˊ-ㄨㄢ 台灣 -3.8
|
||||||
|
ㄊㄞˊ-ㄅㄟˇ 台北 -4.1
|
||||||
|
ㄓㄨㄥ-ㄍㄨㄛˊ 中國 -3.9
|
||||||
|
ㄕㄨ-ㄖㄨˋ 輸入 -4.3
|
||||||
|
ㄕㄨ-ㄖㄨˋ-ㄈㄚˇ 輸入法 -4.6
|
||||||
|
ㄓㄨˋ-ㄧㄣ 注音 -4.6
|
||||||
|
ㄒㄩㄝˊ-ㄒㄧˊ 學習 -4.1
|
||||||
|
ㄒㄩㄝˊ-ㄕㄥ 學生 -4.0
|
||||||
|
ㄒㄩㄝˊ-ㄒㄧㄠˋ 學校 -4.1
|
||||||
|
ㄌㄠˇ-ㄕ 老師 -4.0
|
||||||
|
ㄕˋ-ㄑㄧㄥˊ 事情 -3.9
|
||||||
|
ㄕㄥ-ㄏㄨㄛˊ 生活 -3.9
|
||||||
|
ㄍㄨㄢ-ㄒㄧˋ 關係 -3.9
|
||||||
|
ㄉㄨㄥ-ㄒㄧ 東西 -3.9
|
||||||
|
ㄉㄚˋ-ㄐㄧㄚ 大家 -3.7
|
||||||
|
ㄒㄧˇ-ㄏㄨㄢ 喜歡 -3.8
|
||||||
|
ㄐㄩㄝˊ-ㄉㄜˊ 覺得 -3.6
|
||||||
|
ㄎㄜˇ-ㄋㄥˊ 可能 -3.6
|
||||||
|
ㄧㄥ-ㄍㄞ 應該 -3.7
|
||||||
|
ㄒㄩ-ㄧㄠˋ 需要 -3.7
|
||||||
|
ㄎㄞ-ㄕˇ 開始 -3.7
|
||||||
|
ㄐㄧㄝˊ-ㄕㄨˋ 結束 -4.2
|
||||||
|
ㄐㄧㄝˊ-ㄍㄨㄛˇ 結果 -4.0
|
||||||
|
ㄧˇ-ㄏㄡˋ 以後 -4.0
|
||||||
|
ㄧˇ-ㄑㄧㄢˊ 以前 -4.0
|
||||||
|
ㄓ-ㄑㄧㄢˊ 之前 -4.0
|
||||||
|
ㄓ-ㄏㄡˋ 之後 -3.9
|
||||||
|
ㄏㄣˇ-ㄉㄨㄛ 很多 -4.0
|
||||||
|
ㄓㄣ-ㄉㄜ˙ 真的 -3.7
|
||||||
|
ㄉㄤ-ㄖㄢˊ 當然 -4.0
|
||||||
|
ㄐㄧㄚ-ㄧㄡˊ 加油 -4.4
|
||||||
|
ㄏㄠˇ-ㄉㄜ˙ 好的 -3.9
|
||||||
|
ㄇㄧㄥˊ-ㄅㄞˊ 明白 -4.2
|
||||||
|
ㄉㄧˋ-ㄈㄤ 地方 -3.9
|
||||||
|
ㄈㄤ-ㄈㄚˇ 方法 -4.0
|
||||||
|
ㄖㄣˊ-ㄇㄣ˙ 人們 -4.3
|
||||||
|
ㄧ-ㄕㄥ 醫生 -4.3
|
||||||
|
ㄧ-ㄩㄢˋ 醫院 -4.3
|
||||||
|
ㄏㄨㄟˊ-ㄐㄧㄚ 回家 -4.3
|
||||||
|
ㄔ-ㄈㄢˋ 吃飯 -4.3
|
||||||
|
ㄕㄨㄟˋ-ㄐㄧㄠˋ 睡覺 -4.4
|
||||||
|
ㄕㄤˋ-ㄅㄢ 上班 -4.3
|
||||||
|
ㄒㄧㄚˋ-ㄅㄢ 下班 -4.4
|
||||||
|
ㄕㄤˋ-ㄨˇ 上午 -4.3
|
||||||
|
ㄒㄧㄚˋ-ㄨˇ 下午 -4.2
|
||||||
|
ㄨㄢˇ-ㄕㄤˋ 晚上 -4.1
|
||||||
|
ㄗㄠˇ-ㄕㄤˋ 早上 -4.2
|
||||||
|
ㄗㄠˇ-ㄢ 早安 -4.6
|
||||||
|
ㄨㄢˇ-ㄢ 晚安 -4.6
|
||||||
|
ㄒㄧㄥ-ㄑㄧ 星期 -4.2
|
||||||
|
ㄌㄧˇ-ㄅㄞˋ 禮拜 -4.3
|
||||||
|
ㄇㄚ-ㄇㄚ˙ 媽媽 -4.2
|
||||||
|
ㄅㄚˋ-ㄅㄚ˙ 爸爸 -4.2
|
||||||
|
ㄏㄞˊ-ㄗ˙ 孩子 -4.0
|
||||||
|
ㄒㄧㄠˇ-ㄏㄞˊ 小孩 -4.3
|
||||||
|
ㄖㄣˋ-ㄨㄟˊ 認為 -4.0
|
||||||
|
ㄖㄣˋ-ㄕˋ 認識 -4.2
|
||||||
|
ㄐㄧˋ-ㄉㄜˊ 記得 -4.2
|
||||||
|
ㄐㄧㄝˇ-ㄐㄩㄝˊ 解決 -4.1
|
||||||
|
ㄉㄚˇ-ㄙㄨㄢˋ 打算 -4.3
|
||||||
|
ㄐㄧ-ㄏㄨㄟˋ 機會 -4.1
|
||||||
|
ㄒㄧㄣ-ㄑㄧㄥˊ 心情 -4.3
|
||||||
|
ㄍㄠ-ㄒㄧㄥˋ 高興 -4.3
|
||||||
|
ㄎㄞ-ㄒㄧㄣ 開心 -4.3
|
||||||
|
ㄓㄨㄥˋ-ㄧㄠˋ 重要 -3.9
|
||||||
|
ㄐㄧㄢˇ-ㄉㄢ 簡單 -4.2
|
||||||
|
ㄈㄨˋ-ㄗㄚˊ 複雜 -4.4
|
||||||
|
ㄓㄥˋ-ㄑㄩㄝˋ 正確 -4.3
|
||||||
|
ㄗ-ㄌㄧㄠˋ 資料 -4.1
|
||||||
|
ㄒㄧˋ-ㄊㄨㄥˇ 系統 -4.1
|
||||||
|
ㄔㄥˊ-ㄕˋ 程式 -4.4
|
||||||
|
ㄖㄣˊ-ㄍㄨㄥ-ㄓˋ-ㄏㄨㄟˋ 人工智慧 -4.8
|
||||||
|
ㄗˋ-ㄉㄨㄥˋ 自動 -4.3
|
||||||
|
ㄐㄧㄠˋ-ㄓㄥˋ 校正 -4.8
|
||||||
|
ㄑㄧㄝ-ㄏㄨㄢˋ 切換 -4.6
|
||||||
|
ㄉㄧㄢˋ-ㄧㄥˇ 電影 -4.3
|
||||||
|
ㄧㄣ-ㄩㄝˋ 音樂 -4.3
|
||||||
|
ㄌㄩˇ-ㄒㄧㄥˊ 旅行 -4.4
|
||||||
|
ㄎㄚ-ㄈㄟ 咖啡 -4.4
|
||||||
|
ㄊㄧㄢ-ㄑㄧˋ 天氣 -4.3
|
||||||
|
ㄨㄣˋ-ㄏㄠˇ 問好 -5.0
|
||||||
+172782
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,153 @@
|
|||||||
|
import Cocoa
|
||||||
|
import InputMethodKit
|
||||||
|
import AutoZhuyinCore
|
||||||
|
|
||||||
|
/// Resources shared by every client connection.
|
||||||
|
enum Shared {
|
||||||
|
static var server: IMKServer!
|
||||||
|
static var candidates: IMKCandidates!
|
||||||
|
|
||||||
|
static let learnedKey = "LearnedPreferences"
|
||||||
|
|
||||||
|
static let classifier: Classifier = {
|
||||||
|
let bundle = Bundle.main
|
||||||
|
let lexicon = Lexicon()
|
||||||
|
if let url = bundle.url(forResource: "lexicon", withExtension: "txt"),
|
||||||
|
let text = try? String(contentsOf: url, encoding: .utf8) {
|
||||||
|
lexicon.load(text)
|
||||||
|
}
|
||||||
|
// Optional user phrases: ~/Library/Application Support/AutoZhuyin/user-phrases.txt
|
||||||
|
if let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first {
|
||||||
|
let userFile = support.appendingPathComponent("AutoZhuyin/user-phrases.txt")
|
||||||
|
if let text = try? String(contentsOf: userFile, encoding: .utf8) { lexicon.load(text) }
|
||||||
|
}
|
||||||
|
let english = EnglishModel(commonWordsURL: bundle.url(forResource: "english-common", withExtension: "txt"))
|
||||||
|
let saved = UserDefaults.standard.dictionary(forKey: learnedKey) as? [String: Int] ?? [:]
|
||||||
|
let learned = LearnedPreferences(weights: saved) { weights in
|
||||||
|
UserDefaults.standard.set(weights, forKey: learnedKey)
|
||||||
|
}
|
||||||
|
return Classifier(lexicon: lexicon, english: english, learned: learned)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc(AutoZhuyinInputController)
|
||||||
|
final class InputController: IMKInputController {
|
||||||
|
private let engine = CompositionEngine(classifier: Shared.classifier)
|
||||||
|
|
||||||
|
// MARK: - Key events
|
||||||
|
|
||||||
|
override func recognizedEvents(_ sender: Any!) -> Int {
|
||||||
|
Int(NSEvent.EventTypeMask.keyDown.rawValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
override func handle(_ event: NSEvent!, client sender: Any!) -> Bool {
|
||||||
|
guard let event, event.type == .keyDown, let client = sender as? IMKTextInput else { return false }
|
||||||
|
|
||||||
|
// Shortcuts (⌘C, ⌃A, ⌥…) go to the app; commit any composition first.
|
||||||
|
if !event.modifierFlags.intersection([.command, .control, .option]).isEmpty {
|
||||||
|
commit(engine.commitAll(), to: client)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// While the candidate panel is up, let it handle navigation keys itself.
|
||||||
|
if engine.isShowingCandidates, [125, 126, 123, 124, 116, 121, 36, 76].contains(event.keyCode) {
|
||||||
|
Shared.candidates.interpretKeyEvents([event])
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
guard let key = keyInput(for: event) else { return false }
|
||||||
|
let result = engine.handle(key)
|
||||||
|
if let text = result.commit { commit(text, to: client) }
|
||||||
|
updateComposition(client)
|
||||||
|
return result.handled
|
||||||
|
}
|
||||||
|
|
||||||
|
private func keyInput(for event: NSEvent) -> KeyInput? {
|
||||||
|
switch event.keyCode {
|
||||||
|
case 51: return .backspace
|
||||||
|
case 36, 76: return .enter
|
||||||
|
case 53: return .escape
|
||||||
|
case 48: return .tab
|
||||||
|
case 125: return .down
|
||||||
|
case 126: return .up
|
||||||
|
case 123: return .left
|
||||||
|
case 124: return .right
|
||||||
|
default:
|
||||||
|
guard let c = event.characters?.first, !c.isNewline else { return nil }
|
||||||
|
// Caps Lock without Shift: treat as lowercase so Zhuyin still works.
|
||||||
|
if event.modifierFlags.contains(.capsLock) && !event.modifierFlags.contains(.shift) {
|
||||||
|
return .character(Character(c.lowercased()))
|
||||||
|
}
|
||||||
|
return .character(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Client updates
|
||||||
|
|
||||||
|
private func commit(_ text: String, to client: IMKTextInput) {
|
||||||
|
guard !text.isEmpty else { return }
|
||||||
|
client.insertText(text, replacementRange: NSRange(location: NSNotFound, length: 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
private func updateComposition(_ client: IMKTextInput) {
|
||||||
|
let text = engine.markedText
|
||||||
|
let attrs: [NSAttributedString.Key: Any] = [
|
||||||
|
.underlineStyle: NSUnderlineStyle.single.rawValue,
|
||||||
|
// Literal (English) composition is shown in a different colour as a hint.
|
||||||
|
.foregroundColor: engine.mode == .literal ? NSColor.systemBlue : NSColor.textColor,
|
||||||
|
]
|
||||||
|
let marked = NSAttributedString(string: text, attributes: text.isEmpty ? [:] : attrs)
|
||||||
|
client.setMarkedText(marked,
|
||||||
|
selectionRange: NSRange(location: (text as NSString).length, length: 0),
|
||||||
|
replacementRange: NSRange(location: NSNotFound, length: 0))
|
||||||
|
|
||||||
|
if engine.isShowingCandidates {
|
||||||
|
Shared.candidates.update()
|
||||||
|
Shared.candidates.show(kIMKLocateCandidatesBelowHint)
|
||||||
|
} else {
|
||||||
|
Shared.candidates.hide()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override func commitComposition(_ sender: Any!) {
|
||||||
|
guard let client = sender as? IMKTextInput else { return }
|
||||||
|
commit(engine.commitAll(), to: client)
|
||||||
|
Shared.candidates.hide()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func deactivateServer(_ sender: Any!) {
|
||||||
|
commitComposition(sender)
|
||||||
|
super.deactivateServer(sender)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Candidate panel
|
||||||
|
|
||||||
|
override func candidates(_ sender: Any!) -> [Any]! {
|
||||||
|
engine.candidates.map(\.text)
|
||||||
|
}
|
||||||
|
|
||||||
|
override func candidateSelectionChanged(_ candidateString: NSAttributedString!) {
|
||||||
|
if let s = candidateString?.string, let i = engine.candidates.firstIndex(where: { $0.text == s }) {
|
||||||
|
engine.candidateIndex = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override func candidateSelected(_ candidateString: NSAttributedString!) {
|
||||||
|
guard let s = candidateString?.string,
|
||||||
|
let i = engine.candidates.firstIndex(where: { $0.text == s }) else { return }
|
||||||
|
engine.selectCandidate(i)
|
||||||
|
if let client = client() { updateComposition(client) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Menu
|
||||||
|
|
||||||
|
override func menu() -> NSMenu! {
|
||||||
|
let menu = NSMenu()
|
||||||
|
menu.addItem(withTitle: "清除學習紀錄", action: #selector(clearLearned(_:)), keyEquivalent: "")
|
||||||
|
return menu
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func clearLearned(_ sender: Any?) {
|
||||||
|
Shared.classifier.learned.clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import Carbon
|
||||||
|
import Cocoa
|
||||||
|
import InputMethodKit
|
||||||
|
|
||||||
|
// `AutoZhuyin --register`: register this bundle with Text Input Sources so it shows up
|
||||||
|
// in System Settings without logging out (used by the installer's postinstall script).
|
||||||
|
if CommandLine.arguments.contains("--register") {
|
||||||
|
let status = TISRegisterInputSource(Bundle.main.bundleURL as CFURL)
|
||||||
|
print(status == noErr ? "Registered \(Bundle.main.bundlePath)" : "TISRegisterInputSource failed: \(status)")
|
||||||
|
exit(status == noErr ? 0 : 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entry point of the input method server. macOS launches this process when the
|
||||||
|
// input method is selected; IMKServer then creates one InputController per client.
|
||||||
|
guard let connectionName = Bundle.main.infoDictionary?["InputMethodConnectionName"] as? String,
|
||||||
|
let server = IMKServer(name: connectionName, bundleIdentifier: Bundle.main.bundleIdentifier)
|
||||||
|
else {
|
||||||
|
NSLog("AutoZhuyin: failed to start IMKServer (is this running from the .app bundle?)")
|
||||||
|
exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
Shared.server = server
|
||||||
|
Shared.candidates = IMKCandidates(server: server, panelType: kIMKSingleColumnScrollingCandidatePanel)
|
||||||
|
_ = Shared.classifier // load the lexicon now rather than on the first keystroke
|
||||||
|
|
||||||
|
NSApplication.shared.run()
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Slot a Bopomofo symbol occupies inside a syllable.
|
||||||
|
public enum BopomofoSlot: Int, Comparable {
|
||||||
|
case initial = 0, medial = 1, final = 2
|
||||||
|
|
||||||
|
public static func < (a: BopomofoSlot, b: BopomofoSlot) -> Bool { a.rawValue < b.rawValue }
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum Tone: Int {
|
||||||
|
case first = 1, second, third, fourth, neutral
|
||||||
|
|
||||||
|
/// Mark appended to a reading. First tone is written without a mark.
|
||||||
|
public var mark: String {
|
||||||
|
switch self {
|
||||||
|
case .first: return ""
|
||||||
|
case .second: return "ˊ"
|
||||||
|
case .third: return "ˇ"
|
||||||
|
case .fourth: return "ˋ"
|
||||||
|
case .neutral: return "˙"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Standard Taiwanese "大千" (Dachen) keyboard layout.
|
||||||
|
public enum DachenLayout {
|
||||||
|
public static let symbols: [Character: Character] = [
|
||||||
|
"1": "ㄅ", "q": "ㄆ", "a": "ㄇ", "z": "ㄈ",
|
||||||
|
"2": "ㄉ", "w": "ㄊ", "s": "ㄋ", "x": "ㄌ",
|
||||||
|
"e": "ㄍ", "d": "ㄎ", "c": "ㄏ",
|
||||||
|
"r": "ㄐ", "f": "ㄑ", "v": "ㄒ",
|
||||||
|
"5": "ㄓ", "t": "ㄔ", "g": "ㄕ", "b": "ㄖ",
|
||||||
|
"y": "ㄗ", "h": "ㄘ", "n": "ㄙ",
|
||||||
|
"u": "ㄧ", "j": "ㄨ", "m": "ㄩ",
|
||||||
|
"8": "ㄚ", "i": "ㄛ", "k": "ㄜ", ",": "ㄝ",
|
||||||
|
"9": "ㄞ", "o": "ㄟ", "l": "ㄠ", ".": "ㄡ",
|
||||||
|
"0": "ㄢ", "p": "ㄣ", ";": "ㄤ", "/": "ㄥ", "-": "ㄦ",
|
||||||
|
]
|
||||||
|
|
||||||
|
public static let tones: [Character: Tone] = [
|
||||||
|
" ": .first, "6": .second, "3": .third, "4": .fourth, "7": .neutral,
|
||||||
|
]
|
||||||
|
|
||||||
|
/// Every key that has a meaning in Zhuyin mode.
|
||||||
|
public static func isZhuyinKey(_ c: Character) -> Bool {
|
||||||
|
symbols[c] != nil || tones[c] != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
static let initials: Set<Character> = Set("ㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐㄑㄒㄓㄔㄕㄖㄗㄘㄙ")
|
||||||
|
static let medials: Set<Character> = Set("ㄧㄨㄩ")
|
||||||
|
|
||||||
|
public static func slot(of symbol: Character) -> BopomofoSlot {
|
||||||
|
if initials.contains(symbol) { return .initial }
|
||||||
|
if medials.contains(symbol) { return .medial }
|
||||||
|
return .final
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One syllable as composed from keystrokes.
|
||||||
|
public struct Syllable: Equatable {
|
||||||
|
public var initial: Character?
|
||||||
|
public var medial: Character?
|
||||||
|
public var final: Character?
|
||||||
|
public var tone: Tone?
|
||||||
|
|
||||||
|
public init(initial: Character? = nil, medial: Character? = nil, final: Character? = nil, tone: Tone? = nil) {
|
||||||
|
self.initial = initial
|
||||||
|
self.medial = medial
|
||||||
|
self.final = final
|
||||||
|
self.tone = tone
|
||||||
|
}
|
||||||
|
|
||||||
|
public var isEmpty: Bool { initial == nil && medial == nil && final == nil }
|
||||||
|
|
||||||
|
/// Bopomofo without tone, e.g. "ㄋㄧ".
|
||||||
|
public var toneless: String {
|
||||||
|
String([initial, medial, final].compactMap { $0 })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reading with tone mark, e.g. "ㄋㄧˇ". Untoned syllables return just the symbols.
|
||||||
|
public var reading: String { toneless + (tone?.mark ?? "") }
|
||||||
|
|
||||||
|
public func filled(_ slot: BopomofoSlot) -> Bool {
|
||||||
|
switch slot {
|
||||||
|
case .initial: return initial != nil
|
||||||
|
case .medial: return medial != nil
|
||||||
|
case .final: return final != nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public mutating func set(_ symbol: Character, in slot: BopomofoSlot) {
|
||||||
|
switch slot {
|
||||||
|
case .initial: initial = symbol
|
||||||
|
case .medial: medial = symbol
|
||||||
|
case .final: final = symbol
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
public enum InputMode: String, Codable {
|
||||||
|
/// Keys are Dachen Zhuyin and get converted to Chinese.
|
||||||
|
case zhuyin
|
||||||
|
/// Keys are output as typed (English words, numbers).
|
||||||
|
case literal
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct Classification {
|
||||||
|
public var mode: InputMode
|
||||||
|
public var zhuyinScore: Double
|
||||||
|
public var literalScore: Double
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remembers the user's corrections (Tab toggles) per key sequence.
|
||||||
|
public final class LearnedPreferences {
|
||||||
|
/// Positive = prefers Zhuyin, negative = prefers literal.
|
||||||
|
public private(set) var weights: [String: Int]
|
||||||
|
private let onChange: ([String: Int]) -> Void
|
||||||
|
|
||||||
|
public init(weights: [String: Int] = [:], onChange: @escaping ([String: Int]) -> Void = { _ in }) {
|
||||||
|
self.weights = weights
|
||||||
|
self.onChange = onChange
|
||||||
|
}
|
||||||
|
|
||||||
|
public func record(_ keys: String, as mode: InputMode) {
|
||||||
|
let delta = mode == .zhuyin ? 1 : -1
|
||||||
|
weights[keys] = max(-3, min(3, (weights[keys] ?? 0) + delta))
|
||||||
|
onChange(weights)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func clear() {
|
||||||
|
weights = [:]
|
||||||
|
onChange(weights)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func bias(for keys: String) -> Double { Double(weights[keys] ?? 0) * 4 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decides whether a key sequence is Zhuyin or literal (English / numbers).
|
||||||
|
public final class Classifier {
|
||||||
|
public let lexicon: Lexicon
|
||||||
|
public let english: EnglishModel
|
||||||
|
public let learned: LearnedPreferences
|
||||||
|
|
||||||
|
/// Traditional-Chinese users type Zhuyin most of the time: a small prior toward it.
|
||||||
|
public var zhuyinPrior = 0.5
|
||||||
|
/// How much the previous segment's mode pulls the current one.
|
||||||
|
public var contextWeight = 1.5
|
||||||
|
|
||||||
|
public init(lexicon: Lexicon, english: EnglishModel, learned: LearnedPreferences = LearnedPreferences()) {
|
||||||
|
self.lexicon = lexicon
|
||||||
|
self.english = english
|
||||||
|
self.learned = learned
|
||||||
|
}
|
||||||
|
|
||||||
|
/// - Parameters:
|
||||||
|
/// - finishing: the user pressed space. Zhuyin is scored as if the space were a
|
||||||
|
/// first-tone key; literal is scored as a completed word.
|
||||||
|
/// - previous: mode of the previously committed segment, if recent.
|
||||||
|
public func classify(_ keys: [Character], finishing: Bool = false, previous: InputMode? = nil) -> Classification {
|
||||||
|
var zh = zhuyinScore(finishing ? keys + [" "] : keys) + zhuyinPrior
|
||||||
|
var lit = literalScore(keys, complete: finishing)
|
||||||
|
switch previous {
|
||||||
|
case .zhuyin?: zh += contextWeight
|
||||||
|
case .literal?: lit += contextWeight
|
||||||
|
case nil: break
|
||||||
|
}
|
||||||
|
let learnedBias = learned.bias(for: String(keys))
|
||||||
|
if learnedBias > 0 { zh += learnedBias } else { lit -= learnedBias }
|
||||||
|
return Classification(mode: zh >= lit ? .zhuyin : .literal, zhuyinScore: zh, literalScore: lit)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func zhuyinScore(_ keys: [Character]) -> Double {
|
||||||
|
let parse = ZhuyinParser.parse(keys)
|
||||||
|
if parse.foreignKeys > 0 || parse.syllables.isEmpty { return -.infinity }
|
||||||
|
var s = -5.0 * Double(parse.strayTones)
|
||||||
|
for (i, p) in parse.syllables.enumerated() {
|
||||||
|
let isLast = i == parse.syllables.count - 1
|
||||||
|
// Out-of-order typing is accepted, but is weaker evidence than normal Zhuyin.
|
||||||
|
if p.reordered { s -= 0.5 }
|
||||||
|
let valid = SyllableTable.isValid(p.syllable)
|
||||||
|
if p.toned {
|
||||||
|
if valid {
|
||||||
|
s += 2 + (lexicon.bestScore(for: p.syllable) != nil ? 0.8 : -1.5)
|
||||||
|
} else {
|
||||||
|
s -= 5
|
||||||
|
}
|
||||||
|
} else if isLast {
|
||||||
|
s += SyllableTable.isValidPrefix(p.syllable) ? 0 : -5
|
||||||
|
} else {
|
||||||
|
// Untoned syllable in the middle: allowed (tone omission) but unusual.
|
||||||
|
s += valid ? -2.5 : -5
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
public func literalScore(_ keys: [Character], complete: Bool) -> Double {
|
||||||
|
if keys.isEmpty || keys.contains(" ") { return -.infinity }
|
||||||
|
var score = 0.0
|
||||||
|
if keys.contains(where: { $0.isUppercase }) { score += 20 } // Shift = clearly English
|
||||||
|
|
||||||
|
let letters = String(keys.filter { $0.isLetter })
|
||||||
|
let digits = keys.filter { $0.isNumber }.count
|
||||||
|
let others = keys.count - letters.count - digits
|
||||||
|
|
||||||
|
if letters.isEmpty {
|
||||||
|
// Pure number like "2024" (with possible "." or ",").
|
||||||
|
return score + 0.8 * Double(digits) - 1.0 * Double(others)
|
||||||
|
}
|
||||||
|
score += english.score(letters, complete: complete || digits > 0)
|
||||||
|
score -= 1.5 * Double(digits)
|
||||||
|
// `'` inside a word (don't) is fine; Zhuyin punctuation keys inside a word are not.
|
||||||
|
let apostrophes = keys.filter { $0 == "'" }.count
|
||||||
|
score -= 1.5 * Double(others - apostrophes)
|
||||||
|
return score
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
public enum KeyInput: Equatable {
|
||||||
|
case character(Character)
|
||||||
|
case backspace, enter, escape, tab
|
||||||
|
case up, down, left, right
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct KeyResult: Equatable {
|
||||||
|
/// false → the key should go to the app untouched.
|
||||||
|
public var handled: Bool
|
||||||
|
/// Text to insert into the app (finalised), if any.
|
||||||
|
public var commit: String?
|
||||||
|
|
||||||
|
public static let passThrough = KeyResult(handled: false, commit: nil)
|
||||||
|
public static let consumed = KeyResult(handled: true, commit: nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole input-method state machine, independent of InputMethodKit.
|
||||||
|
///
|
||||||
|
/// Keystrokes accumulate in a buffer. On every key the classifier decides whether the
|
||||||
|
/// buffer is Zhuyin or literal text; the composition (marked text) shows the result
|
||||||
|
/// live. Space / Enter / punctuation commit it. Tab flips the decision and the
|
||||||
|
/// correction is learned.
|
||||||
|
public final class CompositionEngine {
|
||||||
|
public let classifier: Classifier
|
||||||
|
public let converter: Converter
|
||||||
|
|
||||||
|
public private(set) var keys: [Character] = []
|
||||||
|
/// Set by Tab: overrides the classifier for the current buffer.
|
||||||
|
public private(set) var forcedMode: InputMode?
|
||||||
|
/// User-picked phrases, by syllable range.
|
||||||
|
public private(set) var fixed: [Range<Int>: String] = [:]
|
||||||
|
public private(set) var candidates: [Candidate] = []
|
||||||
|
public var candidateIndex = 0
|
||||||
|
public var isShowingCandidates: Bool { !candidates.isEmpty }
|
||||||
|
|
||||||
|
private var previousMode: InputMode?
|
||||||
|
private var previousCommitTime = Date.distantPast
|
||||||
|
/// How long the previous segment's mode keeps influencing the next one.
|
||||||
|
public var contextWindow: TimeInterval = 20
|
||||||
|
public var now: () -> Date = Date.init
|
||||||
|
|
||||||
|
public init(classifier: Classifier) {
|
||||||
|
self.classifier = classifier
|
||||||
|
self.converter = Converter(lexicon: classifier.lexicon)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Derived state
|
||||||
|
|
||||||
|
private var context: InputMode? {
|
||||||
|
now().timeIntervalSince(previousCommitTime) < contextWindow ? previousMode : nil
|
||||||
|
}
|
||||||
|
|
||||||
|
public var mode: InputMode {
|
||||||
|
forcedMode ?? classifier.classify(keys, previous: context).mode
|
||||||
|
}
|
||||||
|
|
||||||
|
public var parse: ZhuyinParse { ZhuyinParser.parse(keys) }
|
||||||
|
|
||||||
|
/// What to show underlined in the app while composing.
|
||||||
|
public var markedText: String {
|
||||||
|
guard !keys.isEmpty else { return "" }
|
||||||
|
switch mode {
|
||||||
|
case .literal:
|
||||||
|
return String(keys)
|
||||||
|
case .zhuyin:
|
||||||
|
let p = parse
|
||||||
|
let done = converter.convert(p.completed.map(\.syllable), fixed: validFixed(p)).map(\.text).joined()
|
||||||
|
return done + (p.pending?.syllable.reading ?? "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func validFixed(_ p: ZhuyinParse) -> [Range<Int>: String] {
|
||||||
|
fixed.filter { $0.key.upperBound <= p.completed.count }
|
||||||
|
}
|
||||||
|
|
||||||
|
private func zhuyinCommitText() -> String {
|
||||||
|
let p = parse
|
||||||
|
// An unfinished trailing syllable is converted as untoned.
|
||||||
|
return converter.convert(p.syllables.map(\.syllable), fixed: validFixed(p)).map(\.text).joined()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Key handling
|
||||||
|
|
||||||
|
public func handle(_ key: KeyInput) -> KeyResult {
|
||||||
|
if isShowingCandidates { return handleCandidateKey(key) }
|
||||||
|
|
||||||
|
switch key {
|
||||||
|
case .character(let c):
|
||||||
|
return handleCharacter(c)
|
||||||
|
case .backspace:
|
||||||
|
guard !keys.isEmpty else { return .passThrough }
|
||||||
|
keys.removeLast()
|
||||||
|
fixed = validFixed(parse)
|
||||||
|
if keys.isEmpty { forcedMode = nil; fixed = [:] }
|
||||||
|
return .consumed
|
||||||
|
case .enter:
|
||||||
|
guard !keys.isEmpty else { return .passThrough }
|
||||||
|
return KeyResult(handled: true, commit: commitCurrent())
|
||||||
|
case .escape:
|
||||||
|
guard !keys.isEmpty else { return .passThrough }
|
||||||
|
reset()
|
||||||
|
return .consumed
|
||||||
|
case .tab:
|
||||||
|
guard !keys.isEmpty else { return .passThrough }
|
||||||
|
forcedMode = (mode == .zhuyin) ? .literal : .zhuyin
|
||||||
|
return .consumed
|
||||||
|
case .down:
|
||||||
|
guard !keys.isEmpty else { return .passThrough }
|
||||||
|
openCandidates()
|
||||||
|
return .consumed
|
||||||
|
case .up, .left, .right:
|
||||||
|
return keys.isEmpty ? .passThrough : .consumed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func handleCharacter(_ c: Character) -> KeyResult {
|
||||||
|
if c == " " {
|
||||||
|
guard !keys.isEmpty else { return .passThrough }
|
||||||
|
let decided = forcedMode ?? classifier.classify(keys, finishing: true, previous: context).mode
|
||||||
|
if decided == .literal {
|
||||||
|
return KeyResult(handled: true, commit: commitCurrent(as: .literal) + " ")
|
||||||
|
}
|
||||||
|
if parse.pending != nil {
|
||||||
|
keys.append(" ") // first tone
|
||||||
|
return .consumed
|
||||||
|
}
|
||||||
|
return KeyResult(handled: true, commit: commitCurrent(as: .zhuyin))
|
||||||
|
}
|
||||||
|
|
||||||
|
let composable = DachenLayout.isZhuyinKey(c) || (c.isASCII && c.isLetter) || (c == "'" && !keys.isEmpty)
|
||||||
|
if composable {
|
||||||
|
// ", . / ; -" are Zhuyin symbols (ㄝ ㄡ ㄥ ㄤ ㄦ) but act as punctuation after an
|
||||||
|
// English word. Decide with the key included: "2;" is ㄉㄤ (檔…), "hello," is English.
|
||||||
|
if !keys.isEmpty, DachenLayout.symbols[c] != nil, !c.isLetter, !c.isNumber, forcedMode != .zhuyin {
|
||||||
|
let withKey = forcedMode ?? classifier.classify(keys + [c], previous: context).mode
|
||||||
|
if withKey == .literal && !keys.allSatisfy(\.isNumber) {
|
||||||
|
return KeyResult(handled: true, commit: commitCurrent(as: .literal) + String(c))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
keys.append(c)
|
||||||
|
return .consumed
|
||||||
|
}
|
||||||
|
|
||||||
|
// Any other character (Shift-punctuation, symbols): commit, then emit it.
|
||||||
|
let chineseContext = keys.isEmpty ? (context == .zhuyin) : (mode == .zhuyin)
|
||||||
|
let committed = keys.isEmpty ? "" : commitCurrent()
|
||||||
|
let punct = chineseContext ? (CompositionEngine.fullwidth[c] ?? String(c)) : String(c)
|
||||||
|
if committed.isEmpty && punct == String(c) { return .passThrough }
|
||||||
|
return KeyResult(handled: true, commit: committed + punct)
|
||||||
|
}
|
||||||
|
|
||||||
|
static let fullwidth: [Character: String] = [
|
||||||
|
"<": ",", ">": "。", "?": "?", "!": "!", ":": ":", "\"": "「", "(": "(", ")": ")",
|
||||||
|
"{": "『", "}": "』", "[": "「", "]": "」", "~": "~", "_": "——",
|
||||||
|
]
|
||||||
|
|
||||||
|
// MARK: - Candidates
|
||||||
|
|
||||||
|
private func openCandidates() {
|
||||||
|
let p = parse
|
||||||
|
guard mode == .zhuyin, !p.completed.isEmpty else { return }
|
||||||
|
candidates = converter.candidates(p.completed.map(\.syllable), endingAt: p.completed.count)
|
||||||
|
candidateIndex = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
public func selectCandidate(_ index: Int) {
|
||||||
|
guard candidates.indices.contains(index) else { return }
|
||||||
|
let c = candidates[index]
|
||||||
|
fixed = fixed.filter { !$0.key.overlaps(c.range) }
|
||||||
|
fixed[c.range] = c.text
|
||||||
|
candidates = []
|
||||||
|
}
|
||||||
|
|
||||||
|
private func handleCandidateKey(_ key: KeyInput) -> KeyResult {
|
||||||
|
switch key {
|
||||||
|
case .character(let c) where c.isNumber && c != "0":
|
||||||
|
selectCandidate(Int(String(c))! - 1 + pageStart)
|
||||||
|
case .character(" "), .enter:
|
||||||
|
selectCandidate(candidateIndex)
|
||||||
|
case .down, .right:
|
||||||
|
candidateIndex = min(candidates.count - 1, candidateIndex + 1)
|
||||||
|
case .up, .left:
|
||||||
|
candidateIndex = max(0, candidateIndex - 1)
|
||||||
|
case .escape, .backspace:
|
||||||
|
candidates = []
|
||||||
|
default:
|
||||||
|
break
|
||||||
|
}
|
||||||
|
return .consumed
|
||||||
|
}
|
||||||
|
|
||||||
|
public var pageSize = 9
|
||||||
|
private var pageStart: Int { (candidateIndex / pageSize) * pageSize }
|
||||||
|
|
||||||
|
// MARK: - Commit
|
||||||
|
|
||||||
|
@discardableResult
|
||||||
|
private func commitCurrent(as decided: InputMode? = nil) -> String {
|
||||||
|
let m = decided ?? mode
|
||||||
|
let text = m == .literal ? String(keys) : zhuyinCommitText()
|
||||||
|
if let forced = forcedMode {
|
||||||
|
classifier.learned.record(String(keys), as: forced)
|
||||||
|
}
|
||||||
|
previousMode = m
|
||||||
|
previousCommitTime = now()
|
||||||
|
reset()
|
||||||
|
return text
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Commits whatever is composed (e.g. the app lost focus). Returns "" when empty.
|
||||||
|
public func commitAll() -> String {
|
||||||
|
keys.isEmpty ? "" : commitCurrent()
|
||||||
|
}
|
||||||
|
|
||||||
|
public func reset() {
|
||||||
|
keys = []
|
||||||
|
forcedMode = nil
|
||||||
|
fixed = [:]
|
||||||
|
candidates = []
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
public struct ConvertedSegment: Equatable {
|
||||||
|
public var range: Range<Int> // syllable indices
|
||||||
|
public var text: String
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct Candidate: Equatable {
|
||||||
|
public var range: Range<Int>
|
||||||
|
public var text: String
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Turns a syllable sequence into the most likely Chinese text (Viterbi over the lexicon).
|
||||||
|
public struct Converter {
|
||||||
|
public let lexicon: Lexicon
|
||||||
|
/// Score used when a syllable has no lexicon entry; the Bopomofo itself is emitted.
|
||||||
|
static let unknownScore = -30.0
|
||||||
|
/// Penalty for matching an untoned syllable against all tones.
|
||||||
|
static let tonelessPenalty = -1.5
|
||||||
|
|
||||||
|
public init(lexicon: Lexicon) { self.lexicon = lexicon }
|
||||||
|
|
||||||
|
/// - Parameter fixed: user-chosen phrases by syllable range; they are always kept.
|
||||||
|
public func convert(_ syllables: [Syllable], fixed: [Range<Int>: String] = [:]) -> [ConvertedSegment] {
|
||||||
|
let n = syllables.count
|
||||||
|
guard n > 0 else { return [] }
|
||||||
|
let maxLen = max(1, lexicon.maxPhraseLength)
|
||||||
|
|
||||||
|
// best[j] = (score, backpointer segment) for the prefix ending at j.
|
||||||
|
var best: [(score: Double, seg: ConvertedSegment?)] = Array(repeating: (-.infinity, nil), count: n + 1)
|
||||||
|
best[0] = (0, nil)
|
||||||
|
|
||||||
|
for j in 1...n {
|
||||||
|
for len in 1...min(maxLen, j) {
|
||||||
|
let i = j - len
|
||||||
|
guard best[i].score > -.infinity else { continue }
|
||||||
|
let range = i..<j
|
||||||
|
for (text, score) in options(for: range, syllables: syllables, fixed: fixed) {
|
||||||
|
let total = best[i].score + score
|
||||||
|
if total > best[j].score { best[j] = (total, ConvertedSegment(range: range, text: text)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var segments: [ConvertedSegment] = []
|
||||||
|
var j = n
|
||||||
|
while j > 0, let seg = best[j].seg {
|
||||||
|
segments.append(seg)
|
||||||
|
j = seg.range.lowerBound
|
||||||
|
}
|
||||||
|
return segments.reversed()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func options(for range: Range<Int>, syllables: [Syllable], fixed: [Range<Int>: String]) -> [(String, Double)] {
|
||||||
|
if let text = fixed[range] { return [(text, 0)] }
|
||||||
|
// A span may not partially overlap or swallow a fixed span.
|
||||||
|
if fixed.keys.contains(where: { $0.overlaps(range) }) { return [] }
|
||||||
|
|
||||||
|
let slice = Array(syllables[range])
|
||||||
|
var result = lexicon.entries(for: slice).map { entry -> (String, Double) in
|
||||||
|
let penalty = slice.contains { $0.tone == nil } ? Converter.tonelessPenalty : 0
|
||||||
|
return (entry.phrase, entry.score + penalty)
|
||||||
|
}
|
||||||
|
if result.isEmpty && range.count == 1 {
|
||||||
|
result = [(slice[0].reading, Converter.unknownScore)]
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Candidates for phrases ending at syllable index `end - 1`, longest phrases first.
|
||||||
|
public func candidates(_ syllables: [Syllable], endingAt end: Int) -> [Candidate] {
|
||||||
|
guard end > 0, end <= syllables.count else { return [] }
|
||||||
|
var out: [Candidate] = []
|
||||||
|
var seen = Set<String>()
|
||||||
|
for len in stride(from: min(lexicon.maxPhraseLength, end), through: 1, by: -1) {
|
||||||
|
let range = (end - len)..<end
|
||||||
|
for entry in lexicon.entries(for: Array(syllables[range])) where !seen.contains(entry.phrase) {
|
||||||
|
seen.insert(entry.phrase)
|
||||||
|
out.append(Candidate(range: range, text: entry.phrase))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Scores how much a typed string looks like English.
|
||||||
|
///
|
||||||
|
/// Three sources of evidence:
|
||||||
|
/// - a list of common words (strong evidence, includes modern words like "ok", "email"),
|
||||||
|
/// - a large dictionary (e.g. /usr/share/dict/words, weaker evidence),
|
||||||
|
/// - a letter-bigram model trained on those words, for words not in either list.
|
||||||
|
public final class EnglishModel {
|
||||||
|
private var common = Set<String>()
|
||||||
|
private var dictionary = Set<String>()
|
||||||
|
private var sortedWords: [String] = []
|
||||||
|
private var sortedCommon: [String] = []
|
||||||
|
private var bigram: [String: Double] = [:] // "ab" -> log2 P(b|a); "^a", "a$" for boundaries
|
||||||
|
private var unseenBigram = -12.0
|
||||||
|
|
||||||
|
public init(commonWords: [String], dictionaryWords: [String] = []) {
|
||||||
|
common = Set(commonWords.map { $0.lowercased() }.filter { !$0.isEmpty })
|
||||||
|
dictionary = Set(dictionaryWords.map { $0.lowercased() }.filter { $0.count > 2 })
|
||||||
|
sortedCommon = common.sorted()
|
||||||
|
sortedWords = common.union(dictionary).sorted()
|
||||||
|
trainBigram()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Loads common words from a bundle resource file and the system dictionary if present.
|
||||||
|
public convenience init(commonWordsURL: URL?, systemDictionary: URL? = URL(fileURLWithPath: "/usr/share/dict/words")) {
|
||||||
|
func lines(_ url: URL?) -> [String] {
|
||||||
|
guard let url, let text = try? String(contentsOf: url, encoding: .utf8) else { return [] }
|
||||||
|
return text.split(whereSeparator: \.isNewline)
|
||||||
|
.map { $0.trimmingCharacters(in: .whitespaces) }
|
||||||
|
.filter { !$0.hasPrefix("#") }
|
||||||
|
}
|
||||||
|
self.init(commonWords: lines(commonWordsURL), dictionaryWords: lines(systemDictionary))
|
||||||
|
}
|
||||||
|
|
||||||
|
public func isCommon(_ w: String) -> Bool { common.contains(w.lowercased()) }
|
||||||
|
public func isWord(_ w: String) -> Bool { let l = w.lowercased(); return common.contains(l) || dictionary.contains(l) }
|
||||||
|
|
||||||
|
/// - Parameter complete: true when the user ended the word (space / punctuation),
|
||||||
|
/// false while still typing (prefixes of words get partial credit).
|
||||||
|
public func score(_ word: String, complete: Bool) -> Double {
|
||||||
|
let w = word.lowercased()
|
||||||
|
let n = Double(w.count)
|
||||||
|
guard !w.isEmpty else { return 0 }
|
||||||
|
if common.contains(w) { return 3 + n }
|
||||||
|
if dictionary.contains(w) { return 1 + 0.6 * n }
|
||||||
|
if !complete {
|
||||||
|
if hasPrefix(w, in: sortedCommon) { return 0.4 * n }
|
||||||
|
if hasPrefix(w, in: sortedWords) { return 0.2 * n }
|
||||||
|
}
|
||||||
|
// Unknown word: judge by how English-like its letter sequence is.
|
||||||
|
let plaus = plausibility(w)
|
||||||
|
return min(0.5 * n, max(-2 * n, n * (plaus + 4.2)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mean log2 probability per letter transition (≈ -3.5 for English, lower for gibberish).
|
||||||
|
public func plausibility(_ w: String) -> Double {
|
||||||
|
let chars = ["^"] + w.map(String.init) + ["$"]
|
||||||
|
var total = 0.0
|
||||||
|
for i in 1..<chars.count { total += bigram[chars[i - 1] + chars[i]] ?? unseenBigram }
|
||||||
|
return total / Double(chars.count - 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func hasPrefix(_ p: String, in words: [String]) -> Bool {
|
||||||
|
var lo = 0, hi = words.count
|
||||||
|
while lo < hi {
|
||||||
|
let mid = (lo + hi) / 2
|
||||||
|
if words[mid] < p { lo = mid + 1 } else { hi = mid }
|
||||||
|
}
|
||||||
|
// words[lo] is the first word >= p; skip an exact match, then test the next one.
|
||||||
|
if lo < words.count && words[lo] == p { lo += 1 }
|
||||||
|
return lo < words.count && words[lo].hasPrefix(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func trainBigram() {
|
||||||
|
var pair: [String: Double] = [:]
|
||||||
|
var first: [String: Double] = [:]
|
||||||
|
for w in sortedWords where w.allSatisfy({ $0.isLetter && $0.isASCII }) {
|
||||||
|
let weight = common.contains(w) ? 5.0 : 1.0
|
||||||
|
let chars = ["^"] + w.map(String.init) + ["$"]
|
||||||
|
for i in 1..<chars.count {
|
||||||
|
pair[chars[i - 1] + chars[i], default: 0] += weight
|
||||||
|
first[chars[i - 1], default: 0] += weight
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Add-one smoothing over 27 possible successors.
|
||||||
|
for (k, c) in pair {
|
||||||
|
let a = String(k.prefix(1))
|
||||||
|
bigram[k] = log2((c + 1) / ((first[a] ?? 0) + 27))
|
||||||
|
}
|
||||||
|
unseenBigram = log2(1.0 / ((first.values.max() ?? 1000) + 27))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
public struct LexiconEntry: Equatable {
|
||||||
|
public var phrase: String
|
||||||
|
/// log10 probability (higher is more likely), McBopomofo-style.
|
||||||
|
public var score: Double
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Maps Bopomofo readings (syllables joined by "-", e.g. "ㄋㄧˇ-ㄏㄠˇ") to phrases.
|
||||||
|
///
|
||||||
|
/// File format, one entry per line (`#` starts a comment):
|
||||||
|
/// ㄋㄧˇ-ㄏㄠˇ 你好 -4.2
|
||||||
|
/// The phrase/reading columns may be in either order; the score is optional.
|
||||||
|
public final class Lexicon {
|
||||||
|
private var exact: [String: [LexiconEntry]] = [:]
|
||||||
|
private var toneless: [String: [LexiconEntry]] = [:]
|
||||||
|
public private(set) var maxPhraseLength = 1
|
||||||
|
|
||||||
|
public init() {}
|
||||||
|
|
||||||
|
public convenience init(contentsOf url: URL) throws {
|
||||||
|
self.init()
|
||||||
|
load(try String(contentsOf: url, encoding: .utf8))
|
||||||
|
}
|
||||||
|
|
||||||
|
public func load(_ text: String) {
|
||||||
|
for line in text.split(whereSeparator: \.isNewline) {
|
||||||
|
let trimmed = line.trimmingCharacters(in: .whitespaces)
|
||||||
|
if trimmed.isEmpty || trimmed.hasPrefix("#") { continue }
|
||||||
|
let cols = trimmed.split(whereSeparator: { $0 == " " || $0 == "\t" }).map(String.init)
|
||||||
|
guard cols.count >= 2 else { continue }
|
||||||
|
let (reading, phrase) = Lexicon.isBopomofo(cols[0]) ? (cols[0], cols[1]) : (cols[1], cols[0])
|
||||||
|
guard Lexicon.isBopomofo(reading) else { continue }
|
||||||
|
let score = cols.count >= 3 ? Double(cols[2]) ?? -6 : -6
|
||||||
|
add(reading: reading, phrase: phrase, score: score)
|
||||||
|
}
|
||||||
|
for key in exact.keys { exact[key]?.sort { $0.score > $1.score } }
|
||||||
|
for key in toneless.keys { toneless[key]?.sort { $0.score > $1.score } }
|
||||||
|
}
|
||||||
|
|
||||||
|
public func add(reading rawReading: String, phrase: String, score: Double) {
|
||||||
|
let entry = LexiconEntry(phrase: phrase, score: score)
|
||||||
|
// Some data sets write the neutral tone as a prefix ("˙ㄉㄜ"); we use a suffix.
|
||||||
|
let syllables = rawReading.split(separator: "-").map { s -> String in
|
||||||
|
s.hasPrefix("˙") ? String(s.dropFirst()) + "˙" : String(s)
|
||||||
|
}
|
||||||
|
let reading = syllables.joined(separator: "-")
|
||||||
|
maxPhraseLength = max(maxPhraseLength, syllables.count)
|
||||||
|
if !(exact[reading]?.contains { $0.phrase == phrase } ?? false) {
|
||||||
|
exact[reading, default: []].append(entry)
|
||||||
|
}
|
||||||
|
let key = Lexicon.stripTones(reading)
|
||||||
|
if let i = toneless[key]?.firstIndex(where: { $0.phrase == phrase }) {
|
||||||
|
toneless[key]![i].score = max(toneless[key]![i].score, score)
|
||||||
|
} else {
|
||||||
|
toneless[key, default: []].append(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Entries for a sequence of readings. Untoned syllables match any tone.
|
||||||
|
public func entries(for syllables: [Syllable]) -> [LexiconEntry] {
|
||||||
|
if syllables.allSatisfy({ $0.tone != nil }) {
|
||||||
|
return exact[syllables.map(\.reading).joined(separator: "-")] ?? []
|
||||||
|
}
|
||||||
|
return toneless[syllables.map(\.toneless).joined(separator: "-")] ?? []
|
||||||
|
}
|
||||||
|
|
||||||
|
public func bestScore(for syllable: Syllable) -> Double? {
|
||||||
|
entries(for: [syllable]).first?.score
|
||||||
|
}
|
||||||
|
|
||||||
|
public var isEmpty: Bool { exact.isEmpty }
|
||||||
|
|
||||||
|
static let toneMarks: Set<Character> = ["ˊ", "ˇ", "ˋ", "˙"]
|
||||||
|
|
||||||
|
static func stripTones(_ reading: String) -> String {
|
||||||
|
String(reading.filter { !toneMarks.contains($0) })
|
||||||
|
}
|
||||||
|
|
||||||
|
static func isBopomofo(_ s: String) -> Bool {
|
||||||
|
guard let first = s.unicodeScalars.first else { return false }
|
||||||
|
return (0x3105...0x312F).contains(first.value) || first == "˙"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// The inventory of valid (toneless) Mandarin syllables in Bopomofo.
|
||||||
|
public enum SyllableTable {
|
||||||
|
private static let raw = """
|
||||||
|
ㄚ ㄛ ㄜ ㄝ ㄞ ㄟ ㄠ ㄡ ㄢ ㄣ ㄤ ㄥ ㄦ
|
||||||
|
ㄧ ㄧㄚ ㄧㄛ ㄧㄝ ㄧㄞ ㄧㄠ ㄧㄡ ㄧㄢ ㄧㄣ ㄧㄤ ㄧㄥ
|
||||||
|
ㄨ ㄨㄚ ㄨㄛ ㄨㄞ ㄨㄟ ㄨㄢ ㄨㄣ ㄨㄤ ㄨㄥ
|
||||||
|
ㄩ ㄩㄝ ㄩㄢ ㄩㄣ ㄩㄥ
|
||||||
|
ㄅㄚ ㄅㄛ ㄅㄞ ㄅㄟ ㄅㄠ ㄅㄢ ㄅㄣ ㄅㄤ ㄅㄥ ㄅㄧ ㄅㄧㄝ ㄅㄧㄠ ㄅㄧㄢ ㄅㄧㄣ ㄅㄧㄥ ㄅㄨ
|
||||||
|
ㄆㄚ ㄆㄛ ㄆㄞ ㄆㄟ ㄆㄠ ㄆㄡ ㄆㄢ ㄆㄣ ㄆㄤ ㄆㄥ ㄆㄧ ㄆㄧㄝ ㄆㄧㄠ ㄆㄧㄢ ㄆㄧㄣ ㄆㄧㄥ ㄆㄨ
|
||||||
|
ㄇㄚ ㄇㄛ ㄇㄜ ㄇㄞ ㄇㄟ ㄇㄠ ㄇㄡ ㄇㄢ ㄇㄣ ㄇㄤ ㄇㄥ ㄇㄧ ㄇㄧㄝ ㄇㄧㄠ ㄇㄧㄡ ㄇㄧㄢ ㄇㄧㄣ ㄇㄧㄥ ㄇㄨ
|
||||||
|
ㄈㄚ ㄈㄛ ㄈㄟ ㄈㄡ ㄈㄢ ㄈㄣ ㄈㄤ ㄈㄥ ㄈㄨ
|
||||||
|
ㄉㄚ ㄉㄜ ㄉㄞ ㄉㄟ ㄉㄠ ㄉㄡ ㄉㄢ ㄉㄣ ㄉㄤ ㄉㄥ ㄉㄧ ㄉㄧㄚ ㄉㄧㄝ ㄉㄧㄠ ㄉㄧㄡ ㄉㄧㄢ ㄉㄧㄥ ㄉㄨ ㄉㄨㄛ ㄉㄨㄟ ㄉㄨㄢ ㄉㄨㄣ ㄉㄨㄥ
|
||||||
|
ㄊㄚ ㄊㄜ ㄊㄞ ㄊㄠ ㄊㄡ ㄊㄢ ㄊㄤ ㄊㄥ ㄊㄧ ㄊㄧㄝ ㄊㄧㄠ ㄊㄧㄢ ㄊㄧㄥ ㄊㄨ ㄊㄨㄛ ㄊㄨㄟ ㄊㄨㄢ ㄊㄨㄣ ㄊㄨㄥ
|
||||||
|
ㄋㄚ ㄋㄜ ㄋㄞ ㄋㄟ ㄋㄠ ㄋㄡ ㄋㄢ ㄋㄣ ㄋㄤ ㄋㄥ ㄋㄧ ㄋㄧㄝ ㄋㄧㄠ ㄋㄧㄡ ㄋㄧㄢ ㄋㄧㄣ ㄋㄧㄤ ㄋㄧㄥ ㄋㄨ ㄋㄨㄛ ㄋㄨㄢ ㄋㄨㄥ ㄋㄩ ㄋㄩㄝ
|
||||||
|
ㄌㄚ ㄌㄛ ㄌㄜ ㄌㄞ ㄌㄟ ㄌㄠ ㄌㄡ ㄌㄢ ㄌㄤ ㄌㄥ ㄌㄧ ㄌㄧㄚ ㄌㄧㄝ ㄌㄧㄠ ㄌㄧㄡ ㄌㄧㄢ ㄌㄧㄣ ㄌㄧㄤ ㄌㄧㄥ ㄌㄨ ㄌㄨㄛ ㄌㄨㄢ ㄌㄨㄣ ㄌㄨㄥ ㄌㄩ ㄌㄩㄝ ㄌㄩㄢ
|
||||||
|
ㄍㄚ ㄍㄜ ㄍㄞ ㄍㄟ ㄍㄠ ㄍㄡ ㄍㄢ ㄍㄣ ㄍㄤ ㄍㄥ ㄍㄨ ㄍㄨㄚ ㄍㄨㄛ ㄍㄨㄞ ㄍㄨㄟ ㄍㄨㄢ ㄍㄨㄣ ㄍㄨㄤ ㄍㄨㄥ
|
||||||
|
ㄎㄚ ㄎㄜ ㄎㄞ ㄎㄟ ㄎㄠ ㄎㄡ ㄎㄢ ㄎㄣ ㄎㄤ ㄎㄥ ㄎㄨ ㄎㄨㄚ ㄎㄨㄛ ㄎㄨㄞ ㄎㄨㄟ ㄎㄨㄢ ㄎㄨㄣ ㄎㄨㄤ ㄎㄨㄥ
|
||||||
|
ㄏㄚ ㄏㄜ ㄏㄞ ㄏㄟ ㄏㄠ ㄏㄡ ㄏㄢ ㄏㄣ ㄏㄤ ㄏㄥ ㄏㄨ ㄏㄨㄚ ㄏㄨㄛ ㄏㄨㄞ ㄏㄨㄟ ㄏㄨㄢ ㄏㄨㄣ ㄏㄨㄤ ㄏㄨㄥ
|
||||||
|
ㄐㄧ ㄐㄧㄚ ㄐㄧㄝ ㄐㄧㄠ ㄐㄧㄡ ㄐㄧㄢ ㄐㄧㄣ ㄐㄧㄤ ㄐㄧㄥ ㄐㄩ ㄐㄩㄝ ㄐㄩㄢ ㄐㄩㄣ ㄐㄩㄥ
|
||||||
|
ㄑㄧ ㄑㄧㄚ ㄑㄧㄝ ㄑㄧㄠ ㄑㄧㄡ ㄑㄧㄢ ㄑㄧㄣ ㄑㄧㄤ ㄑㄧㄥ ㄑㄩ ㄑㄩㄝ ㄑㄩㄢ ㄑㄩㄣ ㄑㄩㄥ
|
||||||
|
ㄒㄧ ㄒㄧㄚ ㄒㄧㄝ ㄒㄧㄠ ㄒㄧㄡ ㄒㄧㄢ ㄒㄧㄣ ㄒㄧㄤ ㄒㄧㄥ ㄒㄩ ㄒㄩㄝ ㄒㄩㄢ ㄒㄩㄣ ㄒㄩㄥ
|
||||||
|
ㄓ ㄓㄚ ㄓㄜ ㄓㄞ ㄓㄟ ㄓㄠ ㄓㄡ ㄓㄢ ㄓㄣ ㄓㄤ ㄓㄥ ㄓㄨ ㄓㄨㄚ ㄓㄨㄛ ㄓㄨㄞ ㄓㄨㄟ ㄓㄨㄢ ㄓㄨㄣ ㄓㄨㄤ ㄓㄨㄥ
|
||||||
|
ㄔ ㄔㄚ ㄔㄜ ㄔㄞ ㄔㄠ ㄔㄡ ㄔㄢ ㄔㄣ ㄔㄤ ㄔㄥ ㄔㄨ ㄔㄨㄚ ㄔㄨㄛ ㄔㄨㄞ ㄔㄨㄟ ㄔㄨㄢ ㄔㄨㄣ ㄔㄨㄤ ㄔㄨㄥ
|
||||||
|
ㄕ ㄕㄚ ㄕㄜ ㄕㄞ ㄕㄟ ㄕㄠ ㄕㄡ ㄕㄢ ㄕㄣ ㄕㄤ ㄕㄥ ㄕㄨ ㄕㄨㄚ ㄕㄨㄛ ㄕㄨㄞ ㄕㄨㄟ ㄕㄨㄢ ㄕㄨㄣ ㄕㄨㄤ
|
||||||
|
ㄖ ㄖㄜ ㄖㄠ ㄖㄡ ㄖㄢ ㄖㄣ ㄖㄤ ㄖㄥ ㄖㄨ ㄖㄨㄛ ㄖㄨㄟ ㄖㄨㄢ ㄖㄨㄣ ㄖㄨㄥ
|
||||||
|
ㄗ ㄗㄚ ㄗㄜ ㄗㄞ ㄗㄟ ㄗㄠ ㄗㄡ ㄗㄢ ㄗㄣ ㄗㄤ ㄗㄥ ㄗㄨ ㄗㄨㄛ ㄗㄨㄟ ㄗㄨㄢ ㄗㄨㄣ ㄗㄨㄥ
|
||||||
|
ㄘ ㄘㄚ ㄘㄜ ㄘㄞ ㄘㄠ ㄘㄡ ㄘㄢ ㄘㄣ ㄘㄤ ㄘㄥ ㄘㄨ ㄘㄨㄛ ㄘㄨㄟ ㄘㄨㄢ ㄘㄨㄣ ㄘㄨㄥ
|
||||||
|
ㄙ ㄙㄚ ㄙㄜ ㄙㄞ ㄙㄠ ㄙㄡ ㄙㄢ ㄙㄣ ㄙㄤ ㄙㄥ ㄙㄨ ㄙㄨㄛ ㄙㄨㄟ ㄙㄨㄢ ㄙㄨㄣ ㄙㄨㄥ
|
||||||
|
"""
|
||||||
|
|
||||||
|
public static let valid: Set<String> = Set(raw.split(whereSeparator: { $0 == " " || $0 == "\n" }).map(String.init))
|
||||||
|
|
||||||
|
/// Every prefix (in initial→medial→final order) of a valid syllable, e.g. "ㄋ", "ㄋㄧ".
|
||||||
|
public static let validPrefixes: Set<String> = {
|
||||||
|
var s = Set<String>()
|
||||||
|
for syl in valid {
|
||||||
|
let chars = Array(syl)
|
||||||
|
for n in 1...chars.count { s.insert(String(chars[0..<n])) }
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}()
|
||||||
|
|
||||||
|
/// Every valid syllable with any of its slots blanked out, as "initial|medial|final"
|
||||||
|
/// with "_" for an empty slot (e.g. "ㄒ_ㄠ" from ㄒㄧㄠ). Used to accept symbols typed
|
||||||
|
/// out of order: a partial syllable is fine if some valid syllable completes it.
|
||||||
|
private static let compatiblePatterns: Set<String> = {
|
||||||
|
var s = Set<String>()
|
||||||
|
for syl in valid {
|
||||||
|
var slots: [Character?] = [nil, nil, nil]
|
||||||
|
for c in syl { slots[DachenLayout.slot(of: c).rawValue] = c }
|
||||||
|
for mask in 0..<8 {
|
||||||
|
let masked = (0..<3).map { i -> Character in
|
||||||
|
mask & (1 << i) != 0 ? (slots[i] ?? "_") : "_"
|
||||||
|
}
|
||||||
|
s.insert(String(masked))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}()
|
||||||
|
|
||||||
|
public static func isCompatible(_ syllable: Syllable) -> Bool {
|
||||||
|
compatiblePatterns.contains(String([syllable.initial ?? "_", syllable.medial ?? "_", syllable.final ?? "_"]))
|
||||||
|
}
|
||||||
|
|
||||||
|
public static func isValid(_ syllable: Syllable) -> Bool { valid.contains(syllable.toneless) }
|
||||||
|
public static func isValidPrefix(_ syllable: Syllable) -> Bool {
|
||||||
|
syllable.isEmpty || validPrefixes.contains(syllable.toneless)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// A syllable parsed out of a key sequence, with the key range that produced it.
|
||||||
|
public struct ParsedSyllable: Equatable {
|
||||||
|
public var syllable: Syllable
|
||||||
|
public var keyRange: Range<Int>
|
||||||
|
/// True when its symbols were typed out of initial→medial→final order.
|
||||||
|
public var reordered = false
|
||||||
|
/// True when the syllable was closed by a tone key.
|
||||||
|
public var toned: Bool { syllable.tone != nil }
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct ZhuyinParse: Equatable {
|
||||||
|
public var syllables: [ParsedSyllable]
|
||||||
|
/// Number of tone keys that had no syllable to attach to (e.g. "33").
|
||||||
|
public var strayTones: Int
|
||||||
|
/// Keys that are not part of the Dachen layout at all (uppercase, `'`, …).
|
||||||
|
public var foreignKeys: Int
|
||||||
|
|
||||||
|
/// The trailing syllable that is still being composed (not closed by a tone), if any.
|
||||||
|
public var pending: ParsedSyllable? {
|
||||||
|
guard let last = syllables.last, !last.toned else { return nil }
|
||||||
|
return last
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Syllables that are finished: either toned, or untoned but followed by another syllable.
|
||||||
|
public var completed: [ParsedSyllable] {
|
||||||
|
pending == nil ? syllables : Array(syllables.dropLast())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Splits raw keystrokes into syllables following Dachen composition rules:
|
||||||
|
/// symbols fill initial → medial → final; a symbol whose slot (or a later one)
|
||||||
|
/// is already filled starts a new syllable; a tone key closes the syllable.
|
||||||
|
public enum ZhuyinParser {
|
||||||
|
public static func parse(_ keys: [Character]) -> ZhuyinParse {
|
||||||
|
var result = ZhuyinParse(syllables: [], strayTones: 0, foreignKeys: 0)
|
||||||
|
var current = Syllable()
|
||||||
|
var start = 0
|
||||||
|
var reordered = false
|
||||||
|
|
||||||
|
func close(at end: Int) {
|
||||||
|
if !current.isEmpty {
|
||||||
|
result.syllables.append(ParsedSyllable(syllable: current, keyRange: start..<end, reordered: reordered))
|
||||||
|
}
|
||||||
|
current = Syllable()
|
||||||
|
start = end
|
||||||
|
reordered = false
|
||||||
|
}
|
||||||
|
|
||||||
|
for (i, key) in keys.enumerated() {
|
||||||
|
if let tone = DachenLayout.tones[key] {
|
||||||
|
if current.isEmpty {
|
||||||
|
result.strayTones += 1
|
||||||
|
start = i + 1
|
||||||
|
} else {
|
||||||
|
current.tone = tone
|
||||||
|
close(at: i + 1)
|
||||||
|
}
|
||||||
|
} else if let symbol = DachenLayout.symbols[key] {
|
||||||
|
let slot = DachenLayout.slot(of: symbol)
|
||||||
|
let laterFilled = [BopomofoSlot.initial, .medial, .final].contains { $0 > slot && current.filled($0) }
|
||||||
|
if current.filled(slot) {
|
||||||
|
close(at: i)
|
||||||
|
} else if laterFilled {
|
||||||
|
// Typed out of order (e.g. ㄧ then ㄒ for ㄒㄧ). Merge into the current
|
||||||
|
// syllable when some valid syllable fits; otherwise start a new one.
|
||||||
|
var merged = current
|
||||||
|
merged.set(symbol, in: slot)
|
||||||
|
if SyllableTable.isCompatible(merged) {
|
||||||
|
reordered = true
|
||||||
|
} else {
|
||||||
|
close(at: i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if current.isEmpty { start = i }
|
||||||
|
current.set(symbol, in: slot)
|
||||||
|
} else {
|
||||||
|
close(at: i)
|
||||||
|
result.foreignKeys += 1
|
||||||
|
start = i + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
close(at: keys.count)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
import XCTest
|
||||||
|
@testable import AutoZhuyinCore
|
||||||
|
|
||||||
|
private let resources = URL(fileURLWithPath: #filePath)
|
||||||
|
.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
|
||||||
|
.appendingPathComponent("Resources")
|
||||||
|
|
||||||
|
private let sharedLexicon = try! Lexicon(contentsOf: resources.appendingPathComponent("lexicon.txt"))
|
||||||
|
private let sharedEnglish = EnglishModel(commonWordsURL: resources.appendingPathComponent("english-common.txt"))
|
||||||
|
|
||||||
|
final class ParserTests: XCTestCase {
|
||||||
|
func testParsesNiHao() {
|
||||||
|
let p = ZhuyinParser.parse(Array("su3cl3"))
|
||||||
|
XCTAssertEqual(p.syllables.map(\.syllable.reading), ["ㄋㄧˇ", "ㄏㄠˇ"])
|
||||||
|
XCTAssertNil(p.pending)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testSpaceIsFirstTone() {
|
||||||
|
let p = ZhuyinParser.parse(Array("wu0 "))
|
||||||
|
XCTAssertEqual(p.syllables.map(\.syllable.reading), ["ㄊㄧㄢ"])
|
||||||
|
XCTAssertEqual(p.syllables.first?.syllable.tone, .first)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testPendingSyllable() {
|
||||||
|
let p = ZhuyinParser.parse(Array("su3c"))
|
||||||
|
XCTAssertEqual(p.completed.count, 1)
|
||||||
|
XCTAssertEqual(p.pending?.syllable.reading, "ㄏ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testOutOfOrderSymbols() {
|
||||||
|
// ㄧ ㄒ ㄠ ˇ → ㄒㄧㄠˇ (小); ㄒ ㄠ ㄧ ˇ → ㄒㄧㄠˇ
|
||||||
|
for keys in ["uvl3", "vlu3", "ulv3"] {
|
||||||
|
let p = ZhuyinParser.parse(Array(keys))
|
||||||
|
XCTAssertEqual(p.syllables.map(\.syllable.reading), ["ㄒㄧㄠˇ"], keys)
|
||||||
|
XCTAssertTrue(p.syllables[0].reordered, keys)
|
||||||
|
}
|
||||||
|
// In-order typing is unchanged and not flagged.
|
||||||
|
XCTAssertFalse(ZhuyinParser.parse(Array("vul3")).syllables[0].reordered)
|
||||||
|
// Symbols that no valid syllable combines (ㄩ then ㄍ) still start a new syllable.
|
||||||
|
XCTAssertEqual(ZhuyinParser.parse(Array("me")).syllables.count, 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testSyllableTable() {
|
||||||
|
XCTAssertTrue(SyllableTable.valid.contains("ㄋㄧ"))
|
||||||
|
XCTAssertTrue(SyllableTable.valid.contains("ㄓ"))
|
||||||
|
XCTAssertFalse(SyllableTable.valid.contains("ㄐㄚ"))
|
||||||
|
XCTAssertTrue(SyllableTable.validPrefixes.contains("ㄐㄧ"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final class ConverterTests: XCTestCase {
|
||||||
|
func testConvertsPhrase() {
|
||||||
|
let c = Converter(lexicon: sharedLexicon)
|
||||||
|
let syl = ZhuyinParser.parse(Array("su3cl3")).syllables.map(\.syllable)
|
||||||
|
XCTAssertEqual(c.convert(syl).map(\.text).joined(), "你好")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testSentence() {
|
||||||
|
let c = Converter(lexicon: sharedLexicon)
|
||||||
|
let syl = ZhuyinParser.parse(Array("rup wu0 wu0 fu4cp3cl3")).syllables.map(\.syllable)
|
||||||
|
XCTAssertEqual(c.convert(syl).map(\.text).joined(), "今天天氣很好")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testLexiconLoadTime() throws {
|
||||||
|
let start = Date()
|
||||||
|
_ = try Lexicon(contentsOf: resources.appendingPathComponent("lexicon.txt"))
|
||||||
|
let elapsed = Date().timeIntervalSince(start)
|
||||||
|
print("lexicon load: \(elapsed)s")
|
||||||
|
XCTAssertLessThan(elapsed, 3)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testFixedCandidateWins() {
|
||||||
|
let c = Converter(lexicon: sharedLexicon)
|
||||||
|
let syl = ZhuyinParser.parse(Array("su3")).syllables.map(\.syllable)
|
||||||
|
XCTAssertEqual(c.convert(syl, fixed: [0..<1: "妳"]).map(\.text).joined(), "妳")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testToneOmissionStillConverts() {
|
||||||
|
let c = Converter(lexicon: sharedLexicon)
|
||||||
|
// ㄨㄛ (untoned) + ㄇㄣ˙ → 我們
|
||||||
|
let syl = ZhuyinParser.parse(Array("jiap7")).syllables.map(\.syllable)
|
||||||
|
XCTAssertEqual(c.convert(syl).map(\.text).joined(), "我們")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final class ClassifierTests: XCTestCase {
|
||||||
|
let classifier = Classifier(lexicon: sharedLexicon, english: sharedEnglish)
|
||||||
|
|
||||||
|
func mode(_ s: String, finishing: Bool = false) -> InputMode {
|
||||||
|
classifier.classify(Array(s), finishing: finishing).mode
|
||||||
|
}
|
||||||
|
|
||||||
|
func testZhuyin() {
|
||||||
|
for s in ["su3cl3", "ji3", "cl3", "ru ", "u ", "fu ", "183", "2k7", "5j/ "] {
|
||||||
|
XCTAssertEqual(mode(s), .zhuyin, s)
|
||||||
|
}
|
||||||
|
for s in ["ru", "ji", "fu"] { XCTAssertEqual(mode(s, finishing: true), .zhuyin, s) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func testEnglish() {
|
||||||
|
for s in ["hello", "the", "is", "ok", "github", "Swift", "2024", "so", "go", "me", "no", "a", "an", "up", "i", "meeting", "email", "push"] {
|
||||||
|
XCTAssertEqual(mode(s, finishing: true), .literal, s)
|
||||||
|
}
|
||||||
|
XCTAssertEqual(mode("hello"), .literal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testLearningFlipsDecision() {
|
||||||
|
let learned = LearnedPreferences()
|
||||||
|
let c = Classifier(lexicon: sharedLexicon, english: sharedEnglish, learned: learned)
|
||||||
|
XCTAssertEqual(c.classify(Array("so"), finishing: true).mode, .literal)
|
||||||
|
learned.record("so", as: .zhuyin)
|
||||||
|
XCTAssertEqual(c.classify(Array("so"), finishing: true).mode, .zhuyin)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final class EngineTests: XCTestCase {
|
||||||
|
func makeEngine() -> CompositionEngine {
|
||||||
|
CompositionEngine(classifier: Classifier(lexicon: sharedLexicon, english: sharedEnglish))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Types a string and returns everything committed.
|
||||||
|
func type(_ s: String, into e: CompositionEngine) -> String {
|
||||||
|
var out = ""
|
||||||
|
for c in s {
|
||||||
|
let key: KeyInput = c == "\n" ? .enter : c == "\t" ? .tab : .character(c)
|
||||||
|
let r = e.handle(key)
|
||||||
|
if let t = r.commit { out += t } else if !r.handled { out.append(c) }
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func testMixedSentence() {
|
||||||
|
let e = makeEngine()
|
||||||
|
// 我 + "hello world " + 你好
|
||||||
|
XCTAssertEqual(type("ji3 hello world su3cl3 ", into: e), "我hello world 你好")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testOutOfOrderTypingConverts() {
|
||||||
|
let e = makeEngine()
|
||||||
|
XCTAssertEqual(type("uvl3\n", into: e), "小")
|
||||||
|
// A phrase typed with one syllable out of order converts like the in-order version.
|
||||||
|
XCTAssertEqual(type("ulv3cl3\n", into: makeEngine()), type("vul3cl3\n", into: makeEngine()))
|
||||||
|
}
|
||||||
|
|
||||||
|
func testMarkedTextWhileTyping() {
|
||||||
|
let e = makeEngine()
|
||||||
|
_ = type("su3c", into: e)
|
||||||
|
XCTAssertEqual(e.markedText, "你ㄏ")
|
||||||
|
_ = type("l3", into: e)
|
||||||
|
XCTAssertEqual(e.markedText, "你好")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testEnterCommitsEnglish() {
|
||||||
|
let e = makeEngine()
|
||||||
|
XCTAssertEqual(type("github\n", into: e), "github")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testTabTogglesAndLearns() {
|
||||||
|
let e = makeEngine()
|
||||||
|
_ = type("so", into: e)
|
||||||
|
XCTAssertEqual(e.mode, .literal)
|
||||||
|
_ = e.handle(.tab)
|
||||||
|
XCTAssertEqual(e.mode, .zhuyin)
|
||||||
|
_ = type("\n", into: e)
|
||||||
|
XCTAssertEqual(e.classifier.learned.weights["so"], 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testEnglishPunctuation() {
|
||||||
|
let e = makeEngine()
|
||||||
|
XCTAssertEqual(type("hello, ", into: e), "hello, ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testFullwidthPunctuationAfterChinese() {
|
||||||
|
let e = makeEngine()
|
||||||
|
XCTAssertEqual(type("su3cl3?", into: e), "你好?")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testCandidates() {
|
||||||
|
let e = makeEngine()
|
||||||
|
_ = type("su3", into: e)
|
||||||
|
_ = e.handle(.down)
|
||||||
|
XCTAssertTrue(e.isShowingCandidates)
|
||||||
|
let idx = e.candidates.firstIndex { $0.text == "妳" }!
|
||||||
|
e.selectCandidate(idx)
|
||||||
|
XCTAssertEqual(type("\n", into: e), "妳")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final class DigitInitialTests: XCTestCase {
|
||||||
|
func engine() -> CompositionEngine {
|
||||||
|
CompositionEngine(classifier: Classifier(lexicon: sharedLexicon, english: sharedEnglish))
|
||||||
|
}
|
||||||
|
|
||||||
|
func run(_ s: String) -> (out: String, marked: String) {
|
||||||
|
let e = engine()
|
||||||
|
var out = ""
|
||||||
|
for c in s {
|
||||||
|
let r = e.handle(c == "\n" ? .enter : .character(c))
|
||||||
|
if let t = r.commit { out += t } else if !r.handled { out.append(c) }
|
||||||
|
}
|
||||||
|
return (out, e.markedText)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testDang3() {
|
||||||
|
// 檔 = ㄉㄤˇ = "2;3": ";" (ㄤ) after a digit initial must not be treated as punctuation.
|
||||||
|
let r = run("2;3")
|
||||||
|
XCTAssertEqual(r.out, "")
|
||||||
|
XCTAssertTrue(r.marked.hasPrefix("檔") || r.marked.hasPrefix("黨") || r.marked.hasPrefix("擋"), r.marked)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testOtherDigitInitialSyllables() {
|
||||||
|
XCTAssertEqual(run("2;3\n").out.count, 1) // ㄉㄤˇ
|
||||||
|
XCTAssertEqual(run("2j/ \n").out, "東") // ㄉㄨㄥ
|
||||||
|
XCTAssertEqual(run("1/4\n").out.count, 1) // ㄅㄥˋ
|
||||||
|
}
|
||||||
|
|
||||||
|
func testNumbersStillWork() {
|
||||||
|
XCTAssertEqual(run("2.5\n").out, "2.5")
|
||||||
|
XCTAssertEqual(run("hello, ").out, "hello, ")
|
||||||
|
}
|
||||||
|
}
|
||||||
Executable
+29
@@ -0,0 +1,29 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Builds build/AutoZhuyin.app (release, ad-hoc signed).
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
# Use the full Xcode toolchain (the Command Line Tools SDK may be incomplete).
|
||||||
|
export DEVELOPER_DIR="${DEVELOPER_DIR:-/Applications/Xcode.app/Contents/Developer}"
|
||||||
|
|
||||||
|
CONFIG="${CONFIG:-release}"
|
||||||
|
APP="build/AutoZhuyin.app"
|
||||||
|
|
||||||
|
# Universal binary: runs on both Apple Silicon and Intel Macs.
|
||||||
|
ARCH_FLAGS=(--arch arm64 --arch x86_64)
|
||||||
|
xcrun swift build -c "$CONFIG" "${ARCH_FLAGS[@]}" --product AutoZhuyin
|
||||||
|
BIN="$(xcrun swift build -c "$CONFIG" "${ARCH_FLAGS[@]}" --show-bin-path)/AutoZhuyin"
|
||||||
|
|
||||||
|
rm -rf "$APP"
|
||||||
|
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
|
||||||
|
cp "$BIN" "$APP/Contents/MacOS/AutoZhuyin"
|
||||||
|
cp Resources/Info.plist "$APP/Contents/Info.plist"
|
||||||
|
cp Resources/lexicon.txt Resources/english-common.txt "$APP/Contents/Resources/"
|
||||||
|
|
||||||
|
if [ ! -f build/icon.tiff ]; then
|
||||||
|
xcrun swift scripts/make-icon.swift build/icon.tiff
|
||||||
|
fi
|
||||||
|
cp build/icon.tiff "$APP/Contents/Resources/icon.tiff"
|
||||||
|
|
||||||
|
codesign --force --sign - "$APP"
|
||||||
|
echo "Built $APP"
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Builds Resources/lexicon.txt from McBopomofo's raw data files (MIT License).
|
||||||
|
|
||||||
|
Only reads data files; it does not run any McBopomofo code. Inputs (from
|
||||||
|
McBopomofo's Source/Data): BPMFBase.txt, BPMFMappings.txt, phrase.occ,
|
||||||
|
heterophony{1,2,3}.list.
|
||||||
|
|
||||||
|
Score = log10(count / total), with multi-reading characters split by how
|
||||||
|
common each reading is (heterophony1 = main reading, 2 and 3 = secondary).
|
||||||
|
|
||||||
|
Usage: convert-mcbopomofo.py <McBopomofo/Source/Data> <seed lexicon> <output>
|
||||||
|
"""
|
||||||
|
import math
|
||||||
|
import sys
|
||||||
|
from collections import defaultdict
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
data, seed, out = Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3])
|
||||||
|
|
||||||
|
|
||||||
|
def rows(name):
|
||||||
|
with open(data / name, encoding="utf-8") as f:
|
||||||
|
for line in f:
|
||||||
|
line = line.strip()
|
||||||
|
if line and not line.startswith("#"):
|
||||||
|
yield line.split()
|
||||||
|
|
||||||
|
|
||||||
|
counts = defaultdict(int)
|
||||||
|
for cols in rows("phrase.occ"):
|
||||||
|
if len(cols) == 2 and cols[1].isdigit():
|
||||||
|
counts[cols[0]] += int(cols[1])
|
||||||
|
total = sum(counts.values())
|
||||||
|
|
||||||
|
# Rank of each (char, reading): 1 = main reading.
|
||||||
|
rank = {}
|
||||||
|
for r in (3, 2, 1):
|
||||||
|
for cols in rows(f"heterophony{r}.list"):
|
||||||
|
if len(cols) >= 2:
|
||||||
|
rank[(cols[0], cols[1])] = r
|
||||||
|
has_main = {ch for (ch, _), r in rank.items() if r == 1}
|
||||||
|
RANK_WEIGHT = {1: 1.0, 2: 0.25, 3: 0.08}
|
||||||
|
|
||||||
|
entries = {} # (reading, phrase) -> score
|
||||||
|
|
||||||
|
|
||||||
|
def add(reading, phrase, count):
|
||||||
|
score = round(math.log10((count + 0.3) / total), 4)
|
||||||
|
key = (reading, phrase)
|
||||||
|
if key not in entries or entries[key] < score:
|
||||||
|
entries[key] = score
|
||||||
|
|
||||||
|
|
||||||
|
# Single characters.
|
||||||
|
char_readings = defaultdict(list)
|
||||||
|
for cols in rows("BPMFBase.txt"):
|
||||||
|
if len(cols) >= 2:
|
||||||
|
char_readings[cols[0]].append(cols[1])
|
||||||
|
for ch, readings in char_readings.items():
|
||||||
|
readings = list(dict.fromkeys(readings))
|
||||||
|
c = counts.get(ch, 0)
|
||||||
|
for rd in readings:
|
||||||
|
if len(readings) == 1:
|
||||||
|
w = 1.0
|
||||||
|
elif (ch, rd) in rank:
|
||||||
|
w = RANK_WEIGHT[rank[(ch, rd)]]
|
||||||
|
elif ch in has_main:
|
||||||
|
w = 0.02
|
||||||
|
else:
|
||||||
|
w = 1.0 / len(readings)
|
||||||
|
add(rd, ch, c * w)
|
||||||
|
|
||||||
|
# Multi-character phrases.
|
||||||
|
for cols in rows("BPMFMappings.txt"):
|
||||||
|
if len(cols) >= 3 and len(cols[0]) == len(cols) - 1:
|
||||||
|
add("-".join(cols[1:]), cols[0], counts.get(cols[0], 0))
|
||||||
|
|
||||||
|
with open(out, "w", encoding="utf-8") as f:
|
||||||
|
f.write("# Generated by scripts/convert-mcbopomofo.py from McBopomofo data (MIT License,\n")
|
||||||
|
f.write("# https://github.com/openvanilla/McBopomofo). Format: <reading> <phrase> <log10 score>\n")
|
||||||
|
for (reading, phrase), score in sorted(entries.items()):
|
||||||
|
f.write(f"{reading} {phrase} {score}\n")
|
||||||
|
# Starter entries come last: the loader keeps the first copy of a duplicate.
|
||||||
|
f.write("\n")
|
||||||
|
f.write(seed.read_text(encoding="utf-8"))
|
||||||
|
|
||||||
|
print(f"{len(entries)} entries from McBopomofo, total occurrences {total}")
|
||||||
Executable
+19
@@ -0,0 +1,19 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Rebuilds Resources/lexicon.txt from the open-source McBopomofo data (MIT License,
|
||||||
|
# https://github.com/openvanilla/McBopomofo). Only McBopomofo's data files are
|
||||||
|
# downloaded and read; none of its code is run. Resources/lexicon-seed.txt (the
|
||||||
|
# hand-written starter lexicon) is appended so its entries stay available.
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
SRC=build/mcbopomofo-src
|
||||||
|
if [ -d "$SRC/.git" ]; then
|
||||||
|
git -C "$SRC" pull -q --depth 1
|
||||||
|
else
|
||||||
|
rm -rf "$SRC"
|
||||||
|
git clone -q --depth 1 --filter=blob:none --sparse https://github.com/openvanilla/McBopomofo.git "$SRC"
|
||||||
|
git -C "$SRC" sparse-checkout set Source/Data
|
||||||
|
fi
|
||||||
|
|
||||||
|
python3 -I scripts/convert-mcbopomofo.py "$SRC/Source/Data" Resources/lexicon-seed.txt Resources/lexicon.txt
|
||||||
|
echo "Rebuild with scripts/install.sh"
|
||||||
Executable
+19
@@ -0,0 +1,19 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Builds and installs AutoZhuyin into ~/Library/Input Methods, restarting any running copy.
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
./scripts/build.sh
|
||||||
|
DEST="$HOME/Library/Input Methods"
|
||||||
|
mkdir -p "$DEST"
|
||||||
|
|
||||||
|
# The running server keeps the old binary; kill it so macOS relaunches the new one.
|
||||||
|
pkill -x AutoZhuyin || true
|
||||||
|
rm -rf "$DEST/AutoZhuyin.app"
|
||||||
|
cp -R build/AutoZhuyin.app "$DEST/"
|
||||||
|
"$DEST/AutoZhuyin.app/Contents/MacOS/AutoZhuyin" --register
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "Installed to $DEST/AutoZhuyin.app"
|
||||||
|
echo "First install: System Settings → Keyboard → Text Input → Edit… → + → 繁體中文 → 自動注音"
|
||||||
|
echo "(If it does not appear, log out and back in once.)"
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
// Renders the menu-bar icon ("注" with a small "A") to a TIFF.
|
||||||
|
// Usage: swift scripts/make-icon.swift <output.tiff>
|
||||||
|
import AppKit
|
||||||
|
|
||||||
|
let out = CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : "icon.tiff"
|
||||||
|
let reps: [NSBitmapImageRep] = [16, 32].map { size in
|
||||||
|
let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: size, pixelsHigh: size,
|
||||||
|
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
|
||||||
|
colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
|
||||||
|
rep.size = NSSize(width: 16, height: 16)
|
||||||
|
NSGraphicsContext.saveGraphicsState()
|
||||||
|
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
|
||||||
|
let font = NSFont.systemFont(ofSize: 13, weight: .semibold)
|
||||||
|
let text = NSAttributedString(string: "注", attributes: [.font: font, .foregroundColor: NSColor.black])
|
||||||
|
let s = text.size()
|
||||||
|
text.draw(at: NSPoint(x: (16 - s.width) / 2, y: (16 - s.height) / 2))
|
||||||
|
NSGraphicsContext.restoreGraphicsState()
|
||||||
|
return rep
|
||||||
|
}
|
||||||
|
let data = NSBitmapImageRep.tiffRepresentationOfImageReps(in: reps, using: .none, factor: 0)!
|
||||||
|
try! data.write(to: URL(fileURLWithPath: out))
|
||||||
|
print("wrote \(out)")
|
||||||
Executable
+41
@@ -0,0 +1,41 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Builds build/AutoZhuyin-<version>.pkg: a universal (Apple Silicon + Intel) installer
|
||||||
|
# that puts AutoZhuyin.app into /Library/Input Methods for all users.
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
./scripts/build.sh
|
||||||
|
|
||||||
|
VERSION="$(plutil -extract CFBundleShortVersionString raw Resources/Info.plist)"
|
||||||
|
ID="com.autozhuyin.inputmethod.pkg"
|
||||||
|
STAGE="build/pkgroot"
|
||||||
|
WORK="build/pkgwork"
|
||||||
|
OUT="build/AutoZhuyin-$VERSION.pkg"
|
||||||
|
|
||||||
|
rm -rf "$STAGE" "$WORK"
|
||||||
|
mkdir -p "$STAGE" "$WORK"
|
||||||
|
cp -R build/AutoZhuyin.app "$STAGE/"
|
||||||
|
chmod +x scripts/pkg/postinstall
|
||||||
|
|
||||||
|
# Always install to /Library/Input Methods, even if another copy exists elsewhere.
|
||||||
|
pkgbuild --analyze --root "$STAGE" "$WORK/component.plist" > "$WORK/analyze.log"
|
||||||
|
plutil -replace 0.BundleIsRelocatable -bool NO "$WORK/component.plist"
|
||||||
|
|
||||||
|
pkgbuild --root "$STAGE" \
|
||||||
|
--component-plist "$WORK/component.plist" \
|
||||||
|
--install-location "/Library/Input Methods" \
|
||||||
|
--scripts scripts/pkg \
|
||||||
|
--identifier "$ID" \
|
||||||
|
--version "$VERSION" \
|
||||||
|
"$WORK/AutoZhuyin-component.pkg"
|
||||||
|
|
||||||
|
# Distribution wrapper: productbuild declares both architectures (hostArchitectures), so
|
||||||
|
# Apple Silicon Macs don't ask for Rosetta. Add an installer title.
|
||||||
|
productbuild --synthesize --package "$WORK/AutoZhuyin-component.pkg" "$WORK/distribution.xml"
|
||||||
|
grep -q 'hostArchitectures="x86_64,arm64"' "$WORK/distribution.xml" \
|
||||||
|
|| sed -i '' 's#<options #<options hostArchitectures="x86_64,arm64" #' "$WORK/distribution.xml"
|
||||||
|
sed -i '' 's#<options #<title>自動注音 AutoZhuyin</title>\
|
||||||
|
<options #' "$WORK/distribution.xml"
|
||||||
|
productbuild --distribution "$WORK/distribution.xml" --package-path "$WORK" "$OUT"
|
||||||
|
|
||||||
|
echo "Built $OUT"
|
||||||
Executable
+19
@@ -0,0 +1,19 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Runs as root after the installer copies AutoZhuyin.app into /Library/Input Methods.
|
||||||
|
APP="/Library/Input Methods/AutoZhuyin.app"
|
||||||
|
|
||||||
|
# Stop a running (old) copy so macOS launches the new one on next use.
|
||||||
|
pkill -x AutoZhuyin || true
|
||||||
|
|
||||||
|
USER_NAME="$(stat -f%Su /dev/console)"
|
||||||
|
if [ -n "$USER_NAME" ] && [ "$USER_NAME" != "root" ]; then
|
||||||
|
USER_ID="$(id -u "$USER_NAME")"
|
||||||
|
USER_HOME="$(dscl . -read "/Users/$USER_NAME" NFSHomeDirectory | awk '{print $2}')"
|
||||||
|
|
||||||
|
# A per-user copy (from scripts/install.sh) would show up as a duplicate entry.
|
||||||
|
rm -rf "$USER_HOME/Library/Input Methods/AutoZhuyin.app"
|
||||||
|
|
||||||
|
# Register in the user's session so it appears in System Settings without logging out.
|
||||||
|
launchctl asuser "$USER_ID" sudo -u "$USER_NAME" "$APP/Contents/MacOS/AutoZhuyin" --register || true
|
||||||
|
fi
|
||||||
|
exit 0
|
||||||
Reference in New Issue
Block a user