orange3 插件开发知识点积累

蒋高扬
2023-12-01

一、安装orange3

python版本 3.6.8

pip install orange3

pip install PyQt5

学习官网:OWWidget — Orange Development 3 documentation

The Data — Orange Data Mining Library 3 documentation

Orange Data Mining - Blogs

启动命令:orange-canvas

附上一份python freeze

AnyQt==0.0.10
baycomp==1.0.2
Bottleneck==1.3.2
CacheControl==0.12.6
certifi==2019.11.28
chardet==3.0.4
click==7.1.1
commonmark==0.9.1
config==0.4.2
contextvars==2.4
cycler==0.10.0
dbs==0.0.0
decorator==4.4.2
dictdiffer==0.8.1
dlib==19.8.1
docutils==0.16
easydict==1.9
et-xmlfile==1.0.1
face-recognition==1.3.0
face-recognition-models==0.3.0
graphviz==0.8.4
h11==0.9.0
h2==3.2.0
hpack==3.0.0
hstspreload==2020.5.5
httpx==0.12.1
hyperframe==5.2.0
idna==2.6
imageio==2.8.0
immutables==0.12
importlib-metadata==1.6.0
jdcal==1.4.1
joblib==0.14.1
keyring==21.2.1
keyrings.alt==3.4.0
kiwisolver==1.1.0
lockfile==0.12.2
logger==1.4
matplotlib==3.2.0
msgpack==1.0.0
mxnet==1.6.0
networkx==2.4
numpy==1.16.6
oauthlib==3.1.0
opencv-python==4.2.0.32
openpyxl==3.0.3
openTSNE==0.4.3
orange-canvas-core==0.1.12
orange-widget-base==4.5.0
Orange3==3.25.0
pandas==1.0.3
Pillow==6.2.2
PyMySQL==0.9.3
pyparsing==2.4.6
PyQt5==5.13.2
PyQt5-sip==12.7.1
pyqt5-tools==5.13.2.1.6rc1
pyqtgraph==0.10.0
PyQtWebEngine==5.13.2
python-dateutil==2.8.1
python-dotenv==0.13.0
python-louvain==0.14
pytz==2020.1
PyWavelets==1.1.1
pywin32-ctypes==0.2.0
PyYAML==5.3.1
requests==2.23.0
requests-oauthlib==1.3.0
rfc3986==1.4.0
scikit-image==0.16.2
scikit-learn==0.22.2.post1
scipy==1.4.1
serverfiles==0.3.0
six==1.14.0
sniffio==1.1.0
torch==1.2.0
torchvision==0.4.0
urllib3==1.24.3
xlrd==1.2.0
XlsxWriter==1.2.8
zipp==3.1.0

二、插件开发

参照项目代码  o3dbs 

安装自带插件,在orange3图形化界面  options下Add-ons

import sys
import urllib.parse
import Orange.data
import requests
import json

from Orange.widgets import widget, gui
from Orange.widgets.settings import Setting
from Orange.data import StringVariable
from PyQt5.QtWidgets import QApplication

class OWDbsKeySearch(widget.OWWidget):
    name = "Dbs key Search"
    description = "Randomly selects a subset of instances from the data set"
    icon = "icons/find.svg"
    priority = 10

    # class Outputs:
    #     sample = Output("Data", Orange.data.Table)
    outputs = [("Data", Orange.data.Table)]
    # Basic (convenience) GUI definition:
    #   a simple 'single column' GUI layout
    want_main_area = False
    #   with a fixed non resizable geometry.
    resizing_enabled = False

    ketString = Setting('')

    def __init__(self):
        super().__init__()
        # GUI
        box = gui.widgetBox(self.controlArea, "关键字查询")
        gui.widgetLabel(box, '')

        gui.lineEdit(self.controlArea, self, "ketString", "输入关键字段",
                     orientation="horizontal", box="ketString",
                     # callback=self.set_data,
                     valueType=str)

        # self.set_data()
        gui.button(self.buttonsArea, self, "查询",
                   callback=self.set_data)

    def set_data(self):

        print(self.ketString)

        url = "http://***/dbs/search?keyword=" + urllib.parse.quote(self.ketString.encode('utf-8')) + \
              "&attributes={id,sid,name,value}"

        header = {'Content-Type': 'application/json'}
        try:
            response = requests.get(url, headers=header)
            res = response.text
            res = json.loads(res)
            arr = []
            for i in res:
                for v in res[i]:
                    arr.append([i, res[i][v]['name'], res[i][v]['id'], res[i][v]['sid'],
                                res[i][v]['value']])

            metas = [StringVariable("对象类别"),
                     StringVariable("对象名称"),
                     StringVariable("对象id"),
                     StringVariable("对象sid"),
                     StringVariable("值")]
            domain = Orange.data.Domain([],
                                        metas=metas)
            table = Orange.data.Table.from_list(domain, arr)
            self.send('Data', table)
        except BaseException as e:
            print(e)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = OWDbsKeySearch()
    win.show()
    sys.exit(app.exec_())
import sys
import numpy
import urllib.parse
import Orange.data
import requests
import json
import datetime

from Orange.widgets import widget
from Orange.data import *
from PyQt5.QtWidgets import QApplication


class CsvTable(widget.OWWidget):
    name = "Dbs CsvTable"
    description = "Randomly selects a subset of instances from the data set"
    icon = "icons/scv.svg"
    priority = 10

    # class Outputs:
    #     sample = Output("Data", Orange.data.Table)
    inputs = [("Data", Orange.data.Table, "set_data"), ("Start_Date", str, "set_start_date"),
              ("End_Date", str, "set_end_date"), ("Interval", str, "set_interval")]
    outputs = [("Data", Orange.data.Table)]
    # Basic (convenience) GUI definition:
    #   a simple 'single column' GUI layout
    want_main_area = False

    startTime = ''
    endTime = ''
    inter = ''

    def __init__(self):
        super().__init__()
        self.table = None

    def set_start_date(self, start):
        self.startTime = start

    def set_end_date(self, end):
        self.endTime = end

    def set_interval(self, interval):
        self.inter = interval

    def set_data(self, table):
        self.table = table
        #print(table[0].metas[3])
        print("table行数")
        print(table)
        captions = "{"
        for n in table:
            captions = captions + n.metas[0] + ":" + n.metas[3] + ":value::::" + n.metas[2] + ","
        print(captions)
        captions = captions + "}"
        if self.inter == '':
            self.inter = '5m'
        url = "http://***?captions=" + urllib.parse.quote(captions.encode('utf-8')) + \
              "&interval=" + self.inter

        if self.endTime == '':
            today = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        else:
            today = self.endTime
        if self.startTime == '':
            yesterday = (datetime.datetime.now()+datetime.timedelta(days=-1)).strftime("%Y-%m-%d %H:%M:%S")
        else:
            yesterday = self.startTime

        print('today:' + today)
        print('yesterday:' + yesterday)
        url = url + "&begin=" + yesterday + "&end=" + today
        header = {'Content-Type': 'application/json'}
        try:
            response = requests.get(url, headers=header)
            res = response.text
            res = json.loads(res)
            arr = []
            metas = []
            attributes = []
            print("计算列数:cols")
            cols = len(list(res))  # 计算列数
            print(cols)
            attributes.append(TimeVariable("时间"))
            for i in res:

                attributes.append(ContinuousVariable(i, number_of_decimals=2))
                temp = []
                time = []
                for v in res[i]:
                    datearray = datetime.datetime.fromtimestamp(int(v))
                    otherstyleTime = datearray.strftime("%Y-%m-%d %H:%M:%S")
                    rows = len(list(res[i]))  # 计算行数
                    time.append([otherstyleTime])
                    temp.append([float(res[i][v])])
                if len(arr):
                    arr = numpy.hstack((arr, temp))  # 水平组合
                else:
                    arr = time
                    arr = numpy.hstack((arr, temp))  # 水平组合
            # 数组重排
            # b = numpy.array(arr).reshape(rows, cols*2)

            # 数组切片
            # a = numpy.array(arr)
            # for num in range(cols):
            #     print(num)
            # c = a[0: rows, 0: 2]
            domain = Orange.data.Domain(attributes)
            table = Orange.data.Table.from_list(domain, arr)
            self.send('Data', table)
        except BaseException as e:
            print(e)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = CsvTable()
    win.show()
    sys.exit(app.exec_())
import sys
from Orange.widgets import widget, gui
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QDate,  QDateTime
from Orange.widgets.settings import Setting


class Interval(widget.OWWidget):

    name = "Dbs Interval"
    description = "Select Interval"
    icon = "icons/interval.svg"
    priority = 10

    # class Outputs:
    #     sample = Output("Data", Orange.data.Table)
    outputs = [("Interval", str)]
    # Basic (convenience) GUI definition:
    #   a simple 'single column' GUI layout
    want_main_area = False
    interval = Setting('')

    def __init__(self):
        super(Interval, self).__init__()
        # GUI
        box = gui.widgetBox(self.controlArea, "时间间隔")
        gui.widgetLabel(box, '')

        gui.lineEdit(self.controlArea, self, "interval", "输入时间间隔",
                     orientation="horizontal", box="interval",
                     callback=self.set_data,
                     valueType=str)

    def set_data(self):
        print(self.interval)
        self.send("Interval", self.interval)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Interval()
    demo.show()
    sys.exit(app.exec_())

 类似资料: