ckan 技術介紹 (開發篇)
TRANSCRIPT
CKAN 技術介紹 (開發篇 )
李承錱 (Sol)
中央研究院資訊科學研究所
本著作採用創用 CC 「姓名標示 -相同方式分享」授權條款台灣 3.0版
2
大綱
● 客製化 CKAN功能● 常見客製化議題探討
3
客製化 CKAN功能
修改網頁介面選項
撰寫擴充套件
修改環境設定檔
較困難
較容易
4
客製化 CKAN功能
● 修改網頁介面選項– 位置: SITE_URL/ckan-admin/config
– 需有系統管理員權限– 設定網站配色、 LOGO、簡介、 header CSS、首頁佈局等
● 修改環境設定檔 (production.ini)
– 參見基礎篇:管理與維護● 撰寫擴充套件
– 建議將客製部分置於擴充套件,避免修改核心造成不相容情形
5
常見客製化議題探討
● 自訂詮釋資料 (Metadata)
● 自訂資料授權選項● 資料驗證與格式轉換● 資料視覺化● 自訂資料集過濾器● 資料採集 (Harvesting)
● 多語系支援
6
自訂詮釋資料
● 擴充套件 ckanext-scheming1
– 使用 JSON資料交換語言自訂詮釋資料欄位– 提供多種常用顯示樣板 (Template)
樣板名稱 欄位型態
text.html 自由文字
large_text.html 較大文字 (用於標題等 )
date.html 日期 (西元年 /月 /日 )
markdown.html 文字方塊 (支援Markdown)
select.html 下拉式選單
multiple_choice.html 多選鈕 (核取方塊 )
repeating.html2 多重值 (自由文字 )
1. https://github.com/open-data/ckanext-scheming,相容於 CKAN 2.3以上版本2.由擴充套件 ckanext-repeating提供
7
自訂詮釋資料:範例
{
"field_name": "data_type",
"label": {"en": "Data Type", "zh_TW": "資料類型 "},
"preset": "select",
"form_attrs": {"data-module": "autocomplete"},
"choices": [
{"value": "statistics", "label":{"en": "Statistics", "zh_TW": "統計資料 "}},
...
]
}
{"preset_name": "select",
"values": {
"form_snippet": "select.html",
"display_snippet": "select.html",
"validators": "scheming_required scheming_choices"}}
結果
Source: http://goo.gl/QF9lJA
8
自訂資料授權選項
● 使用 JSON自訂資料授權選項● 使用環境設定檔變數 licenses_group_url指定 JSON定義檔所在網址– 例: licenses_group_url =
http://licenses.opendefinition.org/licenses/groups/od.json
– 注意:使用 licenses_group_url指定的定義檔案,會直接覆寫內建授權清單
9
自訂資料授權選項:範例 {
"status": "active",
"maintainer": "",
"family": "",
"title": "政府資料開放平臺資料使用規範 ",
"domain_data": false,
"is_okd_compliant": false,
"is_generic": true,
"url": "http://data.gov.tw/principle",
"is_osi_compliant": false,
"domain_content": false,
"domain_software": false,
"id": "twogd"
}
資料集顯示
資料集新增 /編輯
Source: http://goo.gl/IMmQHk
10
資料驗證與轉換
● 資料驗證:確保資料品質● 資料轉換:將格式一致化
● 適用於網頁表單及 API上傳● 核心內建部分驗證器 (Validators)與
轉換器 (Converters)1,2
1. 參見http://docs.ckan.org/en/ckan-2.3/extensions/validators.html2. CKAN中無論驗證器或轉換器均被命名為 validator
11
資料驗證與轉換
● 驗證器 (Validator)
– 檢驗使用者輸入– 部分內建驗證器
● natural_number_validtor(自然數 )● is_positive_integer(正整數 )● isodate(ISO8601格式時間 )● not_empty(必填欄位 )● ignore_missing(允許空值 )
12
資料驗證與轉換
● 驗證器 (Validator)
– 自訂例:驗證輸入是否為 JSON格式
def json_validator(value, context): (...) try: json.loads(value) except ValueError: raise Invalid('Invalid JSON') return value
13
資料驗證與轉換
● 轉換器 (Converter)
– 轉換資料格式以一致化– 部分內建轉換器
● int_validator(轉換文數字為整數 )● boolean_validator
(轉換文字為布林值 )● remove_whitespace
(去除前後空白 )
14
資料驗證與轉換
● 轉換器 (Converter)
– 自訂例:去除多重值欄位之重複內容– ['a', 'b', 'c', 'a'] ['a', 'b', 'c']→
def duplicate_validator(key, data, errors, context): (…) value = json.loads(data[key]) unduplicated = list(set(value)) (...)
15
資料視覺化
● 實作 CKAN未提供之資料預覽 /視覺化 (Viewers)1
● 例:擴充地理資料之預覽 3
– WMTS圖磚服務● 提供電子地圖圖資服務● 如:國土測繪中心提供之通用版電子地圖WMTS
– ESRI Shapefile (shp、 dbf與 prj置於一 zip壓縮檔中 )● GIS領域流行之空間資料格式
1. CKAN提供試算表 (csv、 xls)、文字 (txt, xml)、圖片 (png、 jpg、 gif)、網頁(html)、 pdf、 geojson2、wms2等預覽2.由擴充套件 ckanext-spatial提供3.由第 1及第 2點可知, ckanext-spatial僅提供 geojson與wms兩種空間格式預覽
16
資料視覺化範例: Shapefile預覽
CKAN Shapefile預覽 使用QGIS桌面軟體檢視
http://taijiang.tw/dataset/proj4-29
17
撰寫 CKAN擴充套件
● PyUtilib Component Architecture (PCA)擴充架構
1.繼承 ckan.plugins.SingletonPlugin
2.視需求實作一或多個 ckan.plugins.*抽象介面 (Interface)● 如 IResourceView1:針對指定資料格式實作資料預覽
3.若該外掛涉及前端 (Front-end)介面,則需額外撰寫HTML檔與 JavaScript
● 如: Shapefile預覽需與 leaflet2、 shp2geojson.js3等合併使用
1. http://docs.ckan.org/en/ckan-2.3/extensions/plugin-interfaces.html#ckan.plugins.interfaces.IResourceView 2. http://leafletjs.com/ (圖台套件,以 BSD授權釋出 )3. http://gipong.github.io/shp2geojson.js/ (Shapefile-GeoJSON轉換套件,以MIT授權釋出 )
18
資料視覺化範例: Shapefile預覽
from ckan import plugins as p
class SHPView(p.SingletonPlugin): p.implements(p.IResourceView, inherit=True) SHP = ['shp zip'] def info(self): return {'name': 'shp_view', 'title': 'shp', 'icon': 'map-marker', 'iframed': True, 'default_title': 'SHP', } def can_view(self, data_dict): resource = data_dict['resource'] format_lower = resource['format'].lower() if format_lower in self.SHP: return self.same_domain or self.proxy_is_enabled return False def view_template(self, context, data_dict): return 'dataviewer/shp.html'
<div data-module="shppreview" id="data-preview" … ></div>
// shapefile preview moduleckan.module('shppreview', function (jQuery, _) { Return { initialize: function () { (...) } showPreview: function (url, data) { (…) } }}
Python Plugin View Template (shp.html)
JS Module (shp_view.js)
2.
指定實作抽象介
面
1.進入點 :繼承 SingletonPlugin
2.實作抽象介面之方法
3.前端網頁顯示
Source: http://goo.gl/JIY8Ilhttp://goo.gl/jorVvxhttp://goo.gl/BgNVlX
19
自訂資料集過濾器
● 屬性過濾器 (Filters)
– 以指定條件過濾資料集● 自訂過濾器
1.實作 IPackageController與 Ifacets抽象介面2.新增 Solr搜尋索引定義
20
過濾器範例 1:關鍵字搜尋
from ckan import plugins as p
class TaijiangDatasets(p.SingletonPlugin): p.implements(p.IPackageController, inherit=True) p.implements(p.IFacets)
def before_index(self, data_dict): data_dict.update({'theme_keyword_facets': []})
if data_dict.get('theme_keyword'): data_dict['theme_keyword_facets'] = json.loads(data_dict.get('theme_keyword')) return data_dict
def dataset_facets(self, facets_dict, package_type): facets_dict['theme_keyword_facets'] = p.toolkit._('Theme Keyword') return facets_dict
<field name="theme_keyword_facets" type="string" indexed="true" stored="true" multiValued="true"/>
Python Plugin Solr Schema
註:省略前端顯示部分程式碼
結果
指定為 string型別索引
將詮釋資料定義之主題關鍵字 (選項 )置入過濾器
新增主題關鍵字過濾器
Source: http://goo.gl/YxWx1Uhttp://goo.gl/BWuU6I
21
過濾器範例 2:時間搜尋
from ckan import plugins as p
class TaijiangDatasets(p.SingletonPlugin): p.implements(p.IPackageController, inherit=True) p.implements(p.IFacets)
def before_search(self, search_params): (…) begin = parse_date(search_params['extras']['ext_begin_date']) end = parse_date(search_params['extras']['ext_end_date']) (…) query = ("(start_time: [* TO {0}Z] AND end_time: [{0}Z TO *]) OR (start_time: [{0}Z TO {1}Z] AND end_time: [{0}Z TO *])") query = query.format(begin.isoformat(), end.isoformat()) search_params['q'] = query return search_params
def dataset_facets(self, facets_dict, package_type): facets_dict['date_facet'] = p.toolkit._('Date of Dataset') return facets_dict
<dynamicField name="*_time"type="date"indexed="true" stored="true" multiValued="false"/>
Python Plugin Solr Schema
註:省略前端顯示部分程式碼
結果
指定以 time結尾之欄位指定為 date
型別索引
start_time
end_time
Solr搜尋定義
Source:http://goo.gl/C98Pr2http://goo.gl/9TA014
22
資料採集 (Harvesting)
● 以自動化方式,探索 (discovery)網路資源,並收集其資料及詮釋資料,達成資料交換之目的
● 擴充套件 ckanext-harvest
– 支援自動、定時採集指定資料來源– 僅採集詮釋資料 (亦即實體檔案仍位於資料來源 )
● 支援採集之資料來源– CKAN(內建 )
– CSW (Catalog Service for the Web)*
– WAF (Web Accessible Folder)*
– 自訂來源 (csv、 xls、網站等 )*由擴充套件 ckanext-spatial提供
23
資料採集:自訂採集來源 -SRDA*
from ckan import plugins as p
class SRDAHarvester(SingletonPlugin):
p.implements(IHarvester)
def info(self): (...)
def gather_stage(self, harvest_job): (…)
def fetch_stage(self, harvest_object): (…)
def import_stage(self, harvest_object): (…)
*SRDA=Survey Research Data Archive (中研院人社中心調研中心學術調查研究資料庫 )
結果
Python Plugin
取得 (詮釋 )資料清單
實際取得 (詮釋 )資料
匯入為 CKAN資料集
Source: http://goo.gl/LS79s4
24
資料採集:操作方式
● paster --plugin=ckanext-harvest harvester command -c /etc/ckan/default/production.ini
– gather_consumer:取得 (詮釋 )資料清單– fetch_consumer:實際取得資料– run:匯入為CKAN資料集
● 可使用 Supervisor與 cron job排程執行採集工作– 參見: https://github.com/ckan/ckanext-harvest#setting-up-
the-harvesters-on-a-production-server
需維持執行狀態
25
多語系支援
● 介面翻譯– GNU gettext
– 語法: _('待翻譯文字 ')● Python: p.toolkit._('String')● Jinja Template (HTML): {{ _('String') }}● JavaScript: _('String')_
– 主程式線上翻譯專案● Transifex.com Open Knowledge / CKAN→
26
多語系支援
● 擴充套件翻譯– opendatatrentino/ckan-custom-translations (GitHub)
– 將擴充套件與主程式之翻譯檔 (.po)合併– 需在環境設定檔指定新翻譯檔目錄 (ckan.i18n_directory變數 )
● 詮釋資料翻譯– 已設計於 JSON詮釋資料定義中 *
– 例: "label": {"en": "Data Type", "zh_TW": "資料類型 "}
*使用 ckanext-scheming 自訂詮釋資料時
27
多語系支援
● 中文關鍵字搜尋– Solr + mmseg4j1 (Java斷詞器 )
– Maximum Matching Algorithm2
– 複製mmseg4j至 Solr目錄,並修改 Solr索引定義檔– 參考: http://is.gd/2Vpzgb
1. https://github.com/chenlb/mmseg4j-solr (以 Apache 2.0授權釋出 )2. http://technology.chtsai.org/mmseg/
28
開發篇重點摘要
● 客製化 CKAN功能之方法– 網頁介面選項、修改系統設定檔、撰寫擴充套件– 盡可能將客製部分置於擴充套件
● 常見客製化議題與實作– JSON自定義欄位– PCA擴充架構– Gettext介面翻譯語法– Solr中文搜尋
29
感謝聆聽 敬請指教 Email: cjlee AT iis.sinica.edu.tw