Files
nixevol 28170a7fe2 feat: 补齐全量网格成果并改用竞对图层名
全量包与单市场包含同类完整数据且不含 online;AOI 由报表按最大接触面积自动匹配。Excel 占比写成文本百分号,竞对信号文件和图层改用正确用字。
2026-09-28 11:08:16 +08:00

101 lines
5.3 KiB
Python

"""按用户样板生成两个楼宇专题及其默认 QGIS 样式。"""
from contextlib import closing
from pathlib import Path
import json
import sqlite3
from datetime import datetime, timezone
from time import sleep
import xml.etree.ElementTree as ET
from .gpkg import quote_identifier
STYLES = Path(__file__).with_name('styles')
THEMES = json.loads((STYLES / 'themes.json').read_text(encoding='utf-8'))
# 暂停生成移动 WIFI 专题;保留其样板、字段和代码,后续恢复时只需改回 THEMES。
ACTIVE_THEMES = [theme for theme in THEMES if theme['key'] != 'mobile_wifi']
# ACTIVE_THEMES = THEMES # 需要恢复移动 WIFI 专题时启用这一行,并停用上一行。
def _vacuum(path):
for attempt in range(10):
try:
with closing(sqlite3.connect(path)) as conn:
conn.execute("VACUUM")
return
except PermissionError:
if attempt == 9:
raise
sleep(0.3)
def export_themes(source_path):
results = []
with closing(sqlite3.connect(source_path)) as source:
available = {r[1] for r in source.execute('pragma table_info(NRBuildingsData)')}
for theme in ACTIVE_THEMES:
fields = ['fid', *[name for name, _ in theme['fields']], 'geom']
missing = set(fields) - available
if missing:
raise ValueError(f"{theme['name']} 缺少字段:{', '.join(sorted(missing))}")
output = Path(source_path).with_name(theme['name'] + '.gpkg')
with closing(sqlite3.connect(output)) as target:
source.backup(target)
target.execute('PRAGMA application_id=1196444487')
target.execute('PRAGMA user_version=10400')
with target:
# 保留源几何、主键、索引和 CRS,仅精简业务字段。
for name in available - set(fields):
target.execute(f'ALTER TABLE NRBuildingsData DROP COLUMN {quote_identifier(name)}')
target.execute('DROP TABLE IF EXISTS layer_styles')
target.execute('CREATE TABLE layer_styles (id INTEGER PRIMARY KEY, f_table_catalog TEXT, f_table_schema TEXT, f_table_name TEXT, f_geometry_column TEXT, styleName TEXT, styleQML TEXT, styleSLD TEXT, useAsDefault BOOLEAN, description TEXT, owner TEXT, ui TEXT, update_time DATETIME)')
target.execute('INSERT INTO layer_styles VALUES (1,?,?,?,?,?,?,?,?,?,?,?,?)',
('', '', 'NRBuildingsData', 'geom', theme['style_name'],
(STYLES / (theme['key'] + '.qml')).read_text(encoding='utf-8'),
'', 1, '', '', None, datetime.now(timezone.utc).isoformat()))
target.execute("INSERT OR REPLACE INTO gpkg_contents(table_name,data_type,srs_id) VALUES ('layer_styles','attributes',0)")
# Windows 上不能在仍打开该文件的连接里 VACUUM,否则替换文件会报 WinError 32。
_vacuum(output)
with closing(sqlite3.connect(output)) as target:
count = target.execute('SELECT count(*) FROM NRBuildingsData').fetchone()[0]
results.append({'output': str(output), 'feature_count': count, 'name': theme['name']})
return results
def add_theme_layers(root, extent):
from .qgis import remove_qgis_layer, set_xml_extent
remove_qgis_layer(root, 'NRBuildingsData.gpkg', required=False)
tree = root.find('layer-tree-group')
# 倒序插入,保持样板中 C 端在 WIFI 上方。
for theme in reversed(ACTIVE_THEMES):
filename = theme['name'] + '.gpkg'
remove_qgis_layer(root, filename, required=False)
layer = ET.parse(STYLES / (theme['key'] + '.xml')).getroot()
layer_id = 'market_' + theme['key']
layer.find('id').text = layer_id
datasource = './' + filename + '|layername=NRBuildingsData'
layer.find('datasource').text = datasource
for tag in ('extent', 'wgs84extent'):
element = layer.find(tag)
if element is None:
element = ET.SubElement(layer, tag)
set_xml_extent(element, extent)
root.find('projectlayers').append(layer)
tree.insert(0, ET.Element('layer-tree-layer', id=layer_id, name=theme['name'], source=datasource,
providerKey='ogr', checked=theme['checked'], expanded='0'))
order = tree.find('custom-order')
if order is not None:
item = ET.Element('item'); item.text = layer_id; order.insert(0, item)
order = root.find('layerorder')
if order is not None:
order.insert(0, ET.Element('layer', id=layer_id))
visibility = json.loads((STYLES / 'visibility.json').read_text(encoding='utf-8'))
for element in tree.iter('layer-tree-layer'):
if element.get('name') in visibility:
element.set('checked', visibility[element.get('name')])
for element in root.findall('legend/legendlayer'):
if element.get('name') in visibility:
checked = visibility[element.get('name')]
element.set('checked', checked)
for child in element.iter('legendlayerfile'):
child.set('visible', '1' if checked == 'Qt::Checked' else '0')