import
requests
import
subprocess
import
os
from
datetime
import
datetime
from
bs4
import
BeautifulSoup
CONFIG
=
{
"github"
: {
"enable"
:
True
,
"api_url"
:
"https://api.github.com/repos/outloudvi/mw2fcitx/releases/latest"
,
"target_file"
:
"moegirl.dict.yaml"
},
"sogou"
: {
"enable"
:
True
,
"list_url"
:
"https://pinyin.sogou.com/dict/search/search_list/%CD%F8%C2%E7%C1%F7%D0%D0%D0%C2%B4%CA/normal"
,
"download_url"
:
"https://pinyin.sogou.com/d/dict/download_cell.php?id=4&name=网络流行新词&f=detail"
,
"converter_path"
:
"D:\\Tools\\publish\\深蓝词库转换.exe"
,
},
"headers"
: {
"User-Agent"
:
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
},
"version_file"
:
"D:\\Cache\\Weasel\\dict.version"
,
"dict_dir"
:
"D:\\Applications\\Weasel\\Rime\\cn_dicts\\"
,
"temp_dir"
:
"D:\\Cache\\Weasel\\"
,
"log_dir"
:
"D:\\Cache\\Weasel\\"
}
class
UpdateLogger:
def
__init__(
self
):
self
.logs
=
[]
self
.start_time
=
datetime.now()
def
add(
self
, message, task
=
""):
timestamp
=
datetime.now().strftime(
'%Y-%m-%d %H:%M:%S'
)
entry
=
f
"[{timestamp}] {'['+task+'] ' if task else ''}{message}"
self
.logs.append(entry)
def
save(
self
):
os.makedirs(CONFIG[
"log_dir"
], exist_ok
=
True
)
log_file
=
f
"{CONFIG['log_dir']}update_{self.start_time.strftime('%Y%m%d')}.log"
with
open
(log_file,
"w"
, encoding
=
"utf-8"
) as f:
f.write(
"\n"
.join(
self
.logs))
return
log_file
def
update_version_file(target_prefix, new_version):
try
:
lines
=
[]
try
:
with
open
(CONFIG[
"version_file"
],
"r"
) as f:
lines
=
f.readlines()
except
FileNotFoundError:
pass
found
=
False
for
i, line
in
enumerate
(lines):
if
line.startswith(target_prefix):
lines[i]
=
f
"{target_prefix}{new_version}\n"
found
=
True
break
if
not
found:
lines.append(f
"{target_prefix}{new_version}\n"
)
with
open
(CONFIG[
"version_file"
],
"w"
) as f:
f.writelines(lines)
return
True
except
Exception as e:
return
False
def
github_task(logger):
cfg
=
CONFIG[
"github"
]
try
:
local_version
=
"0"
try
:
with
open
(CONFIG[
"version_file"
],
"r"
) as f:
for
line
in
f:
if
line.startswith(
"[moegirl_dict]:"
):
local_version
=
line[
len
(
"[moegirl_dict]:"
):].strip()
break
except
FileNotFoundError:
logger.add(
"初始化本地版本"
,
"GitHub"
)
response
=
requests.get(cfg[
"api_url"
], headers
=
CONFIG[
"headers"
], timeout
=
10
)
response.raise_for_status()
release_data
=
response.json()
remote_version
=
release_data[
"tag_name"
]
logger.add(f
"本地版本: {local_version} → 远程版本: {remote_version}"
,
"GitHub"
)
if
remote_version > local_version:
asset
=
next
((a
for
a
in
release_data[
"assets"
]
if
a[
"name"
]
=
=
cfg[
"target_file"
]),
None
)
if
asset:
os.makedirs(CONFIG[
"dict_dir"
], exist_ok
=
True
)
save_path
=
os.path.join(CONFIG[
"dict_dir"
], cfg[
"target_file"
])
response
=
requests.get(asset[
"browser_download_url"
])
response.raise_for_status()
with
open
(save_path,
"wb"
) as f:
f.write(response.content)
with
open
(CONFIG[
"version_file"
],
"w"
) as f:
f.write(
"[moegirl_dict]:"
+
remote_version)
if
update_version_file(
"[moegirl_dict]:"
, remote_version):
logger.add(f
"成功更新到版本 {remote_version}"
,
"GitHub"
)
else
:
logger.add(
"更新版本文件失败"
,
"GitHub"
)
return
True
logger.add(
"未找到目标文件"
,
"GitHub"
)
return
False
logger.add(
"当前已是最新版本"
,
"GitHub"
)
return
True
except
Exception as e:
logger.add(f
"更新失败: {str(e)}"
,
"GitHub"
)
return
False
def
sogou_task(logger):
cfg
=
CONFIG[
"sogou"
]
try
:
response
=
requests.get(cfg[
"list_url"
], headers
=
CONFIG[
"headers"
], timeout
=
10
)
response.raise_for_status()
soup
=
BeautifulSoup(response.text,
'html.parser'
)
target
=
soup.find(
'a'
, string
=
"网络流行新词"
)
if
not
target:
logger.add(
"未找到目标词库"
,
"Sogou"
)
return
False
update_div
=
target.find_parent(
'div'
,
class_
=
'dict_detail_block'
).find(
'div'
,
class_
=
'show_title'
, string
=
"更新时间:"
).find_next_sibling(
'div'
,
class_
=
'show_content'
)
if
not
update_div:
logger.add(
"未找到更新时间"
,
"Sogou"
)
return
False
web_time
=
datetime.strptime(update_div.get_text(strip
=
True
),
"%Y-%m-%d %H:%M:%S"
)
local_time
=
datetime.
min
try
:
with
open
(CONFIG[
"version_file"
],
'r'
) as f:
for
line
in
f:
if
line.startswith(
"[Sogou_dict]:"
):
local_time
=
datetime.strptime(line[
len
(
"[Sogou_dict]:"
):].strip(),
"%Y-%m-%d %H:%M:%S"
)
break
except
FileNotFoundError:
logger.add(
"初始化本地版本"
,
"GitHub"
)
if
web_time <
=
local_time:
logger.add(
"当前已是最新版本"
,
"Sogou"
)
return
True
logger.add(f
"本地版本: {local_time.strftime('%Y-%m-%d %H:%M:%S')} → 远程版本: {web_time.strftime('%Y-%m-%d %H:%M:%S')}"
,
"Sogou"
)
scel_path
=
CONFIG[
"temp_dir"
]
+
"网络流行新词.scel"
temp_txt_path
=
CONFIG[
"temp_dir"
]
+
"temp.txt"
response
=
requests.get(cfg[
"download_url"
], headers
=
CONFIG[
"headers"
])
response.raise_for_status()
with
open
(scel_path,
'wb'
) as f:
f.write(response.content)
subprocess.run([
cfg[
"converter_path"
],
"-i:scel"
, scel_path,
"-o:rime"
, temp_txt_path,
"-ct:pinyin"
,
"-os:windows"
], check
=
True
)
with
open
(temp_txt_path,
'r'
, encoding
=
'utf-8'
) as f:
content
=
[line.rstrip()[:
-
1
]
+
"\n"
for
line
in
f
if
line.strip()
and
not
line.startswith((
"#"
,
"name"
,
"version"
,
"sort"
))]
header
=
[
"---\n"
,
"name: sougou\n"
,
f
'version: "{datetime.now().strftime("%Y-%m-%d")}"\n'
,
"sort: by_weight\n\n"
"...\n"
]
output_path
=
CONFIG[
"dict_dir"
]
+
"sougou.dict.yaml"
os.makedirs(os.path.dirname(output_path), exist_ok
=
True
)
with
open
(output_path,
'w'
, encoding
=
'utf-8'
) as f:
f.writelines(header
+
content)
os.remove(temp_txt_path)
os.remove(scel_path)
if
update_version_file(
"[Sogou_dict]:"
, web_time.strftime(
"%Y-%m-%d %H:%M:%S"
)):
logger.add(f
"成功更新到版本 {web_time.strftime('%Y-%m-%d %H:%M:%S')}"
,
"Sogou"
)
else
:
logger.add(
"更新版本文件失败"
,
"Sogou"
)
return
True
except
Exception as e:
logger.add(f
"更新失败: {str(e)}"
,
"Sogou"
)
return
False
def
main():
logger
=
UpdateLogger()
logger.add(
"开始自动更新任务"
)
if
CONFIG[
"github"
][
"enable"
]:
github_task(logger)
if
CONFIG[
"sogou"
][
"enable"
]:
sogou_task(logger)
logger.add(
"所有任务执行完成"
)
log_path
=
logger.save()
print
(f
"日志已保存至: {log_path}"
)
if
__name__
=
=
"__main__"
:
main()