lca_index
int64 0
223
| idx
stringlengths 7
11
| line_type
stringclasses 6
values | ground_truth
stringlengths 2
35
| completions
sequencelengths 3
1.16k
| prefix
stringlengths 298
32.8k
| postfix
stringlengths 0
28.6k
| repo
stringclasses 34
values |
---|---|---|---|---|---|---|---|
14 | 14-123-31 | random | sql | [
"Accumulator",
"AccumulatorParam",
"accumulators",
"Any",
"BarrierTaskContext",
"BarrierTaskInfo",
"BasicProfiler",
"bin",
"Broadcast",
"broadcast",
"Callable",
"cast",
"cloudpickle",
"conf",
"context",
"copy_func",
"CPickleSerializer",
"daemon",
"data",
"errors",
"examples",
"files",
"filterwarnings",
"find_spark_home",
"HiveContext",
"inheritable_thread_target",
"InheritableThread",
"install",
"instrumentation_utils",
"jars",
"java_gateway",
"join",
"keyword_only",
"licenses",
"MarshalSerializer",
"ml",
"mllib",
"Optional",
"pandas",
"Profiler",
"profiler",
"python",
"RDD",
"rdd",
"RDDBarrier",
"rddsampler",
"resource",
"resultiterable",
"Row",
"sbin",
"serializers",
"shell",
"shuffle",
"since",
"SparkConf",
"SparkContext",
"SparkFiles",
"SparkJobInfo",
"SparkStageInfo",
"sql",
"SQLContext",
"statcounter",
"status",
"StatusTracker",
"StorageLevel",
"storagelevel",
"streaming",
"TaskContext",
"taskcontext",
"testing",
"traceback_utils",
"types",
"TypeVar",
"Union",
"util",
"version",
"worker",
"worker_util",
"wraps",
"_F",
"_globals",
"_NoValue",
"_typing",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | """
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
"""
import mock
import pyspark
from dataproc_templates.jdbc.jdbc_to_gcs import JDBCToGCSTemplate
import dataproc_templates.util.template_constants as constants
class TestJDBCToGCSTemplate:
"""
Test suite for JDBCToGCSTemplate
"""
def test_parse_args1(self):
"""Tests JDBCToGCSTemplate.parse_args()"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.input.partitioncolumn=column",
"--jdbctogcs.input.lowerbound=1",
"--jdbctogcs.input.upperbound=2",
"--jdbctogcs.numpartitions=5",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=csv",
"--jdbctogcs.output.mode=append",
"--jdbctogcs.output.partitioncolumn=column"
])
assert parsed_args["jdbctogcs.input.url"] == "url"
assert parsed_args["jdbctogcs.input.driver"] == "driver"
assert parsed_args["jdbctogcs.input.table"] == "table1"
assert parsed_args["jdbctogcs.input.partitioncolumn"] == "column"
assert parsed_args["jdbctogcs.input.lowerbound"] == "1"
assert parsed_args["jdbctogcs.input.upperbound"] == "2"
assert parsed_args["jdbctogcs.numpartitions"] == "5"
assert parsed_args["jdbctogcs.output.location"] == "gs://test"
assert parsed_args["jdbctogcs.output.format"] == "csv"
assert parsed_args["jdbctogcs.output.mode"] == "append"
assert parsed_args["jdbctogcs.output.partitioncolumn"] == "column"
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_pass_args2(self, mock_spark_session):
"""Tests JDBCToGCSTemplate write parquet"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.input.partitioncolumn=column",
"--jdbctogcs.input.lowerbound=1",
"--jdbctogcs.input.upperbound=2",
"--jdbctogcs.numpartitions=5",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=parquet",
"--jdbctogcs.output.mode=overwrite"
])
mock_spark_session.read.format().option().option().option().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_PARTITIONCOLUMN, "column")
mock_spark_session.read.format().option().option().option().option().option.assert_called_with(constants.JDBC_LOWERBOUND, "1")
mock_spark_session.read.format().option().option().option().option().option().option.assert_called_with(constants.JDBC_UPPERBOUND, "2")
mock_spark_session.read.format().option().option().option().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "5")
mock_spark_session.read.format().option().option().option().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_OVERWRITE)
mock_spark_session.dataframe.DataFrame.write.mode().parquet.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_pass_args3(self, mock_spark_session):
"""Tests JDBCToGCSTemplate write avro"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.input.partitioncolumn=column",
"--jdbctogcs.input.lowerbound=1",
"--jdbctogcs.input.upperbound=2",
"--jdbctogcs.numpartitions=5",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=avro",
"--jdbctogcs.output.mode=append"
])
mock_spark_session.read.format().option().option().option().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_PARTITIONCOLUMN, "column")
mock_spark_session.read.format().option().option().option().option().option.assert_called_with(constants.JDBC_LOWERBOUND, "1")
mock_spark_session.read.format().option().option().option().option().option().option.assert_called_with(constants.JDBC_UPPERBOUND, "2")
mock_spark_session.read.format().option().option().option().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "5")
mock_spark_session.read.format().option().option().option().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_APPEND)
mock_spark_session.dataframe.DataFrame.write.mode().format.assert_called_once_with(constants.FORMAT_AVRO)
mock_spark_session.dataframe.DataFrame.write.mode().format().save.assert_called_once_with("gs://test")
@mock.patch.object(pyspark. | , 'SparkSession')
def test_run_pass_args4(self, mock_spark_session):
"""Tests JDBCToGCSTemplate write csv"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.input.partitioncolumn=column",
"--jdbctogcs.input.lowerbound=1",
"--jdbctogcs.input.upperbound=2",
"--jdbctogcs.numpartitions=5",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=csv",
"--jdbctogcs.output.mode=ignore"
])
mock_spark_session.read.format().option().option().option().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_PARTITIONCOLUMN, "column")
mock_spark_session.read.format().option().option().option().option().option.assert_called_with(constants.JDBC_LOWERBOUND, "1")
mock_spark_session.read.format().option().option().option().option().option().option.assert_called_with(constants.JDBC_UPPERBOUND, "2")
mock_spark_session.read.format().option().option().option().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "5")
mock_spark_session.read.format().option().option().option().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_IGNORE)
mock_spark_session.dataframe.DataFrame.write.mode().option.assert_called_once_with(constants.CSV_HEADER, True)
mock_spark_session.dataframe.DataFrame.write.mode().option().csv.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_pass_args5(self, mock_spark_session):
"""Tests JDBCToGCSTemplate write json"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.input.partitioncolumn=column",
"--jdbctogcs.input.lowerbound=1",
"--jdbctogcs.input.upperbound=2",
"--jdbctogcs.numpartitions=5",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=json",
"--jdbctogcs.output.mode=ignore"
])
mock_spark_session.read.format().option().option().option().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_PARTITIONCOLUMN, "column")
mock_spark_session.read.format().option().option().option().option().option.assert_called_with(constants.JDBC_LOWERBOUND, "1")
mock_spark_session.read.format().option().option().option().option().option().option.assert_called_with(constants.JDBC_UPPERBOUND, "2")
mock_spark_session.read.format().option().option().option().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "5")
mock_spark_session.read.format().option().option().option().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_IGNORE)
#mock_spark_session.dataframe.DataFrame.write.mode().json.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_pass_args6(self, mock_spark_session):
"""Tests JDBCToGCSTemplate pass args"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=csv",
"--jdbctogcs.output.mode=append"
])
mock_spark_session.read.format().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "10")
mock_spark_session.read.format().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_APPEND)
mock_spark_session.dataframe.DataFrame.write.mode().option.assert_called_once_with(constants.CSV_HEADER, True)
mock_spark_session.dataframe.DataFrame.write.mode().option().csv.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_pass_args7(self, mock_spark_session):
"""Tests JDBCToGCSTemplate pass args"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=csv",
"--jdbctogcs.output.mode=append",
"--jdbctogcs.output.partitioncolumn=column"
])
mock_spark_session.read.format().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "10")
mock_spark_session.read.format().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_APPEND)
mock_spark_session.dataframe.DataFrame.write.mode().partitionBy.assert_called_once_with("column")
mock_spark_session.dataframe.DataFrame.write.mode().partitionBy().option.assert_called_once_with(constants.CSV_HEADER, True)
mock_spark_session.dataframe.DataFrame.write.mode().partitionBy().option().csv.assert_called_once_with("gs://test") | googlecloudplatform__dataproc-templates |
14 | 14-142-29 | common | run | [
"build",
"get_logger",
"parse_args",
"run",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
"""
import mock
import pyspark
from dataproc_templates.jdbc.jdbc_to_gcs import JDBCToGCSTemplate
import dataproc_templates.util.template_constants as constants
class TestJDBCToGCSTemplate:
"""
Test suite for JDBCToGCSTemplate
"""
def test_parse_args1(self):
"""Tests JDBCToGCSTemplate.parse_args()"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.input.partitioncolumn=column",
"--jdbctogcs.input.lowerbound=1",
"--jdbctogcs.input.upperbound=2",
"--jdbctogcs.numpartitions=5",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=csv",
"--jdbctogcs.output.mode=append",
"--jdbctogcs.output.partitioncolumn=column"
])
assert parsed_args["jdbctogcs.input.url"] == "url"
assert parsed_args["jdbctogcs.input.driver"] == "driver"
assert parsed_args["jdbctogcs.input.table"] == "table1"
assert parsed_args["jdbctogcs.input.partitioncolumn"] == "column"
assert parsed_args["jdbctogcs.input.lowerbound"] == "1"
assert parsed_args["jdbctogcs.input.upperbound"] == "2"
assert parsed_args["jdbctogcs.numpartitions"] == "5"
assert parsed_args["jdbctogcs.output.location"] == "gs://test"
assert parsed_args["jdbctogcs.output.format"] == "csv"
assert parsed_args["jdbctogcs.output.mode"] == "append"
assert parsed_args["jdbctogcs.output.partitioncolumn"] == "column"
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_pass_args2(self, mock_spark_session):
"""Tests JDBCToGCSTemplate write parquet"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.input.partitioncolumn=column",
"--jdbctogcs.input.lowerbound=1",
"--jdbctogcs.input.upperbound=2",
"--jdbctogcs.numpartitions=5",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=parquet",
"--jdbctogcs.output.mode=overwrite"
])
mock_spark_session.read.format().option().option().option().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_PARTITIONCOLUMN, "column")
mock_spark_session.read.format().option().option().option().option().option.assert_called_with(constants.JDBC_LOWERBOUND, "1")
mock_spark_session.read.format().option().option().option().option().option().option.assert_called_with(constants.JDBC_UPPERBOUND, "2")
mock_spark_session.read.format().option().option().option().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "5")
mock_spark_session.read.format().option().option().option().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_OVERWRITE)
mock_spark_session.dataframe.DataFrame.write.mode().parquet.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_pass_args3(self, mock_spark_session):
"""Tests JDBCToGCSTemplate write avro"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.input.partitioncolumn=column",
"--jdbctogcs.input.lowerbound=1",
"--jdbctogcs.input.upperbound=2",
"--jdbctogcs.numpartitions=5",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=avro",
"--jdbctogcs.output.mode=append"
])
mock_spark_session.read.format().option().option().option().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_PARTITIONCOLUMN, "column")
mock_spark_session.read.format().option().option().option().option().option.assert_called_with(constants.JDBC_LOWERBOUND, "1")
mock_spark_session.read.format().option().option().option().option().option().option.assert_called_with(constants.JDBC_UPPERBOUND, "2")
mock_spark_session.read.format().option().option().option().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "5")
mock_spark_session.read.format().option().option().option().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_APPEND)
mock_spark_session.dataframe.DataFrame.write.mode().format.assert_called_once_with(constants.FORMAT_AVRO)
mock_spark_session.dataframe.DataFrame.write.mode().format().save.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_pass_args4(self, mock_spark_session):
"""Tests JDBCToGCSTemplate write csv"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.input.partitioncolumn=column",
"--jdbctogcs.input.lowerbound=1",
"--jdbctogcs.input.upperbound=2",
"--jdbctogcs.numpartitions=5",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=csv",
"--jdbctogcs.output.mode=ignore"
])
mock_spark_session.read.format().option().option().option().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template. | (mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_PARTITIONCOLUMN, "column")
mock_spark_session.read.format().option().option().option().option().option.assert_called_with(constants.JDBC_LOWERBOUND, "1")
mock_spark_session.read.format().option().option().option().option().option().option.assert_called_with(constants.JDBC_UPPERBOUND, "2")
mock_spark_session.read.format().option().option().option().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "5")
mock_spark_session.read.format().option().option().option().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_IGNORE)
mock_spark_session.dataframe.DataFrame.write.mode().option.assert_called_once_with(constants.CSV_HEADER, True)
mock_spark_session.dataframe.DataFrame.write.mode().option().csv.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_pass_args5(self, mock_spark_session):
"""Tests JDBCToGCSTemplate write json"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.input.partitioncolumn=column",
"--jdbctogcs.input.lowerbound=1",
"--jdbctogcs.input.upperbound=2",
"--jdbctogcs.numpartitions=5",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=json",
"--jdbctogcs.output.mode=ignore"
])
mock_spark_session.read.format().option().option().option().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_PARTITIONCOLUMN, "column")
mock_spark_session.read.format().option().option().option().option().option.assert_called_with(constants.JDBC_LOWERBOUND, "1")
mock_spark_session.read.format().option().option().option().option().option().option.assert_called_with(constants.JDBC_UPPERBOUND, "2")
mock_spark_session.read.format().option().option().option().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "5")
mock_spark_session.read.format().option().option().option().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_IGNORE)
#mock_spark_session.dataframe.DataFrame.write.mode().json.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_pass_args6(self, mock_spark_session):
"""Tests JDBCToGCSTemplate pass args"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=csv",
"--jdbctogcs.output.mode=append"
])
mock_spark_session.read.format().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "10")
mock_spark_session.read.format().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_APPEND)
mock_spark_session.dataframe.DataFrame.write.mode().option.assert_called_once_with(constants.CSV_HEADER, True)
mock_spark_session.dataframe.DataFrame.write.mode().option().csv.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_pass_args7(self, mock_spark_session):
"""Tests JDBCToGCSTemplate pass args"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=csv",
"--jdbctogcs.output.mode=append",
"--jdbctogcs.output.partitioncolumn=column"
])
mock_spark_session.read.format().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "10")
mock_spark_session.read.format().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_APPEND)
mock_spark_session.dataframe.DataFrame.write.mode().partitionBy.assert_called_once_with("column")
mock_spark_session.dataframe.DataFrame.write.mode().partitionBy().option.assert_called_once_with(constants.CSV_HEADER, True)
mock_spark_session.dataframe.DataFrame.write.mode().partitionBy().option().csv.assert_called_once_with("gs://test") | googlecloudplatform__dataproc-templates |
14 | 14-162-48 | inproject | parse_args | [
"build",
"get_logger",
"parse_args",
"run",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
"""
import mock
import pyspark
from dataproc_templates.jdbc.jdbc_to_gcs import JDBCToGCSTemplate
import dataproc_templates.util.template_constants as constants
class TestJDBCToGCSTemplate:
"""
Test suite for JDBCToGCSTemplate
"""
def test_parse_args1(self):
"""Tests JDBCToGCSTemplate.parse_args()"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.input.partitioncolumn=column",
"--jdbctogcs.input.lowerbound=1",
"--jdbctogcs.input.upperbound=2",
"--jdbctogcs.numpartitions=5",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=csv",
"--jdbctogcs.output.mode=append",
"--jdbctogcs.output.partitioncolumn=column"
])
assert parsed_args["jdbctogcs.input.url"] == "url"
assert parsed_args["jdbctogcs.input.driver"] == "driver"
assert parsed_args["jdbctogcs.input.table"] == "table1"
assert parsed_args["jdbctogcs.input.partitioncolumn"] == "column"
assert parsed_args["jdbctogcs.input.lowerbound"] == "1"
assert parsed_args["jdbctogcs.input.upperbound"] == "2"
assert parsed_args["jdbctogcs.numpartitions"] == "5"
assert parsed_args["jdbctogcs.output.location"] == "gs://test"
assert parsed_args["jdbctogcs.output.format"] == "csv"
assert parsed_args["jdbctogcs.output.mode"] == "append"
assert parsed_args["jdbctogcs.output.partitioncolumn"] == "column"
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_pass_args2(self, mock_spark_session):
"""Tests JDBCToGCSTemplate write parquet"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.input.partitioncolumn=column",
"--jdbctogcs.input.lowerbound=1",
"--jdbctogcs.input.upperbound=2",
"--jdbctogcs.numpartitions=5",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=parquet",
"--jdbctogcs.output.mode=overwrite"
])
mock_spark_session.read.format().option().option().option().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_PARTITIONCOLUMN, "column")
mock_spark_session.read.format().option().option().option().option().option.assert_called_with(constants.JDBC_LOWERBOUND, "1")
mock_spark_session.read.format().option().option().option().option().option().option.assert_called_with(constants.JDBC_UPPERBOUND, "2")
mock_spark_session.read.format().option().option().option().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "5")
mock_spark_session.read.format().option().option().option().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_OVERWRITE)
mock_spark_session.dataframe.DataFrame.write.mode().parquet.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_pass_args3(self, mock_spark_session):
"""Tests JDBCToGCSTemplate write avro"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.input.partitioncolumn=column",
"--jdbctogcs.input.lowerbound=1",
"--jdbctogcs.input.upperbound=2",
"--jdbctogcs.numpartitions=5",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=avro",
"--jdbctogcs.output.mode=append"
])
mock_spark_session.read.format().option().option().option().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_PARTITIONCOLUMN, "column")
mock_spark_session.read.format().option().option().option().option().option.assert_called_with(constants.JDBC_LOWERBOUND, "1")
mock_spark_session.read.format().option().option().option().option().option().option.assert_called_with(constants.JDBC_UPPERBOUND, "2")
mock_spark_session.read.format().option().option().option().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "5")
mock_spark_session.read.format().option().option().option().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_APPEND)
mock_spark_session.dataframe.DataFrame.write.mode().format.assert_called_once_with(constants.FORMAT_AVRO)
mock_spark_session.dataframe.DataFrame.write.mode().format().save.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_pass_args4(self, mock_spark_session):
"""Tests JDBCToGCSTemplate write csv"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.input.partitioncolumn=column",
"--jdbctogcs.input.lowerbound=1",
"--jdbctogcs.input.upperbound=2",
"--jdbctogcs.numpartitions=5",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=csv",
"--jdbctogcs.output.mode=ignore"
])
mock_spark_session.read.format().option().option().option().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_PARTITIONCOLUMN, "column")
mock_spark_session.read.format().option().option().option().option().option.assert_called_with(constants.JDBC_LOWERBOUND, "1")
mock_spark_session.read.format().option().option().option().option().option().option.assert_called_with(constants.JDBC_UPPERBOUND, "2")
mock_spark_session.read.format().option().option().option().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "5")
mock_spark_session.read.format().option().option().option().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_IGNORE)
mock_spark_session.dataframe.DataFrame.write.mode().option.assert_called_once_with(constants.CSV_HEADER, True)
mock_spark_session.dataframe.DataFrame.write.mode().option().csv.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_pass_args5(self, mock_spark_session):
"""Tests JDBCToGCSTemplate write json"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template. | (
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.input.partitioncolumn=column",
"--jdbctogcs.input.lowerbound=1",
"--jdbctogcs.input.upperbound=2",
"--jdbctogcs.numpartitions=5",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=json",
"--jdbctogcs.output.mode=ignore"
])
mock_spark_session.read.format().option().option().option().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_PARTITIONCOLUMN, "column")
mock_spark_session.read.format().option().option().option().option().option.assert_called_with(constants.JDBC_LOWERBOUND, "1")
mock_spark_session.read.format().option().option().option().option().option().option.assert_called_with(constants.JDBC_UPPERBOUND, "2")
mock_spark_session.read.format().option().option().option().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "5")
mock_spark_session.read.format().option().option().option().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_IGNORE)
#mock_spark_session.dataframe.DataFrame.write.mode().json.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_pass_args6(self, mock_spark_session):
"""Tests JDBCToGCSTemplate pass args"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=csv",
"--jdbctogcs.output.mode=append"
])
mock_spark_session.read.format().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "10")
mock_spark_session.read.format().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_APPEND)
mock_spark_session.dataframe.DataFrame.write.mode().option.assert_called_once_with(constants.CSV_HEADER, True)
mock_spark_session.dataframe.DataFrame.write.mode().option().csv.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_pass_args7(self, mock_spark_session):
"""Tests JDBCToGCSTemplate pass args"""
jdbc_to_gcs_template = JDBCToGCSTemplate()
mock_parsed_args = jdbc_to_gcs_template.parse_args(
["--jdbctogcs.input.url=url",
"--jdbctogcs.input.driver=driver",
"--jdbctogcs.input.table=table1",
"--jdbctogcs.output.location=gs://test",
"--jdbctogcs.output.format=csv",
"--jdbctogcs.output.mode=append",
"--jdbctogcs.output.partitioncolumn=column"
])
mock_spark_session.read.format().option().option().option().option().load.return_value = mock_spark_session.dataframe.DataFrame
jdbc_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read.format.assert_called_with(constants.FORMAT_JDBC)
mock_spark_session.read.format().option.assert_called_with(constants.JDBC_URL, "url")
mock_spark_session.read.format().option().option.assert_called_with(constants.JDBC_DRIVER, "driver")
mock_spark_session.read.format().option().option().option.assert_called_with(constants.JDBC_TABLE, "table1")
mock_spark_session.read.format().option().option().option().option.assert_called_with(constants.JDBC_NUMPARTITIONS, "10")
mock_spark_session.read.format().option().option().option().option().load()
mock_spark_session.dataframe.DataFrame.write.mode.assert_called_once_with(constants.OUTPUT_MODE_APPEND)
mock_spark_session.dataframe.DataFrame.write.mode().partitionBy.assert_called_once_with("column")
mock_spark_session.dataframe.DataFrame.write.mode().partitionBy().option.assert_called_once_with(constants.CSV_HEADER, True)
mock_spark_session.dataframe.DataFrame.write.mode().partitionBy().option().csv.assert_called_once_with("gs://test") | googlecloudplatform__dataproc-templates |
15 | 15-32-44 | inproject | parse_args | [
"build",
"get_logger",
"parse_args",
"run",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
"""
import mock
import pyspark
from dataproc_templates.mongo.mongo_to_gcs import MongoToGCSTemplate
import dataproc_templates.util.template_constants as constants
class TestMongoToGCSTemplate:
"""
Test suite for MongoToGCSTemplate
"""
def test_parse_args(self):
"""Tests MongoToGCSTemplate.parse_args()"""
mongo_to_gcs_template = MongoToGCSTemplate()
parsed_args = mongo_to_gcs_template. | (
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=parquet",
"--mongo.gcs.output.mode=overwrite",
"--mongo.gcs.output.location=gs://test"])
assert parsed_args["mongo.gcs.input.uri"] == "mongodb://host:port"
assert parsed_args["mongo.gcs.input.database"] == "database"
assert parsed_args["mongo.gcs.input.collection"] == "collection"
assert parsed_args["mongo.gcs.output.format"] == "parquet"
assert parsed_args["mongo.gcs.output.mode"] == "overwrite"
assert parsed_args["mongo.gcs.output.location"] == "gs://test"
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_parquet(self, mock_spark_session):
"""Tests MongoToGCSTemplate runs for parquet format output"""
mongo_to_gcs_template = MongoToGCSTemplate()
mock_parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=parquet",
"--mongo.gcs.output.mode=overwrite",
"--mongo.gcs.output.location=gs://test"])
mock_spark_session.read.format().option().option().option().load.return_value \
= mock_spark_session.dataframe.DataFrame
mongo_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read \
.format.assert_called_with(constants.FORMAT_MONGO)
mock_spark_session.read \
.format() \
.option() \
.option.assert_called_with(constants.MONGO_DATABASE,"database")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option.assert_called_with(constants.MONGO_COLLECTION,"collection")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option() \
.load.assert_called_with()
mock_spark_session.dataframe.DataFrame.write \
.mode.assert_called_once_with(constants.OUTPUT_MODE_OVERWRITE)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.parquet.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_avro(self, mock_spark_session):
"""Tests MongoToGCSTemplate runs for avro format output"""
mongo_to_gcs_template = MongoToGCSTemplate()
mock_parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=avro",
"--mongo.gcs.output.mode=append",
"--mongo.gcs.output.location=gs://test"])
mock_spark_session.read.format().option().option().option().load.return_value \
= mock_spark_session.dataframe.DataFrame
mongo_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read \
.format.assert_called_with(constants.FORMAT_MONGO)
mock_spark_session.read \
.format() \
.option() \
.option.assert_called_with(constants.MONGO_DATABASE,"database")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option.assert_called_with(constants.MONGO_COLLECTION,"collection")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option() \
.load.assert_called_with()
mock_spark_session.dataframe.DataFrame.write \
.mode.assert_called_once_with(constants.OUTPUT_MODE_APPEND)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.format.assert_called_once_with(constants.FORMAT_AVRO)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.format() \
.save.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_csv(self, mock_spark_session):
"""Tests MongoToGCSTemplate runs for csv format output"""
mongo_to_gcs_template = MongoToGCSTemplate()
mock_parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=csv",
"--mongo.gcs.output.mode=ignore",
"--mongo.gcs.output.location=gs://test"])
mock_spark_session.read.format().option().option().option().load.return_value \
= mock_spark_session.dataframe.DataFrame
mongo_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read \
.format.assert_called_with(constants.FORMAT_MONGO)
mock_spark_session.read \
.format() \
.option() \
.option.assert_called_with(constants.MONGO_DATABASE,"database")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option.assert_called_with(constants.MONGO_COLLECTION,"collection")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option() \
.load.assert_called_with()
mock_spark_session.dataframe.DataFrame.write \
.mode.assert_called_once_with(constants.OUTPUT_MODE_IGNORE)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.option.assert_called_once_with(constants.HEADER, True)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.option() \
.csv.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_json(self, mock_spark_session):
"""Tests MongoToGCSTemplate runs for json format output"""
mongo_to_gcs_template = MongoToGCSTemplate()
mock_parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=json",
"--mongo.gcs.output.mode=errorifexists",
"--mongo.gcs.output.location=gs://test"])
mock_spark_session.read.format().option().option().option().load.return_value \
= mock_spark_session.dataframe.DataFrame
mongo_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read \
.format.assert_called_with(constants.FORMAT_MONGO)
mock_spark_session.read \
.format() \
.option() \
.option.assert_called_with(constants.MONGO_DATABASE,"database")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option.assert_called_with(constants.MONGO_COLLECTION,"collection")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option() \
.load.assert_called_with()
mock_spark_session.dataframe.DataFrame.write \
.mode.assert_called_once_with(constants.OUTPUT_MODE_ERRORIFEXISTS)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.json.assert_called_once_with("gs://test")
| googlecloudplatform__dataproc-templates |
15 | 15-61-30 | common | run | [
"build",
"get_logger",
"parse_args",
"run",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
"""
import mock
import pyspark
from dataproc_templates.mongo.mongo_to_gcs import MongoToGCSTemplate
import dataproc_templates.util.template_constants as constants
class TestMongoToGCSTemplate:
"""
Test suite for MongoToGCSTemplate
"""
def test_parse_args(self):
"""Tests MongoToGCSTemplate.parse_args()"""
mongo_to_gcs_template = MongoToGCSTemplate()
parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=parquet",
"--mongo.gcs.output.mode=overwrite",
"--mongo.gcs.output.location=gs://test"])
assert parsed_args["mongo.gcs.input.uri"] == "mongodb://host:port"
assert parsed_args["mongo.gcs.input.database"] == "database"
assert parsed_args["mongo.gcs.input.collection"] == "collection"
assert parsed_args["mongo.gcs.output.format"] == "parquet"
assert parsed_args["mongo.gcs.output.mode"] == "overwrite"
assert parsed_args["mongo.gcs.output.location"] == "gs://test"
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_parquet(self, mock_spark_session):
"""Tests MongoToGCSTemplate runs for parquet format output"""
mongo_to_gcs_template = MongoToGCSTemplate()
mock_parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=parquet",
"--mongo.gcs.output.mode=overwrite",
"--mongo.gcs.output.location=gs://test"])
mock_spark_session.read.format().option().option().option().load.return_value \
= mock_spark_session.dataframe.DataFrame
mongo_to_gcs_template. | (mock_spark_session, mock_parsed_args)
mock_spark_session.read \
.format.assert_called_with(constants.FORMAT_MONGO)
mock_spark_session.read \
.format() \
.option() \
.option.assert_called_with(constants.MONGO_DATABASE,"database")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option.assert_called_with(constants.MONGO_COLLECTION,"collection")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option() \
.load.assert_called_with()
mock_spark_session.dataframe.DataFrame.write \
.mode.assert_called_once_with(constants.OUTPUT_MODE_OVERWRITE)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.parquet.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_avro(self, mock_spark_session):
"""Tests MongoToGCSTemplate runs for avro format output"""
mongo_to_gcs_template = MongoToGCSTemplate()
mock_parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=avro",
"--mongo.gcs.output.mode=append",
"--mongo.gcs.output.location=gs://test"])
mock_spark_session.read.format().option().option().option().load.return_value \
= mock_spark_session.dataframe.DataFrame
mongo_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read \
.format.assert_called_with(constants.FORMAT_MONGO)
mock_spark_session.read \
.format() \
.option() \
.option.assert_called_with(constants.MONGO_DATABASE,"database")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option.assert_called_with(constants.MONGO_COLLECTION,"collection")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option() \
.load.assert_called_with()
mock_spark_session.dataframe.DataFrame.write \
.mode.assert_called_once_with(constants.OUTPUT_MODE_APPEND)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.format.assert_called_once_with(constants.FORMAT_AVRO)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.format() \
.save.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_csv(self, mock_spark_session):
"""Tests MongoToGCSTemplate runs for csv format output"""
mongo_to_gcs_template = MongoToGCSTemplate()
mock_parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=csv",
"--mongo.gcs.output.mode=ignore",
"--mongo.gcs.output.location=gs://test"])
mock_spark_session.read.format().option().option().option().load.return_value \
= mock_spark_session.dataframe.DataFrame
mongo_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read \
.format.assert_called_with(constants.FORMAT_MONGO)
mock_spark_session.read \
.format() \
.option() \
.option.assert_called_with(constants.MONGO_DATABASE,"database")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option.assert_called_with(constants.MONGO_COLLECTION,"collection")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option() \
.load.assert_called_with()
mock_spark_session.dataframe.DataFrame.write \
.mode.assert_called_once_with(constants.OUTPUT_MODE_IGNORE)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.option.assert_called_once_with(constants.HEADER, True)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.option() \
.csv.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_json(self, mock_spark_session):
"""Tests MongoToGCSTemplate runs for json format output"""
mongo_to_gcs_template = MongoToGCSTemplate()
mock_parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=json",
"--mongo.gcs.output.mode=errorifexists",
"--mongo.gcs.output.location=gs://test"])
mock_spark_session.read.format().option().option().option().load.return_value \
= mock_spark_session.dataframe.DataFrame
mongo_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read \
.format.assert_called_with(constants.FORMAT_MONGO)
mock_spark_session.read \
.format() \
.option() \
.option.assert_called_with(constants.MONGO_DATABASE,"database")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option.assert_called_with(constants.MONGO_COLLECTION,"collection")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option() \
.load.assert_called_with()
mock_spark_session.dataframe.DataFrame.write \
.mode.assert_called_once_with(constants.OUTPUT_MODE_ERRORIFEXISTS)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.json.assert_called_once_with("gs://test")
| googlecloudplatform__dataproc-templates |
15 | 15-68-49 | random | MONGO_DATABASE | [
"BQ_GCS_INPUT_TABLE",
"BQ_GCS_OUTPUT_FORMAT",
"BQ_GCS_OUTPUT_LOCATION",
"BQ_GCS_OUTPUT_MODE",
"COMPRESSION_BZIP2",
"COMPRESSION_DEFLATE",
"COMPRESSION_GZIP",
"COMPRESSION_LZ4",
"COMPRESSION_NONE",
"FORMAT_AVRO",
"FORMAT_AVRO_EXTD",
"FORMAT_BIGQUERY",
"FORMAT_CSV",
"FORMAT_HBASE",
"FORMAT_JDBC",
"FORMAT_JSON",
"FORMAT_MONGO",
"FORMAT_PRQT",
"FORMAT_TXT",
"GCS_BQ_INPUT_FORMAT",
"GCS_BQ_INPUT_LOCATION",
"GCS_BQ_LD_TEMP_BUCKET_NAME",
"GCS_BQ_OUTPUT_DATASET",
"GCS_BQ_OUTPUT_MODE",
"GCS_BQ_OUTPUT_TABLE",
"GCS_BQ_TEMP_BUCKET",
"GCS_BT_HBASE_CATALOG_JSON",
"GCS_BT_INPUT_FORMAT",
"GCS_BT_INPUT_LOCATION",
"GCS_JDBC_BATCH_SIZE",
"GCS_JDBC_INPUT_FORMAT",
"GCS_JDBC_INPUT_LOCATION",
"GCS_JDBC_OUTPUT_DRIVER",
"GCS_JDBC_OUTPUT_MODE",
"GCS_JDBC_OUTPUT_TABLE",
"GCS_JDBC_OUTPUT_URL",
"GCS_MONGO_BATCH_SIZE",
"GCS_MONGO_INPUT_FORMAT",
"GCS_MONGO_INPUT_LOCATION",
"GCS_MONGO_OUTPUT_COLLECTION",
"GCS_MONGO_OUTPUT_DATABASE",
"GCS_MONGO_OUTPUT_MODE",
"GCS_MONGO_OUTPUT_URI",
"HBASE_GCS_CATALOG_JSON",
"HBASE_GCS_OUTPUT_FORMAT",
"HBASE_GCS_OUTPUT_LOCATION",
"HBASE_GCS_OUTPUT_MODE",
"HEADER",
"HIVE_BQ_INPUT_DATABASE",
"HIVE_BQ_INPUT_TABLE",
"HIVE_BQ_LD_TEMP_BUCKET_NAME",
"HIVE_BQ_OUTPUT_DATASET",
"HIVE_BQ_OUTPUT_MODE",
"HIVE_BQ_OUTPUT_TABLE",
"HIVE_GCS_INPUT_DATABASE",
"HIVE_GCS_INPUT_TABLE",
"HIVE_GCS_OUTPUT_FORMAT",
"HIVE_GCS_OUTPUT_LOCATION",
"HIVE_GCS_OUTPUT_MODE",
"INFER_SCHEMA",
"INPUT_COMPRESSION",
"INPUT_DELIMITER",
"JDBC_BATCH_SIZE",
"JDBC_CREATE_TABLE_OPTIONS",
"JDBC_DRIVER",
"JDBC_LOWERBOUND",
"JDBC_NUMPARTITIONS",
"JDBC_PARTITIONCOLUMN",
"JDBC_TABLE",
"JDBC_UPPERBOUND",
"JDBC_URL",
"JDBCTOGCS_INPUT_DRIVER",
"JDBCTOGCS_INPUT_LOWERBOUND",
"JDBCTOGCS_INPUT_PARTITIONCOLUMN",
"JDBCTOGCS_INPUT_TABLE",
"JDBCTOGCS_INPUT_UPPERBOUND",
"JDBCTOGCS_INPUT_URL",
"JDBCTOGCS_NUMPARTITIONS",
"JDBCTOGCS_OUTPUT_FORMAT",
"JDBCTOGCS_OUTPUT_LOCATION",
"JDBCTOGCS_OUTPUT_MODE",
"JDBCTOGCS_OUTPUT_PARTITIONCOLUMN",
"JDBCTOJDBC_INPUT_DRIVER",
"JDBCTOJDBC_INPUT_LOWERBOUND",
"JDBCTOJDBC_INPUT_PARTITIONCOLUMN",
"JDBCTOJDBC_INPUT_TABLE",
"JDBCTOJDBC_INPUT_UPPERBOUND",
"JDBCTOJDBC_INPUT_URL",
"JDBCTOJDBC_NUMPARTITIONS",
"JDBCTOJDBC_OUTPUT_BATCH_SIZE",
"JDBCTOJDBC_OUTPUT_CREATE_TABLE_OPTION",
"JDBCTOJDBC_OUTPUT_DRIVER",
"JDBCTOJDBC_OUTPUT_MODE",
"JDBCTOJDBC_OUTPUT_TABLE",
"JDBCTOJDBC_OUTPUT_URL",
"MONGO_BATCH_SIZE",
"MONGO_COLLECTION",
"MONGO_DATABASE",
"MONGO_DEFAULT_BATCH_SIZE",
"MONGO_GCS_INPUT_COLLECTION",
"MONGO_GCS_INPUT_DATABASE",
"MONGO_GCS_INPUT_URI",
"MONGO_GCS_OUTPUT_FORMAT",
"MONGO_GCS_OUTPUT_LOCATION",
"MONGO_GCS_OUTPUT_MODE",
"MONGO_INPUT_URI",
"MONGO_URL",
"OUTPUT_MODE_APPEND",
"OUTPUT_MODE_ERRORIFEXISTS",
"OUTPUT_MODE_IGNORE",
"OUTPUT_MODE_OVERWRITE",
"PROJECT_ID_PROP",
"TABLE",
"TEMP_GCS_BUCKET",
"TEXT_BQ_INPUT_INFERSCHEMA",
"TEXT_BQ_INPUT_LOCATION",
"TEXT_BQ_LD_TEMP_BUCKET_NAME",
"TEXT_BQ_OUTPUT_DATASET",
"TEXT_BQ_OUTPUT_MODE",
"TEXT_BQ_OUTPUT_TABLE",
"TEXT_BQ_TEMP_BUCKET",
"TEXT_INPUT_COMPRESSION",
"TEXT_INPUT_DELIMITER",
"__doc__",
"__file__",
"__name__",
"__package__"
] | """
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
"""
import mock
import pyspark
from dataproc_templates.mongo.mongo_to_gcs import MongoToGCSTemplate
import dataproc_templates.util.template_constants as constants
class TestMongoToGCSTemplate:
"""
Test suite for MongoToGCSTemplate
"""
def test_parse_args(self):
"""Tests MongoToGCSTemplate.parse_args()"""
mongo_to_gcs_template = MongoToGCSTemplate()
parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=parquet",
"--mongo.gcs.output.mode=overwrite",
"--mongo.gcs.output.location=gs://test"])
assert parsed_args["mongo.gcs.input.uri"] == "mongodb://host:port"
assert parsed_args["mongo.gcs.input.database"] == "database"
assert parsed_args["mongo.gcs.input.collection"] == "collection"
assert parsed_args["mongo.gcs.output.format"] == "parquet"
assert parsed_args["mongo.gcs.output.mode"] == "overwrite"
assert parsed_args["mongo.gcs.output.location"] == "gs://test"
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_parquet(self, mock_spark_session):
"""Tests MongoToGCSTemplate runs for parquet format output"""
mongo_to_gcs_template = MongoToGCSTemplate()
mock_parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=parquet",
"--mongo.gcs.output.mode=overwrite",
"--mongo.gcs.output.location=gs://test"])
mock_spark_session.read.format().option().option().option().load.return_value \
= mock_spark_session.dataframe.DataFrame
mongo_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read \
.format.assert_called_with(constants.FORMAT_MONGO)
mock_spark_session.read \
.format() \
.option() \
.option.assert_called_with(constants. | ,"database")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option.assert_called_with(constants.MONGO_COLLECTION,"collection")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option() \
.load.assert_called_with()
mock_spark_session.dataframe.DataFrame.write \
.mode.assert_called_once_with(constants.OUTPUT_MODE_OVERWRITE)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.parquet.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_avro(self, mock_spark_session):
"""Tests MongoToGCSTemplate runs for avro format output"""
mongo_to_gcs_template = MongoToGCSTemplate()
mock_parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=avro",
"--mongo.gcs.output.mode=append",
"--mongo.gcs.output.location=gs://test"])
mock_spark_session.read.format().option().option().option().load.return_value \
= mock_spark_session.dataframe.DataFrame
mongo_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read \
.format.assert_called_with(constants.FORMAT_MONGO)
mock_spark_session.read \
.format() \
.option() \
.option.assert_called_with(constants.MONGO_DATABASE,"database")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option.assert_called_with(constants.MONGO_COLLECTION,"collection")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option() \
.load.assert_called_with()
mock_spark_session.dataframe.DataFrame.write \
.mode.assert_called_once_with(constants.OUTPUT_MODE_APPEND)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.format.assert_called_once_with(constants.FORMAT_AVRO)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.format() \
.save.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_csv(self, mock_spark_session):
"""Tests MongoToGCSTemplate runs for csv format output"""
mongo_to_gcs_template = MongoToGCSTemplate()
mock_parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=csv",
"--mongo.gcs.output.mode=ignore",
"--mongo.gcs.output.location=gs://test"])
mock_spark_session.read.format().option().option().option().load.return_value \
= mock_spark_session.dataframe.DataFrame
mongo_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read \
.format.assert_called_with(constants.FORMAT_MONGO)
mock_spark_session.read \
.format() \
.option() \
.option.assert_called_with(constants.MONGO_DATABASE,"database")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option.assert_called_with(constants.MONGO_COLLECTION,"collection")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option() \
.load.assert_called_with()
mock_spark_session.dataframe.DataFrame.write \
.mode.assert_called_once_with(constants.OUTPUT_MODE_IGNORE)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.option.assert_called_once_with(constants.HEADER, True)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.option() \
.csv.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_json(self, mock_spark_session):
"""Tests MongoToGCSTemplate runs for json format output"""
mongo_to_gcs_template = MongoToGCSTemplate()
mock_parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=json",
"--mongo.gcs.output.mode=errorifexists",
"--mongo.gcs.output.location=gs://test"])
mock_spark_session.read.format().option().option().option().load.return_value \
= mock_spark_session.dataframe.DataFrame
mongo_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read \
.format.assert_called_with(constants.FORMAT_MONGO)
mock_spark_session.read \
.format() \
.option() \
.option.assert_called_with(constants.MONGO_DATABASE,"database")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option.assert_called_with(constants.MONGO_COLLECTION,"collection")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option() \
.load.assert_called_with()
mock_spark_session.dataframe.DataFrame.write \
.mode.assert_called_once_with(constants.OUTPUT_MODE_ERRORIFEXISTS)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.json.assert_called_once_with("gs://test")
| googlecloudplatform__dataproc-templates |
15 | 15-134-49 | inproject | parse_args | [
"build",
"get_logger",
"parse_args",
"run",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | """
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
"""
import mock
import pyspark
from dataproc_templates.mongo.mongo_to_gcs import MongoToGCSTemplate
import dataproc_templates.util.template_constants as constants
class TestMongoToGCSTemplate:
"""
Test suite for MongoToGCSTemplate
"""
def test_parse_args(self):
"""Tests MongoToGCSTemplate.parse_args()"""
mongo_to_gcs_template = MongoToGCSTemplate()
parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=parquet",
"--mongo.gcs.output.mode=overwrite",
"--mongo.gcs.output.location=gs://test"])
assert parsed_args["mongo.gcs.input.uri"] == "mongodb://host:port"
assert parsed_args["mongo.gcs.input.database"] == "database"
assert parsed_args["mongo.gcs.input.collection"] == "collection"
assert parsed_args["mongo.gcs.output.format"] == "parquet"
assert parsed_args["mongo.gcs.output.mode"] == "overwrite"
assert parsed_args["mongo.gcs.output.location"] == "gs://test"
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_parquet(self, mock_spark_session):
"""Tests MongoToGCSTemplate runs for parquet format output"""
mongo_to_gcs_template = MongoToGCSTemplate()
mock_parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=parquet",
"--mongo.gcs.output.mode=overwrite",
"--mongo.gcs.output.location=gs://test"])
mock_spark_session.read.format().option().option().option().load.return_value \
= mock_spark_session.dataframe.DataFrame
mongo_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read \
.format.assert_called_with(constants.FORMAT_MONGO)
mock_spark_session.read \
.format() \
.option() \
.option.assert_called_with(constants.MONGO_DATABASE,"database")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option.assert_called_with(constants.MONGO_COLLECTION,"collection")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option() \
.load.assert_called_with()
mock_spark_session.dataframe.DataFrame.write \
.mode.assert_called_once_with(constants.OUTPUT_MODE_OVERWRITE)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.parquet.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_avro(self, mock_spark_session):
"""Tests MongoToGCSTemplate runs for avro format output"""
mongo_to_gcs_template = MongoToGCSTemplate()
mock_parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=avro",
"--mongo.gcs.output.mode=append",
"--mongo.gcs.output.location=gs://test"])
mock_spark_session.read.format().option().option().option().load.return_value \
= mock_spark_session.dataframe.DataFrame
mongo_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read \
.format.assert_called_with(constants.FORMAT_MONGO)
mock_spark_session.read \
.format() \
.option() \
.option.assert_called_with(constants.MONGO_DATABASE,"database")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option.assert_called_with(constants.MONGO_COLLECTION,"collection")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option() \
.load.assert_called_with()
mock_spark_session.dataframe.DataFrame.write \
.mode.assert_called_once_with(constants.OUTPUT_MODE_APPEND)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.format.assert_called_once_with(constants.FORMAT_AVRO)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.format() \
.save.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_csv(self, mock_spark_session):
"""Tests MongoToGCSTemplate runs for csv format output"""
mongo_to_gcs_template = MongoToGCSTemplate()
mock_parsed_args = mongo_to_gcs_template. | (
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=csv",
"--mongo.gcs.output.mode=ignore",
"--mongo.gcs.output.location=gs://test"])
mock_spark_session.read.format().option().option().option().load.return_value \
= mock_spark_session.dataframe.DataFrame
mongo_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read \
.format.assert_called_with(constants.FORMAT_MONGO)
mock_spark_session.read \
.format() \
.option() \
.option.assert_called_with(constants.MONGO_DATABASE,"database")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option.assert_called_with(constants.MONGO_COLLECTION,"collection")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option() \
.load.assert_called_with()
mock_spark_session.dataframe.DataFrame.write \
.mode.assert_called_once_with(constants.OUTPUT_MODE_IGNORE)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.option.assert_called_once_with(constants.HEADER, True)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.option() \
.csv.assert_called_once_with("gs://test")
@mock.patch.object(pyspark.sql, 'SparkSession')
def test_run_json(self, mock_spark_session):
"""Tests MongoToGCSTemplate runs for json format output"""
mongo_to_gcs_template = MongoToGCSTemplate()
mock_parsed_args = mongo_to_gcs_template.parse_args(
["--mongo.gcs.input.uri=mongodb://host:port",
"--mongo.gcs.input.database=database",
"--mongo.gcs.input.collection=collection",
"--mongo.gcs.output.format=json",
"--mongo.gcs.output.mode=errorifexists",
"--mongo.gcs.output.location=gs://test"])
mock_spark_session.read.format().option().option().option().load.return_value \
= mock_spark_session.dataframe.DataFrame
mongo_to_gcs_template.run(mock_spark_session, mock_parsed_args)
mock_spark_session.read \
.format.assert_called_with(constants.FORMAT_MONGO)
mock_spark_session.read \
.format() \
.option() \
.option.assert_called_with(constants.MONGO_DATABASE,"database")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option.assert_called_with(constants.MONGO_COLLECTION,"collection")
mock_spark_session.read \
.format() \
.option() \
.option() \
.option() \
.load.assert_called_with()
mock_spark_session.dataframe.DataFrame.write \
.mode.assert_called_once_with(constants.OUTPUT_MODE_ERRORIFEXISTS)
mock_spark_session.dataframe.DataFrame.write \
.mode() \
.json.assert_called_once_with("gs://test")
| googlecloudplatform__dataproc-templates |
27 | 27-35-13 | infile | typing_console_handler | [
"chat_plugins",
"console_handler",
"debug",
"double_check",
"error",
"file_handler",
"get_log_directory",
"info",
"json_logger",
"log_json",
"logger",
"set_level",
"speak_mode",
"typewriter_log",
"typing_console_handler",
"typing_logger",
"warn",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self. | = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-40-13 | infile | console_handler | [
"chat_plugins",
"console_handler",
"debug",
"double_check",
"error",
"file_handler",
"get_log_directory",
"info",
"json_logger",
"log_json",
"logger",
"set_level",
"speak_mode",
"typewriter_log",
"typing_console_handler",
"typing_logger",
"warn",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self. | = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-100-13 | random | typing_logger | [
"chat_plugins",
"console_handler",
"debug",
"double_check",
"error",
"file_handler",
"get_log_directory",
"info",
"json_logger",
"log_json",
"logger",
"set_level",
"speak_mode",
"typewriter_log",
"typing_console_handler",
"typing_logger",
"warn",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self. | .log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-100-27 | random | log | [
"addFilter",
"addHandler",
"callHandlers",
"critical",
"debug",
"disabled",
"error",
"exception",
"fatal",
"filter",
"filters",
"findCaller",
"getChild",
"getEffectiveLevel",
"handle",
"handlers",
"hasHandlers",
"info",
"isEnabledFor",
"level",
"log",
"makeRecord",
"name",
"parent",
"propagate",
"removeFilter",
"removeHandler",
"setLevel",
"warn",
"warning",
"_cache",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger. | (
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-110-13 | infile | _log | [
"chat_plugins",
"console_handler",
"debug",
"double_check",
"error",
"file_handler",
"get_log_directory",
"info",
"json_logger",
"log_json",
"logger",
"set_level",
"speak_mode",
"typewriter_log",
"typing_console_handler",
"typing_logger",
"warn",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self. | (title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-110-55 | infile | DEBUG | [
"addLevelName",
"atexit",
"BASIC_FORMAT",
"basicConfig",
"BufferingFormatter",
"captureWarnings",
"collections",
"config",
"critical",
"CRITICAL",
"currentframe",
"debug",
"DEBUG",
"disable",
"error",
"ERROR",
"exception",
"fatal",
"FATAL",
"FileHandler",
"Filter",
"Filterer",
"Formatter",
"getLevelName",
"getLogger",
"getLoggerClass",
"getLogRecordFactory",
"Handler",
"handlers",
"info",
"INFO",
"io",
"lastResort",
"log",
"Logger",
"LoggerAdapter",
"logMultiprocessing",
"logProcesses",
"LogRecord",
"logThreads",
"makeLogRecord",
"Manager",
"NOTSET",
"NullHandler",
"os",
"PercentStyle",
"PlaceHolder",
"raiseExceptions",
"re",
"root",
"RootLogger",
"setLoggerClass",
"setLogRecordFactory",
"shutdown",
"StreamHandler",
"StrFormatStyle",
"StringTemplateStyle",
"sys",
"Template",
"threading",
"time",
"traceback",
"warn",
"WARN",
"warning",
"WARNING",
"warnings",
"weakref",
"_acquireLock",
"_addHandlerRef",
"_after_at_fork_child_reinit_locks",
"_at_fork_reinit_lock_weakset",
"_checkLevel",
"_defaultFormatter",
"_defaultLastResort",
"_handlerList",
"_handlers",
"_levelToName",
"_lock",
"_loggerClass",
"_logRecordFactory",
"_nameToLevel",
"_register_at_fork_reinit_lock",
"_releaseLock",
"_removeHandlerRef",
"_showwarning",
"_srcfile",
"_startTime",
"_StderrHandler",
"_str_formatter",
"_STYLES",
"_warnings_showwarning",
"__all__",
"__author__",
"__date__",
"__doc__",
"__file__",
"__name__",
"__package__",
"__status__",
"__version__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging. | )
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-118-13 | infile | _log | [
"chat_plugins",
"console_handler",
"debug",
"double_check",
"error",
"file_handler",
"get_log_directory",
"info",
"json_logger",
"log_json",
"logger",
"set_level",
"speak_mode",
"typewriter_log",
"typing_console_handler",
"typing_logger",
"warn",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self. | (title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-118-55 | infile | INFO | [
"addLevelName",
"atexit",
"BASIC_FORMAT",
"basicConfig",
"BufferingFormatter",
"captureWarnings",
"collections",
"config",
"critical",
"CRITICAL",
"currentframe",
"debug",
"DEBUG",
"disable",
"error",
"ERROR",
"exception",
"fatal",
"FATAL",
"FileHandler",
"Filter",
"Filterer",
"Formatter",
"getLevelName",
"getLogger",
"getLoggerClass",
"getLogRecordFactory",
"Handler",
"handlers",
"info",
"INFO",
"io",
"lastResort",
"log",
"Logger",
"LoggerAdapter",
"logMultiprocessing",
"logProcesses",
"LogRecord",
"logThreads",
"makeLogRecord",
"Manager",
"NOTSET",
"NullHandler",
"os",
"PercentStyle",
"PlaceHolder",
"raiseExceptions",
"re",
"root",
"RootLogger",
"setLoggerClass",
"setLogRecordFactory",
"shutdown",
"StreamHandler",
"StrFormatStyle",
"StringTemplateStyle",
"sys",
"Template",
"threading",
"time",
"traceback",
"warn",
"WARN",
"warning",
"WARNING",
"warnings",
"weakref",
"_acquireLock",
"_addHandlerRef",
"_after_at_fork_child_reinit_locks",
"_at_fork_reinit_lock_weakset",
"_checkLevel",
"_defaultFormatter",
"_defaultLastResort",
"_handlerList",
"_handlers",
"_levelToName",
"_lock",
"_loggerClass",
"_logRecordFactory",
"_nameToLevel",
"_register_at_fork_reinit_lock",
"_releaseLock",
"_removeHandlerRef",
"_showwarning",
"_srcfile",
"_startTime",
"_StderrHandler",
"_str_formatter",
"_STYLES",
"_warnings_showwarning",
"__all__",
"__author__",
"__date__",
"__doc__",
"__file__",
"__name__",
"__package__",
"__status__",
"__version__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging. | )
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-126-13 | infile | _log | [
"chat_plugins",
"console_handler",
"debug",
"double_check",
"error",
"file_handler",
"get_log_directory",
"info",
"json_logger",
"log_json",
"logger",
"set_level",
"speak_mode",
"typewriter_log",
"typing_console_handler",
"typing_logger",
"warn",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self. | (title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-126-55 | infile | WARN | [
"addLevelName",
"atexit",
"BASIC_FORMAT",
"basicConfig",
"BufferingFormatter",
"captureWarnings",
"collections",
"config",
"critical",
"CRITICAL",
"currentframe",
"debug",
"DEBUG",
"disable",
"error",
"ERROR",
"exception",
"fatal",
"FATAL",
"FileHandler",
"Filter",
"Filterer",
"Formatter",
"getLevelName",
"getLogger",
"getLoggerClass",
"getLogRecordFactory",
"Handler",
"handlers",
"info",
"INFO",
"io",
"lastResort",
"log",
"Logger",
"LoggerAdapter",
"logMultiprocessing",
"logProcesses",
"LogRecord",
"logThreads",
"makeLogRecord",
"Manager",
"NOTSET",
"NullHandler",
"os",
"PercentStyle",
"PlaceHolder",
"raiseExceptions",
"re",
"root",
"RootLogger",
"setLoggerClass",
"setLogRecordFactory",
"shutdown",
"StreamHandler",
"StrFormatStyle",
"StringTemplateStyle",
"sys",
"Template",
"threading",
"time",
"traceback",
"warn",
"WARN",
"warning",
"WARNING",
"warnings",
"weakref",
"_acquireLock",
"_addHandlerRef",
"_after_at_fork_child_reinit_locks",
"_at_fork_reinit_lock_weakset",
"_checkLevel",
"_defaultFormatter",
"_defaultLastResort",
"_handlerList",
"_handlers",
"_levelToName",
"_lock",
"_loggerClass",
"_logRecordFactory",
"_nameToLevel",
"_register_at_fork_reinit_lock",
"_releaseLock",
"_removeHandlerRef",
"_showwarning",
"_srcfile",
"_startTime",
"_StderrHandler",
"_str_formatter",
"_STYLES",
"_warnings_showwarning",
"__all__",
"__author__",
"__date__",
"__doc__",
"__file__",
"__name__",
"__package__",
"__status__",
"__version__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging. | )
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-129-13 | infile | _log | [
"chat_plugins",
"console_handler",
"debug",
"double_check",
"error",
"file_handler",
"get_log_directory",
"info",
"json_logger",
"log_json",
"logger",
"set_level",
"speak_mode",
"typewriter_log",
"typing_console_handler",
"typing_logger",
"warn",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self. | (title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-129-30 | infile | RED | [
"BLACK",
"BLUE",
"CYAN",
"GREEN",
"LIGHTBLACK_EX",
"LIGHTBLUE_EX",
"LIGHTCYAN_EX",
"LIGHTGREEN_EX",
"LIGHTMAGENTA_EX",
"LIGHTRED_EX",
"LIGHTWHITE_EX",
"LIGHTYELLOW_EX",
"MAGENTA",
"RED",
"RESET",
"WHITE",
"YELLOW",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore. | , message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-129-52 | infile | ERROR | [
"addLevelName",
"atexit",
"BASIC_FORMAT",
"basicConfig",
"BufferingFormatter",
"captureWarnings",
"collections",
"config",
"critical",
"CRITICAL",
"currentframe",
"debug",
"DEBUG",
"disable",
"error",
"ERROR",
"exception",
"fatal",
"FATAL",
"FileHandler",
"Filter",
"Filterer",
"Formatter",
"getLevelName",
"getLogger",
"getLoggerClass",
"getLogRecordFactory",
"Handler",
"handlers",
"info",
"INFO",
"io",
"lastResort",
"log",
"Logger",
"LoggerAdapter",
"logMultiprocessing",
"logProcesses",
"LogRecord",
"logThreads",
"makeLogRecord",
"Manager",
"NOTSET",
"NullHandler",
"os",
"PercentStyle",
"PlaceHolder",
"raiseExceptions",
"re",
"root",
"RootLogger",
"setLoggerClass",
"setLogRecordFactory",
"shutdown",
"StreamHandler",
"StrFormatStyle",
"StringTemplateStyle",
"sys",
"Template",
"threading",
"time",
"traceback",
"warn",
"WARN",
"warning",
"WARNING",
"warnings",
"weakref",
"_acquireLock",
"_addHandlerRef",
"_after_at_fork_child_reinit_locks",
"_at_fork_reinit_lock_weakset",
"_checkLevel",
"_defaultFormatter",
"_defaultLastResort",
"_handlerList",
"_handlers",
"_levelToName",
"_lock",
"_loggerClass",
"_logRecordFactory",
"_nameToLevel",
"_register_at_fork_reinit_lock",
"_releaseLock",
"_removeHandlerRef",
"_showwarning",
"_srcfile",
"_startTime",
"_StderrHandler",
"_str_formatter",
"_STYLES",
"_warnings_showwarning",
"__all__",
"__author__",
"__date__",
"__doc__",
"__file__",
"__name__",
"__package__",
"__status__",
"__version__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging. | )
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-158-13 | infile | typewriter_log | [
"chat_plugins",
"console_handler",
"debug",
"double_check",
"error",
"file_handler",
"get_log_directory",
"info",
"json_logger",
"log_json",
"logger",
"set_level",
"speak_mode",
"typewriter_log",
"typing_console_handler",
"typing_logger",
"warn",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self. | ("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-158-63 | infile | YELLOW | [
"BLACK",
"BLUE",
"CYAN",
"GREEN",
"LIGHTBLACK_EX",
"LIGHTBLUE_EX",
"LIGHTCYAN_EX",
"LIGHTGREEN_EX",
"LIGHTMAGENTA_EX",
"LIGHTRED_EX",
"LIGHTWHITE_EX",
"LIGHTYELLOW_EX",
"MAGENTA",
"RED",
"RESET",
"WHITE",
"YELLOW",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore. | , additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-168-26 | random | setFormatter | [
"acquire",
"addFilter",
"baseFilename",
"close",
"createLock",
"delay",
"emit",
"encoding",
"filter",
"filters",
"flush",
"format",
"formatter",
"handle",
"handleError",
"level",
"lock",
"mode",
"name",
"release",
"removeFilter",
"setFormatter",
"setLevel",
"setStream",
"stream",
"terminator",
"_open",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler. | (JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-172-13 | infile | json_logger | [
"chat_plugins",
"console_handler",
"debug",
"double_check",
"error",
"file_handler",
"get_log_directory",
"info",
"json_logger",
"log_json",
"logger",
"set_level",
"speak_mode",
"typewriter_log",
"typing_console_handler",
"typing_logger",
"warn",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self. | .debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-172-25 | infile | debug | [
"addFilter",
"addHandler",
"callHandlers",
"critical",
"debug",
"disabled",
"error",
"exception",
"fatal",
"filter",
"filters",
"findCaller",
"getChild",
"getEffectiveLevel",
"handle",
"handlers",
"hasHandlers",
"info",
"isEnabledFor",
"level",
"log",
"makeRecord",
"name",
"parent",
"propagate",
"removeFilter",
"removeHandler",
"setLevel",
"warn",
"warning",
"_cache",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger. | (data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-173-13 | random | json_logger | [
"chat_plugins",
"console_handler",
"debug",
"double_check",
"error",
"file_handler",
"get_log_directory",
"info",
"json_logger",
"log_json",
"logger",
"set_level",
"speak_mode",
"typewriter_log",
"typing_console_handler",
"typing_logger",
"warn",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self. | .removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-173-25 | random | removeHandler | [
"addFilter",
"addHandler",
"callHandlers",
"critical",
"debug",
"disabled",
"error",
"exception",
"fatal",
"filter",
"filters",
"findCaller",
"getChild",
"getEffectiveLevel",
"handle",
"handlers",
"hasHandlers",
"info",
"isEnabledFor",
"level",
"log",
"makeRecord",
"name",
"parent",
"propagate",
"removeFilter",
"removeHandler",
"setLevel",
"warn",
"warning",
"_cache",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger. | (json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-184-35 | non_informative | StreamHandler | [
"addLevelName",
"atexit",
"BASIC_FORMAT",
"basicConfig",
"BufferingFormatter",
"captureWarnings",
"collections",
"config",
"critical",
"CRITICAL",
"currentframe",
"debug",
"DEBUG",
"disable",
"error",
"ERROR",
"exception",
"fatal",
"FATAL",
"FileHandler",
"Filter",
"Filterer",
"Formatter",
"getLevelName",
"getLogger",
"getLoggerClass",
"getLogRecordFactory",
"Handler",
"handlers",
"info",
"INFO",
"io",
"lastResort",
"log",
"Logger",
"LoggerAdapter",
"logMultiprocessing",
"logProcesses",
"LogRecord",
"logThreads",
"makeLogRecord",
"Manager",
"NOTSET",
"NullHandler",
"os",
"PercentStyle",
"PlaceHolder",
"raiseExceptions",
"re",
"root",
"RootLogger",
"setLoggerClass",
"setLogRecordFactory",
"shutdown",
"StreamHandler",
"StrFormatStyle",
"StringTemplateStyle",
"sys",
"Template",
"threading",
"time",
"traceback",
"warn",
"WARN",
"warning",
"WARNING",
"warnings",
"weakref",
"_acquireLock",
"_addHandlerRef",
"_after_at_fork_child_reinit_locks",
"_at_fork_reinit_lock_weakset",
"_checkLevel",
"_defaultFormatter",
"_defaultLastResort",
"_handlerList",
"_handlers",
"_levelToName",
"_lock",
"_loggerClass",
"_logRecordFactory",
"_nameToLevel",
"_register_at_fork_reinit_lock",
"_releaseLock",
"_removeHandlerRef",
"_showwarning",
"_srcfile",
"_startTime",
"_StderrHandler",
"_str_formatter",
"_STYLES",
"_warnings_showwarning",
"__all__",
"__author__",
"__date__",
"__doc__",
"__file__",
"__name__",
"__package__",
"__status__",
"__version__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging. | ):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-207-19 | infile | format | [
"acquire",
"addFilter",
"close",
"createLock",
"emit",
"filter",
"filters",
"flush",
"format",
"formatter",
"handle",
"handleError",
"level",
"lock",
"name",
"release",
"removeFilter",
"setFormatter",
"setLevel",
"setStream",
"stream",
"terminator",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self. | (record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-238-23 | infile | format | [
"converter",
"datefmt",
"default_msec_format",
"default_time_format",
"format",
"formatException",
"formatMessage",
"formatStack",
"formatTime",
"usesTime",
"_fmt",
"_style",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super(). | (record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-243-23 | random | sub | [
"findall",
"finditer",
"flags",
"fullmatch",
"groupindex",
"groups",
"match",
"pattern",
"search",
"split",
"sub",
"subn",
"__annotations__",
"__class__",
"__class_getitem__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape. | ("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-266-11 | infile | typewriter_log | [
"chat_plugins",
"console_handler",
"debug",
"double_check",
"error",
"file_handler",
"get_log_directory",
"info",
"json_logger",
"log_json",
"logger",
"set_level",
"speak_mode",
"typewriter_log",
"typing_console_handler",
"typing_logger",
"warn",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger. | (
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-269-11 | infile | typewriter_log | [
"chat_plugins",
"console_handler",
"debug",
"double_check",
"error",
"file_handler",
"get_log_directory",
"info",
"json_logger",
"log_json",
"logger",
"set_level",
"speak_mode",
"typewriter_log",
"typing_console_handler",
"typing_logger",
"warn",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger. | ("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-269-45 | infile | YELLOW | [
"BLACK",
"BLUE",
"CYAN",
"GREEN",
"LIGHTBLACK_EX",
"LIGHTBLUE_EX",
"LIGHTCYAN_EX",
"LIGHTGREEN_EX",
"LIGHTMAGENTA_EX",
"LIGHTRED_EX",
"LIGHTWHITE_EX",
"LIGHTYELLOW_EX",
"MAGENTA",
"RED",
"RESET",
"WHITE",
"YELLOW",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore. | , f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-271-15 | infile | typewriter_log | [
"chat_plugins",
"console_handler",
"debug",
"double_check",
"error",
"file_handler",
"get_log_directory",
"info",
"json_logger",
"log_json",
"logger",
"set_level",
"speak_mode",
"typewriter_log",
"typing_console_handler",
"typing_logger",
"warn",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger. | ("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-271-44 | infile | YELLOW | [
"BLACK",
"BLUE",
"CYAN",
"GREEN",
"LIGHTBLACK_EX",
"LIGHTBLUE_EX",
"LIGHTCYAN_EX",
"LIGHTGREEN_EX",
"LIGHTMAGENTA_EX",
"LIGHTRED_EX",
"LIGHTWHITE_EX",
"LIGHTYELLOW_EX",
"MAGENTA",
"RED",
"RESET",
"WHITE",
"YELLOW",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore. | , "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-282-19 | infile | typewriter_log | [
"chat_plugins",
"console_handler",
"debug",
"double_check",
"error",
"file_handler",
"get_log_directory",
"info",
"json_logger",
"log_json",
"logger",
"set_level",
"speak_mode",
"typewriter_log",
"typing_console_handler",
"typing_logger",
"warn",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger. | ("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-282-45 | infile | GREEN | [
"BLACK",
"BLUE",
"CYAN",
"GREEN",
"LIGHTBLACK_EX",
"LIGHTBLUE_EX",
"LIGHTCYAN_EX",
"LIGHTGREEN_EX",
"LIGHTMAGENTA_EX",
"LIGHTRED_EX",
"LIGHTWHITE_EX",
"LIGHTYELLOW_EX",
"MAGENTA",
"RED",
"RESET",
"WHITE",
"YELLOW",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore. | , line.strip())
logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-283-11 | infile | typewriter_log | [
"chat_plugins",
"console_handler",
"debug",
"double_check",
"error",
"file_handler",
"get_log_directory",
"info",
"json_logger",
"log_json",
"logger",
"set_level",
"speak_mode",
"typewriter_log",
"typing_console_handler",
"typing_logger",
"warn",
"_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger. | ("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
27 | 27-283-45 | infile | YELLOW | [
"BLACK",
"BLUE",
"CYAN",
"GREEN",
"LIGHTBLACK_EX",
"LIGHTBLUE_EX",
"LIGHTCYAN_EX",
"LIGHTGREEN_EX",
"LIGHTMAGENTA_EX",
"LIGHTRED_EX",
"LIGHTWHITE_EX",
"LIGHTYELLOW_EX",
"MAGENTA",
"RED",
"RESET",
"WHITE",
"YELLOW",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import logging
import os
import random
import re
import time
from logging import LogRecord
from typing import Any
from colorama import Fore, Style
from pilot.log.json_handler import JsonFileHandler, JsonFormatter
from pilot.singleton import Singleton
from pilot.speech import say_text
class Logger(metaclass=Singleton):
"""
Logger that handle titles in different colors.
Outputs logs in console, activity.log, and errors.log
For console handler: simulates typing
"""
def __init__(self):
# create log directory if it doesn't exist
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = "activity.log"
error_file = "error.log"
console_formatter = DbGptFormatter("%(title_color)s %(message)s")
# Create a handler for console which simulate typing
self.typing_console_handler = TypingConsoleHandler()
self.typing_console_handler.setLevel(logging.INFO)
self.typing_console_handler.setFormatter(console_formatter)
# Create a handler for console without typing simulation
self.console_handler = ConsoleHandler()
self.console_handler.setLevel(logging.DEBUG)
self.console_handler.setFormatter(console_formatter)
# Info handler in activity.log
self.file_handler = logging.FileHandler(
os.path.join(log_dir, log_file), "a", "utf-8"
)
self.file_handler.setLevel(logging.DEBUG)
info_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
)
self.file_handler.setFormatter(info_formatter)
# Error handler error.log
error_handler = logging.FileHandler(
os.path.join(log_dir, error_file), "a", "utf-8"
)
error_handler.setLevel(logging.ERROR)
error_formatter = DbGptFormatter(
"%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
" %(message_no_color)s"
)
error_handler.setFormatter(error_formatter)
self.typing_logger = logging.getLogger("TYPER")
self.typing_logger.addHandler(self.typing_console_handler)
self.typing_logger.addHandler(self.file_handler)
self.typing_logger.addHandler(error_handler)
self.typing_logger.setLevel(logging.DEBUG)
self.logger = logging.getLogger("LOGGER")
self.logger.addHandler(self.console_handler)
self.logger.addHandler(self.file_handler)
self.logger.addHandler(error_handler)
self.logger.setLevel(logging.DEBUG)
self.json_logger = logging.getLogger("JSON_LOGGER")
self.json_logger.addHandler(self.file_handler)
self.json_logger.addHandler(error_handler)
self.json_logger.setLevel(logging.DEBUG)
self.speak_mode = False
self.chat_plugins = []
def typewriter_log(
self, title="", title_color="", content="", speak_text=False, level=logging.INFO
):
if speak_text and self.speak_mode:
say_text(f"{title}. {content}")
for plugin in self.chat_plugins:
plugin.report(f"{title}. {content}")
if content:
if isinstance(content, list):
content = " ".join(content)
else:
content = ""
self.typing_logger.log(
level, content, extra={"title": title, "color": title_color}
)
def debug(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.DEBUG)
def info(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.INFO)
def warn(
self,
message,
title="",
title_color="",
):
self._log(title, title_color, message, logging.WARN)
def error(self, title, message=""):
self._log(title, Fore.RED, message, logging.ERROR)
def _log(
self,
title: str = "",
title_color: str = "",
message: str = "",
level=logging.INFO,
):
if message:
if isinstance(message, list):
message = " ".join(message)
self.logger.log(
level, message, extra={"title": str(title), "color": str(title_color)}
)
def set_level(self, level):
self.logger.setLevel(level)
self.typing_logger.setLevel(level)
def double_check(self, additionalText=None):
if not additionalText:
additionalText = (
"Please ensure you've setup and configured everything"
" correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
"double check. You can also create a github issue or join the discord"
" and ask there!"
)
self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
def log_json(self, data: Any, file_name: str) -> None:
# Define log directory
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
# Create a handler for JSON files
json_file_path = os.path.join(log_dir, file_name)
json_data_handler = JsonFileHandler(json_file_path)
json_data_handler.setFormatter(JsonFormatter())
# Log the JSON data using the custom file handler
self.json_logger.addHandler(json_data_handler)
self.json_logger.debug(data)
self.json_logger.removeHandler(json_data_handler)
def get_log_directory(self):
this_files_dir_path = os.path.dirname(__file__)
log_dir = os.path.join(this_files_dir_path, "../logs")
return os.path.abspath(log_dir)
"""
Output stream to console using simulated typing
"""
class TypingConsoleHandler(logging.StreamHandler):
def emit(self, record):
min_typing_speed = 0.05
max_typing_speed = 0.01
msg = self.format(record)
try:
words = msg.split()
for i, word in enumerate(words):
print(word, end="", flush=True)
if i < len(words) - 1:
print(" ", end="", flush=True)
typing_speed = random.uniform(min_typing_speed, max_typing_speed)
time.sleep(typing_speed)
# type faster after each word
min_typing_speed = min_typing_speed * 0.95
max_typing_speed = max_typing_speed * 0.95
print()
except Exception:
self.handleError(record)
class ConsoleHandler(logging.StreamHandler):
def emit(self, record) -> None:
msg = self.format(record)
try:
print(msg)
except Exception:
self.handleError(record)
class DbGptFormatter(logging.Formatter):
"""
Allows to handle custom placeholders 'title_color' and 'message_no_color'.
To use this formatter, make sure to pass 'color', 'title' as log extras.
"""
def format(self, record: LogRecord) -> str:
if hasattr(record, "color"):
record.title_color = (
getattr(record, "color")
+ getattr(record, "title", "")
+ " "
+ Style.RESET_ALL
)
else:
record.title_color = getattr(record, "title", "")
# Add this line to set 'title' to an empty string if it doesn't exist
record.title = getattr(record, "title", "")
if hasattr(record, "msg"):
record.message_no_color = remove_color_codes(getattr(record, "msg"))
else:
record.message_no_color = ""
return super().format(record)
def remove_color_codes(s: str) -> str:
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", s)
logger = Logger()
def print_assistant_thoughts(
ai_name: object,
assistant_reply_json_valid: object,
speak_mode: bool = False,
) -> None:
assistant_thoughts_reasoning = None
assistant_thoughts_plan = None
assistant_thoughts_speak = None
assistant_thoughts_criticism = None
assistant_thoughts = assistant_reply_json_valid.get("thoughts", {})
assistant_thoughts_text = assistant_thoughts.get("text")
if assistant_thoughts:
assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
assistant_thoughts_plan = assistant_thoughts.get("plan")
assistant_thoughts_criticism = assistant_thoughts.get("criticism")
assistant_thoughts_speak = assistant_thoughts.get("speak")
logger.typewriter_log(
f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
)
logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}")
if assistant_thoughts_plan:
logger.typewriter_log("PLAN:", Fore.YELLOW, "")
# If it's a list, join it into a string
if isinstance(assistant_thoughts_plan, list):
assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
elif isinstance(assistant_thoughts_plan, dict):
assistant_thoughts_plan = str(assistant_thoughts_plan)
# Split the input_string using the newline character and dashes
lines = assistant_thoughts_plan.split("\n")
for line in lines:
line = line.lstrip("- ")
logger.typewriter_log("- ", Fore.GREEN, line.strip())
logger.typewriter_log("CRITICISM:", Fore. | , f"{assistant_thoughts_criticism}")
# Speak the assistant's thoughts
if speak_mode and assistant_thoughts_speak:
say_text(assistant_thoughts_speak)
| eosphoros-ai__DB-GPT |
30 | 30-11-20 | common | load | [
"codecs",
"decoder",
"detect_encoding",
"dump",
"dumps",
"encoder",
"JSONDecodeError",
"JSONDecoder",
"JSONEncoder",
"load",
"loads",
"scanner",
"tool",
"_default_decoder",
"_default_encoder",
"__all__",
"__author__",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import os
import json
import functools
from aiohttp import web
from dask_gateway_server.options import Options, Select, Mapping
from dask_gateway_server.auth import JupyterHubAuthenticator
def dask_gateway_config(path="/var/lib/dask-gateway/config.json"):
with open(path) as f:
return json. | (f)
config = dask_gateway_config()
c.DaskGateway.log_level = config["gateway"]["loglevel"]
# Configure addresses
c.DaskGateway.address = ":8000"
c.KubeBackend.api_url = f'http://{config["gateway_service_name"]}.{config["gateway_service_namespace"]}:8000/api'
c.DaskGateway.backend_class = "dask_gateway_server.backends.kubernetes.KubeBackend"
c.KubeBackend.gateway_instance = config["gateway_service_name"]
# ========= Dask Cluster Default Configuration =========
c.KubeClusterConfig.image = (
f"{config['cluster-image']['name']}:{config['cluster-image']['tag']}"
)
c.KubeClusterConfig.image_pull_policy = config["cluster"]["image_pull_policy"]
c.KubeClusterConfig.environment = config["cluster"]["environment"]
c.KubeClusterConfig.scheduler_cores = config["cluster"]["scheduler_cores"]
c.KubeClusterConfig.scheduler_cores_limit = config["cluster"]["scheduler_cores_limit"]
c.KubeClusterConfig.scheduler_memory = config["cluster"]["scheduler_memory"]
c.KubeClusterConfig.scheduler_memory_limit = config["cluster"]["scheduler_memory_limit"]
c.KubeClusterConfig.scheduler_extra_container_config = config["cluster"][
"scheduler_extra_container_config"
]
c.KubeClusterConfig.scheduler_extra_pod_config = config["cluster"][
"scheduler_extra_pod_config"
]
c.KubeClusterConfig.worker_cores = config["cluster"]["worker_cores"]
c.KubeClusterConfig.worker_cores_limit = config["cluster"]["worker_cores_limit"]
c.KubeClusterConfig.worker_memory = config["cluster"]["worker_memory"]
c.KubeClusterConfig.worker_memory_limit = config["cluster"]["worker_memory_limit"]
c.KubeClusterConfig.worker_extra_container_config = config["cluster"][
"worker_extra_container_config"
]
c.KubeClusterConfig.worker_extra_pod_config = config["cluster"][
"worker_extra_pod_config"
]
# ============ Authentication =================
class QHubAuthentication(JupyterHubAuthenticator):
async def authenticate(self, request):
user = await super().authenticate(request)
url = f"{self.jupyterhub_api_url}/users/{user.name}"
kwargs = {
"headers": {"Authorization": "token %s" % self.jupyterhub_api_token},
"ssl": self.ssl_context,
}
resp = await self.session.get(url, **kwargs)
data = (await resp.json())["auth_state"]["oauth_user"]
if (
"dask_gateway_developer" not in data["roles"]
and "dask_gateway_admin" not in data["roles"]
):
raise web.HTTPInternalServerError(
reason="Permission failure user does not have required dask_gateway roles"
)
user.admin = "dask_gateway_admin" in data["roles"]
user.groups = [
os.path.basename(group)
for group in data["groups"]
if os.path.dirname(group) == "/projects"
]
return user
c.DaskGateway.authenticator_class = QHubAuthentication
c.JupyterHubAuthenticator.jupyterhub_api_url = config["jupyterhub_api_url"]
c.JupyterHubAuthenticator.jupyterhub_api_token = config["jupyterhub_api_token"]
# ==================== Profiles =======================
def get_packages(conda_prefix):
packages = set()
for filename in os.listdir(os.path.join(conda_prefix, "conda-meta")):
if filename.endswith(".json"):
with open(os.path.join(conda_prefix, "conda-meta", filename)) as f:
packages.add(json.load(f).get("name"))
return packages
def get_conda_prefixes(conda_store_mount):
for namespace in os.listdir(conda_store_mount):
if os.path.isdir(os.path.join(conda_store_mount, namespace, "envs")):
for name in os.listdir(os.path.join(conda_store_mount, namespace, "envs")):
yield namespace, name, os.path.join(
conda_store_mount, namespace, "envs", name
)
def list_dask_environments(conda_store_mount):
for namespace, name, conda_prefix in get_conda_prefixes(conda_store_mount):
if {"dask", "distributed"} <= get_packages(conda_prefix):
yield namespace, name, conda_prefix
def base_node_group():
worker_node_group = {
config["worker-node-group"]["key"]: config["worker-node-group"]["value"]
}
return {
"scheduler_extra_pod_config": {"nodeSelector": worker_node_group},
"worker_extra_pod_config": {"nodeSelector": worker_node_group},
}
def base_conda_store_mounts(namespace, name):
conda_store_pvc_name = config["conda-store-pvc"]
conda_store_mount = config["conda-store-mount"]
return {
"scheduler_extra_pod_config": {
"volumes": [
{
"name": "conda-store",
"persistentVolumeClaim": {
"claimName": conda_store_pvc_name,
},
}
]
},
"scheduler_extra_container_config": {
"volumeMounts": [
{
"mountPath": os.path.join(conda_store_mount, namespace),
"name": "conda-store",
"subPath": namespace,
}
]
},
"worker_extra_pod_config": {
"volumes": [
{
"name": "conda-store",
"persistentVolumeClaim": {
"claimName": conda_store_pvc_name,
},
}
]
},
"worker_extra_container_config": {
"volumeMounts": [
{
"mountPath": os.path.join(conda_store_mount, namespace),
"name": "conda-store",
"subPath": namespace,
}
]
},
"worker_cmd": "/opt/conda-run-worker",
"scheduler_cmd": "/opt/conda-run-scheduler",
"environment": {
"CONDA_ENVIRONMENT": os.path.join(
conda_store_mount, namespace, "envs", name
),
},
}
def base_username_mount(username, uid=1000, gid=100):
return {
"scheduler_extra_pod_config": {"volumes": [{"name": "home", "emptyDir": {}}]},
"scheduler_extra_container_config": {
"securityContext": {"runAsUser": uid, "runAsGroup": gid, "fsGroup": gid},
"workingDir": f"/home/{username}",
"volumeMounts": [
{
"mountPath": f"/home/{username}",
"name": "home",
}
],
},
"worker_extra_pod_config": {"volumes": [{"name": "home", "emptyDir": {}}]},
"worker_extra_container_config": {
"securityContext": {"runAsUser": uid, "runAsGroup": gid, "fsGroup": gid},
"workingDir": f"/home/{username}",
"volumeMounts": [
{
"mountPath": f"/home/{username}",
"name": "home",
}
],
},
"environment": {
"HOME": f"/home/{username}",
},
}
def worker_profile(options, user):
namespace, name = options.conda_environment.split("/")
return functools.reduce(
deep_merge,
[
base_node_group(),
base_conda_store_mounts(namespace, name),
base_username_mount(user.name),
config["profiles"][options.profile],
{"environment": {**options.environment_vars}},
],
{},
)
def user_options(user):
allowed_namespaces = set(["filesystem", "default", user.name] + list(user.groups))
environments = {
f"{namespace}/{name}": conda_prefix
for namespace, name, conda_prefix in list_dask_environments(
config["conda-store-mount"]
)
if namespace in allowed_namespaces
}
args = []
if environments:
args += [
Select(
"conda_environment",
list(environments.keys()),
default=list(environments.keys())[0],
label="Environment",
)
]
if config["profiles"]:
args += [
Select(
"profile",
list(config["profiles"].keys()),
default=list(config["profiles"].keys())[0],
label="Cluster Profile",
)
]
args += [
Mapping("environment_vars", {}, label="Environment Variables"),
]
return Options(
*args,
handler=worker_profile,
)
c.Backend.cluster_options = user_options
# ============== utils ============
def deep_merge(d1, d2):
"""Deep merge two dictionaries.
>>> value_1 = {
'a': [1, 2],
'b': {'c': 1, 'z': [5, 6]},
'e': {'f': {'g': {}}},
'm': 1,
}
>>> value_2 = {
'a': [3, 4],
'b': {'d': 2, 'z': [7]},
'e': {'f': {'h': 1}},
'm': [1],
}
>>> print(deep_merge(value_1, value_2))
{'m': 1, 'e': {'f': {'g': {}, 'h': 1}}, 'b': {'d': 2, 'c': 1, 'z': [5, 6, 7]}, 'a': [1, 2, 3, 4]}
"""
if isinstance(d1, dict) and isinstance(d2, dict):
d3 = {}
for key in d1.keys() | d2.keys():
if key in d1 and key in d2:
d3[key] = deep_merge(d1[key], d2[key])
elif key in d1:
d3[key] = d1[key]
elif key in d2:
d3[key] = d2[key]
return d3
elif isinstance(d1, list) and isinstance(d2, list):
return [*d1, *d2]
else: # if they don't match use left one
return d1
| nebari-dev__nebari |
30 | 30-59-29 | infile | authenticate | [
"add_traits",
"authenticate",
"authenticate_and_handle",
"cache",
"cache_max_age",
"class_config_rst_doc",
"class_config_section",
"class_get_help",
"class_get_trait_help",
"class_own_trait_events",
"class_own_traits",
"class_print_help",
"class_trait_names",
"class_traits",
"cleanup",
"config",
"cookie_name",
"cross_validation_lock",
"get_token",
"has_trait",
"hold_trait_notifications",
"jupyterhub_api_token",
"jupyterhub_api_url",
"log",
"notify_change",
"observe",
"on_trait_change",
"parent",
"pre_response",
"section_names",
"session",
"set_trait",
"setup",
"setup_instance",
"ssl_context",
"tls_ca",
"tls_cert",
"tls_key",
"trait_defaults",
"trait_events",
"trait_has_value",
"trait_metadata",
"trait_names",
"trait_values",
"traits",
"unobserve",
"unobserve_all",
"update_config",
"_add_notifiers",
"_all_trait_default_generators",
"_config_changed",
"_cross_validation_lock",
"_default_cache",
"_default_cookie_name",
"_default_jupyterhub_api_token",
"_default_jupyterhub_api_url",
"_defining_class",
"_find_my_config",
"_get_log_handler",
"_get_trait_default_generator",
"_load_config",
"_log_default",
"_notify_observers",
"_notify_trait",
"_register_validator",
"_remove_notifiers",
"_static_immutable_initial_values",
"_trait_notifiers",
"_trait_validators",
"_trait_values",
"_traits",
"_validate_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__getstate__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__setstate__",
"__sizeof__",
"__slots__",
"__str__"
] | import os
import json
import functools
from aiohttp import web
from dask_gateway_server.options import Options, Select, Mapping
from dask_gateway_server.auth import JupyterHubAuthenticator
def dask_gateway_config(path="/var/lib/dask-gateway/config.json"):
with open(path) as f:
return json.load(f)
config = dask_gateway_config()
c.DaskGateway.log_level = config["gateway"]["loglevel"]
# Configure addresses
c.DaskGateway.address = ":8000"
c.KubeBackend.api_url = f'http://{config["gateway_service_name"]}.{config["gateway_service_namespace"]}:8000/api'
c.DaskGateway.backend_class = "dask_gateway_server.backends.kubernetes.KubeBackend"
c.KubeBackend.gateway_instance = config["gateway_service_name"]
# ========= Dask Cluster Default Configuration =========
c.KubeClusterConfig.image = (
f"{config['cluster-image']['name']}:{config['cluster-image']['tag']}"
)
c.KubeClusterConfig.image_pull_policy = config["cluster"]["image_pull_policy"]
c.KubeClusterConfig.environment = config["cluster"]["environment"]
c.KubeClusterConfig.scheduler_cores = config["cluster"]["scheduler_cores"]
c.KubeClusterConfig.scheduler_cores_limit = config["cluster"]["scheduler_cores_limit"]
c.KubeClusterConfig.scheduler_memory = config["cluster"]["scheduler_memory"]
c.KubeClusterConfig.scheduler_memory_limit = config["cluster"]["scheduler_memory_limit"]
c.KubeClusterConfig.scheduler_extra_container_config = config["cluster"][
"scheduler_extra_container_config"
]
c.KubeClusterConfig.scheduler_extra_pod_config = config["cluster"][
"scheduler_extra_pod_config"
]
c.KubeClusterConfig.worker_cores = config["cluster"]["worker_cores"]
c.KubeClusterConfig.worker_cores_limit = config["cluster"]["worker_cores_limit"]
c.KubeClusterConfig.worker_memory = config["cluster"]["worker_memory"]
c.KubeClusterConfig.worker_memory_limit = config["cluster"]["worker_memory_limit"]
c.KubeClusterConfig.worker_extra_container_config = config["cluster"][
"worker_extra_container_config"
]
c.KubeClusterConfig.worker_extra_pod_config = config["cluster"][
"worker_extra_pod_config"
]
# ============ Authentication =================
class QHubAuthentication(JupyterHubAuthenticator):
async def authenticate(self, request):
user = await super(). | (request)
url = f"{self.jupyterhub_api_url}/users/{user.name}"
kwargs = {
"headers": {"Authorization": "token %s" % self.jupyterhub_api_token},
"ssl": self.ssl_context,
}
resp = await self.session.get(url, **kwargs)
data = (await resp.json())["auth_state"]["oauth_user"]
if (
"dask_gateway_developer" not in data["roles"]
and "dask_gateway_admin" not in data["roles"]
):
raise web.HTTPInternalServerError(
reason="Permission failure user does not have required dask_gateway roles"
)
user.admin = "dask_gateway_admin" in data["roles"]
user.groups = [
os.path.basename(group)
for group in data["groups"]
if os.path.dirname(group) == "/projects"
]
return user
c.DaskGateway.authenticator_class = QHubAuthentication
c.JupyterHubAuthenticator.jupyterhub_api_url = config["jupyterhub_api_url"]
c.JupyterHubAuthenticator.jupyterhub_api_token = config["jupyterhub_api_token"]
# ==================== Profiles =======================
def get_packages(conda_prefix):
packages = set()
for filename in os.listdir(os.path.join(conda_prefix, "conda-meta")):
if filename.endswith(".json"):
with open(os.path.join(conda_prefix, "conda-meta", filename)) as f:
packages.add(json.load(f).get("name"))
return packages
def get_conda_prefixes(conda_store_mount):
for namespace in os.listdir(conda_store_mount):
if os.path.isdir(os.path.join(conda_store_mount, namespace, "envs")):
for name in os.listdir(os.path.join(conda_store_mount, namespace, "envs")):
yield namespace, name, os.path.join(
conda_store_mount, namespace, "envs", name
)
def list_dask_environments(conda_store_mount):
for namespace, name, conda_prefix in get_conda_prefixes(conda_store_mount):
if {"dask", "distributed"} <= get_packages(conda_prefix):
yield namespace, name, conda_prefix
def base_node_group():
worker_node_group = {
config["worker-node-group"]["key"]: config["worker-node-group"]["value"]
}
return {
"scheduler_extra_pod_config": {"nodeSelector": worker_node_group},
"worker_extra_pod_config": {"nodeSelector": worker_node_group},
}
def base_conda_store_mounts(namespace, name):
conda_store_pvc_name = config["conda-store-pvc"]
conda_store_mount = config["conda-store-mount"]
return {
"scheduler_extra_pod_config": {
"volumes": [
{
"name": "conda-store",
"persistentVolumeClaim": {
"claimName": conda_store_pvc_name,
},
}
]
},
"scheduler_extra_container_config": {
"volumeMounts": [
{
"mountPath": os.path.join(conda_store_mount, namespace),
"name": "conda-store",
"subPath": namespace,
}
]
},
"worker_extra_pod_config": {
"volumes": [
{
"name": "conda-store",
"persistentVolumeClaim": {
"claimName": conda_store_pvc_name,
},
}
]
},
"worker_extra_container_config": {
"volumeMounts": [
{
"mountPath": os.path.join(conda_store_mount, namespace),
"name": "conda-store",
"subPath": namespace,
}
]
},
"worker_cmd": "/opt/conda-run-worker",
"scheduler_cmd": "/opt/conda-run-scheduler",
"environment": {
"CONDA_ENVIRONMENT": os.path.join(
conda_store_mount, namespace, "envs", name
),
},
}
def base_username_mount(username, uid=1000, gid=100):
return {
"scheduler_extra_pod_config": {"volumes": [{"name": "home", "emptyDir": {}}]},
"scheduler_extra_container_config": {
"securityContext": {"runAsUser": uid, "runAsGroup": gid, "fsGroup": gid},
"workingDir": f"/home/{username}",
"volumeMounts": [
{
"mountPath": f"/home/{username}",
"name": "home",
}
],
},
"worker_extra_pod_config": {"volumes": [{"name": "home", "emptyDir": {}}]},
"worker_extra_container_config": {
"securityContext": {"runAsUser": uid, "runAsGroup": gid, "fsGroup": gid},
"workingDir": f"/home/{username}",
"volumeMounts": [
{
"mountPath": f"/home/{username}",
"name": "home",
}
],
},
"environment": {
"HOME": f"/home/{username}",
},
}
def worker_profile(options, user):
namespace, name = options.conda_environment.split("/")
return functools.reduce(
deep_merge,
[
base_node_group(),
base_conda_store_mounts(namespace, name),
base_username_mount(user.name),
config["profiles"][options.profile],
{"environment": {**options.environment_vars}},
],
{},
)
def user_options(user):
allowed_namespaces = set(["filesystem", "default", user.name] + list(user.groups))
environments = {
f"{namespace}/{name}": conda_prefix
for namespace, name, conda_prefix in list_dask_environments(
config["conda-store-mount"]
)
if namespace in allowed_namespaces
}
args = []
if environments:
args += [
Select(
"conda_environment",
list(environments.keys()),
default=list(environments.keys())[0],
label="Environment",
)
]
if config["profiles"]:
args += [
Select(
"profile",
list(config["profiles"].keys()),
default=list(config["profiles"].keys())[0],
label="Cluster Profile",
)
]
args += [
Mapping("environment_vars", {}, label="Environment Variables"),
]
return Options(
*args,
handler=worker_profile,
)
c.Backend.cluster_options = user_options
# ============== utils ============
def deep_merge(d1, d2):
"""Deep merge two dictionaries.
>>> value_1 = {
'a': [1, 2],
'b': {'c': 1, 'z': [5, 6]},
'e': {'f': {'g': {}}},
'm': 1,
}
>>> value_2 = {
'a': [3, 4],
'b': {'d': 2, 'z': [7]},
'e': {'f': {'h': 1}},
'm': [1],
}
>>> print(deep_merge(value_1, value_2))
{'m': 1, 'e': {'f': {'g': {}, 'h': 1}}, 'b': {'d': 2, 'c': 1, 'z': [5, 6, 7]}, 'a': [1, 2, 3, 4]}
"""
if isinstance(d1, dict) and isinstance(d2, dict):
d3 = {}
for key in d1.keys() | d2.keys():
if key in d1 and key in d2:
d3[key] = deep_merge(d1[key], d2[key])
elif key in d1:
d3[key] = d1[key]
elif key in d2:
d3[key] = d2[key]
return d3
elif isinstance(d1, list) and isinstance(d2, list):
return [*d1, *d2]
else: # if they don't match use left one
return d1
| nebari-dev__nebari |
30 | 30-65-26 | common | session | [
"add_traits",
"authenticate",
"authenticate_and_handle",
"cache",
"cache_max_age",
"class_config_rst_doc",
"class_config_section",
"class_get_help",
"class_get_trait_help",
"class_own_trait_events",
"class_own_traits",
"class_print_help",
"class_trait_names",
"class_traits",
"cleanup",
"config",
"cookie_name",
"cross_validation_lock",
"get_token",
"has_trait",
"hold_trait_notifications",
"jupyterhub_api_token",
"jupyterhub_api_url",
"log",
"notify_change",
"observe",
"on_trait_change",
"parent",
"pre_response",
"section_names",
"session",
"set_trait",
"setup",
"setup_instance",
"ssl_context",
"tls_ca",
"tls_cert",
"tls_key",
"trait_defaults",
"trait_events",
"trait_has_value",
"trait_metadata",
"trait_names",
"trait_values",
"traits",
"unobserve",
"unobserve_all",
"update_config",
"_add_notifiers",
"_all_trait_default_generators",
"_config_changed",
"_cross_validation_lock",
"_default_cache",
"_default_cookie_name",
"_default_jupyterhub_api_token",
"_default_jupyterhub_api_url",
"_defining_class",
"_find_my_config",
"_get_log_handler",
"_get_trait_default_generator",
"_load_config",
"_log_default",
"_notify_observers",
"_notify_trait",
"_register_validator",
"_remove_notifiers",
"_static_immutable_initial_values",
"_trait_notifiers",
"_trait_validators",
"_trait_values",
"_traits",
"_validate_log",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__getstate__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__setstate__",
"__sizeof__",
"__slots__",
"__str__"
] | import os
import json
import functools
from aiohttp import web
from dask_gateway_server.options import Options, Select, Mapping
from dask_gateway_server.auth import JupyterHubAuthenticator
def dask_gateway_config(path="/var/lib/dask-gateway/config.json"):
with open(path) as f:
return json.load(f)
config = dask_gateway_config()
c.DaskGateway.log_level = config["gateway"]["loglevel"]
# Configure addresses
c.DaskGateway.address = ":8000"
c.KubeBackend.api_url = f'http://{config["gateway_service_name"]}.{config["gateway_service_namespace"]}:8000/api'
c.DaskGateway.backend_class = "dask_gateway_server.backends.kubernetes.KubeBackend"
c.KubeBackend.gateway_instance = config["gateway_service_name"]
# ========= Dask Cluster Default Configuration =========
c.KubeClusterConfig.image = (
f"{config['cluster-image']['name']}:{config['cluster-image']['tag']}"
)
c.KubeClusterConfig.image_pull_policy = config["cluster"]["image_pull_policy"]
c.KubeClusterConfig.environment = config["cluster"]["environment"]
c.KubeClusterConfig.scheduler_cores = config["cluster"]["scheduler_cores"]
c.KubeClusterConfig.scheduler_cores_limit = config["cluster"]["scheduler_cores_limit"]
c.KubeClusterConfig.scheduler_memory = config["cluster"]["scheduler_memory"]
c.KubeClusterConfig.scheduler_memory_limit = config["cluster"]["scheduler_memory_limit"]
c.KubeClusterConfig.scheduler_extra_container_config = config["cluster"][
"scheduler_extra_container_config"
]
c.KubeClusterConfig.scheduler_extra_pod_config = config["cluster"][
"scheduler_extra_pod_config"
]
c.KubeClusterConfig.worker_cores = config["cluster"]["worker_cores"]
c.KubeClusterConfig.worker_cores_limit = config["cluster"]["worker_cores_limit"]
c.KubeClusterConfig.worker_memory = config["cluster"]["worker_memory"]
c.KubeClusterConfig.worker_memory_limit = config["cluster"]["worker_memory_limit"]
c.KubeClusterConfig.worker_extra_container_config = config["cluster"][
"worker_extra_container_config"
]
c.KubeClusterConfig.worker_extra_pod_config = config["cluster"][
"worker_extra_pod_config"
]
# ============ Authentication =================
class QHubAuthentication(JupyterHubAuthenticator):
async def authenticate(self, request):
user = await super().authenticate(request)
url = f"{self.jupyterhub_api_url}/users/{user.name}"
kwargs = {
"headers": {"Authorization": "token %s" % self.jupyterhub_api_token},
"ssl": self.ssl_context,
}
resp = await self. | .get(url, **kwargs)
data = (await resp.json())["auth_state"]["oauth_user"]
if (
"dask_gateway_developer" not in data["roles"]
and "dask_gateway_admin" not in data["roles"]
):
raise web.HTTPInternalServerError(
reason="Permission failure user does not have required dask_gateway roles"
)
user.admin = "dask_gateway_admin" in data["roles"]
user.groups = [
os.path.basename(group)
for group in data["groups"]
if os.path.dirname(group) == "/projects"
]
return user
c.DaskGateway.authenticator_class = QHubAuthentication
c.JupyterHubAuthenticator.jupyterhub_api_url = config["jupyterhub_api_url"]
c.JupyterHubAuthenticator.jupyterhub_api_token = config["jupyterhub_api_token"]
# ==================== Profiles =======================
def get_packages(conda_prefix):
packages = set()
for filename in os.listdir(os.path.join(conda_prefix, "conda-meta")):
if filename.endswith(".json"):
with open(os.path.join(conda_prefix, "conda-meta", filename)) as f:
packages.add(json.load(f).get("name"))
return packages
def get_conda_prefixes(conda_store_mount):
for namespace in os.listdir(conda_store_mount):
if os.path.isdir(os.path.join(conda_store_mount, namespace, "envs")):
for name in os.listdir(os.path.join(conda_store_mount, namespace, "envs")):
yield namespace, name, os.path.join(
conda_store_mount, namespace, "envs", name
)
def list_dask_environments(conda_store_mount):
for namespace, name, conda_prefix in get_conda_prefixes(conda_store_mount):
if {"dask", "distributed"} <= get_packages(conda_prefix):
yield namespace, name, conda_prefix
def base_node_group():
worker_node_group = {
config["worker-node-group"]["key"]: config["worker-node-group"]["value"]
}
return {
"scheduler_extra_pod_config": {"nodeSelector": worker_node_group},
"worker_extra_pod_config": {"nodeSelector": worker_node_group},
}
def base_conda_store_mounts(namespace, name):
conda_store_pvc_name = config["conda-store-pvc"]
conda_store_mount = config["conda-store-mount"]
return {
"scheduler_extra_pod_config": {
"volumes": [
{
"name": "conda-store",
"persistentVolumeClaim": {
"claimName": conda_store_pvc_name,
},
}
]
},
"scheduler_extra_container_config": {
"volumeMounts": [
{
"mountPath": os.path.join(conda_store_mount, namespace),
"name": "conda-store",
"subPath": namespace,
}
]
},
"worker_extra_pod_config": {
"volumes": [
{
"name": "conda-store",
"persistentVolumeClaim": {
"claimName": conda_store_pvc_name,
},
}
]
},
"worker_extra_container_config": {
"volumeMounts": [
{
"mountPath": os.path.join(conda_store_mount, namespace),
"name": "conda-store",
"subPath": namespace,
}
]
},
"worker_cmd": "/opt/conda-run-worker",
"scheduler_cmd": "/opt/conda-run-scheduler",
"environment": {
"CONDA_ENVIRONMENT": os.path.join(
conda_store_mount, namespace, "envs", name
),
},
}
def base_username_mount(username, uid=1000, gid=100):
return {
"scheduler_extra_pod_config": {"volumes": [{"name": "home", "emptyDir": {}}]},
"scheduler_extra_container_config": {
"securityContext": {"runAsUser": uid, "runAsGroup": gid, "fsGroup": gid},
"workingDir": f"/home/{username}",
"volumeMounts": [
{
"mountPath": f"/home/{username}",
"name": "home",
}
],
},
"worker_extra_pod_config": {"volumes": [{"name": "home", "emptyDir": {}}]},
"worker_extra_container_config": {
"securityContext": {"runAsUser": uid, "runAsGroup": gid, "fsGroup": gid},
"workingDir": f"/home/{username}",
"volumeMounts": [
{
"mountPath": f"/home/{username}",
"name": "home",
}
],
},
"environment": {
"HOME": f"/home/{username}",
},
}
def worker_profile(options, user):
namespace, name = options.conda_environment.split("/")
return functools.reduce(
deep_merge,
[
base_node_group(),
base_conda_store_mounts(namespace, name),
base_username_mount(user.name),
config["profiles"][options.profile],
{"environment": {**options.environment_vars}},
],
{},
)
def user_options(user):
allowed_namespaces = set(["filesystem", "default", user.name] + list(user.groups))
environments = {
f"{namespace}/{name}": conda_prefix
for namespace, name, conda_prefix in list_dask_environments(
config["conda-store-mount"]
)
if namespace in allowed_namespaces
}
args = []
if environments:
args += [
Select(
"conda_environment",
list(environments.keys()),
default=list(environments.keys())[0],
label="Environment",
)
]
if config["profiles"]:
args += [
Select(
"profile",
list(config["profiles"].keys()),
default=list(config["profiles"].keys())[0],
label="Cluster Profile",
)
]
args += [
Mapping("environment_vars", {}, label="Environment Variables"),
]
return Options(
*args,
handler=worker_profile,
)
c.Backend.cluster_options = user_options
# ============== utils ============
def deep_merge(d1, d2):
"""Deep merge two dictionaries.
>>> value_1 = {
'a': [1, 2],
'b': {'c': 1, 'z': [5, 6]},
'e': {'f': {'g': {}}},
'm': 1,
}
>>> value_2 = {
'a': [3, 4],
'b': {'d': 2, 'z': [7]},
'e': {'f': {'h': 1}},
'm': [1],
}
>>> print(deep_merge(value_1, value_2))
{'m': 1, 'e': {'f': {'g': {}, 'h': 1}}, 'b': {'d': 2, 'c': 1, 'z': [5, 6, 7]}, 'a': [1, 2, 3, 4]}
"""
if isinstance(d1, dict) and isinstance(d2, dict):
d3 = {}
for key in d1.keys() | d2.keys():
if key in d1 and key in d2:
d3[key] = deep_merge(d1[key], d2[key])
elif key in d1:
d3[key] = d1[key]
elif key in d2:
d3[key] = d2[key]
return d3
elif isinstance(d1, list) and isinstance(d2, list):
return [*d1, *d2]
else: # if they don't match use left one
return d1
| nebari-dev__nebari |
30 | 30-65-34 | common | get | [
"ATTRS",
"auth",
"auto_decompress",
"close",
"closed",
"connector",
"connector_owner",
"cookie_jar",
"delete",
"detach",
"get",
"head",
"headers",
"json_serialize",
"loop",
"options",
"patch",
"post",
"put",
"raise_for_status",
"request",
"requote_redirect_url",
"skip_auto_headers",
"timeout",
"trace_configs",
"trust_env",
"version",
"ws_connect",
"_auto_decompress",
"_base_url",
"_build_url",
"_connector",
"_connector_owner",
"_cookie_jar",
"_default_auth",
"_default_headers",
"_json_serialize",
"_loop",
"_max_field_size",
"_max_line_size",
"_prepare_headers",
"_raise_for_status",
"_read_bufsize",
"_request",
"_request_class",
"_requote_redirect_url",
"_resolve_charset",
"_response_class",
"_skip_auto_headers",
"_source_traceback",
"_timeout",
"_trace_configs",
"_trust_env",
"_version",
"_ws_connect",
"_ws_response_class",
"__aenter__",
"__aexit__",
"__annotations__",
"__class__",
"__del__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__enter__",
"__eq__",
"__exit__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import os
import json
import functools
from aiohttp import web
from dask_gateway_server.options import Options, Select, Mapping
from dask_gateway_server.auth import JupyterHubAuthenticator
def dask_gateway_config(path="/var/lib/dask-gateway/config.json"):
with open(path) as f:
return json.load(f)
config = dask_gateway_config()
c.DaskGateway.log_level = config["gateway"]["loglevel"]
# Configure addresses
c.DaskGateway.address = ":8000"
c.KubeBackend.api_url = f'http://{config["gateway_service_name"]}.{config["gateway_service_namespace"]}:8000/api'
c.DaskGateway.backend_class = "dask_gateway_server.backends.kubernetes.KubeBackend"
c.KubeBackend.gateway_instance = config["gateway_service_name"]
# ========= Dask Cluster Default Configuration =========
c.KubeClusterConfig.image = (
f"{config['cluster-image']['name']}:{config['cluster-image']['tag']}"
)
c.KubeClusterConfig.image_pull_policy = config["cluster"]["image_pull_policy"]
c.KubeClusterConfig.environment = config["cluster"]["environment"]
c.KubeClusterConfig.scheduler_cores = config["cluster"]["scheduler_cores"]
c.KubeClusterConfig.scheduler_cores_limit = config["cluster"]["scheduler_cores_limit"]
c.KubeClusterConfig.scheduler_memory = config["cluster"]["scheduler_memory"]
c.KubeClusterConfig.scheduler_memory_limit = config["cluster"]["scheduler_memory_limit"]
c.KubeClusterConfig.scheduler_extra_container_config = config["cluster"][
"scheduler_extra_container_config"
]
c.KubeClusterConfig.scheduler_extra_pod_config = config["cluster"][
"scheduler_extra_pod_config"
]
c.KubeClusterConfig.worker_cores = config["cluster"]["worker_cores"]
c.KubeClusterConfig.worker_cores_limit = config["cluster"]["worker_cores_limit"]
c.KubeClusterConfig.worker_memory = config["cluster"]["worker_memory"]
c.KubeClusterConfig.worker_memory_limit = config["cluster"]["worker_memory_limit"]
c.KubeClusterConfig.worker_extra_container_config = config["cluster"][
"worker_extra_container_config"
]
c.KubeClusterConfig.worker_extra_pod_config = config["cluster"][
"worker_extra_pod_config"
]
# ============ Authentication =================
class QHubAuthentication(JupyterHubAuthenticator):
async def authenticate(self, request):
user = await super().authenticate(request)
url = f"{self.jupyterhub_api_url}/users/{user.name}"
kwargs = {
"headers": {"Authorization": "token %s" % self.jupyterhub_api_token},
"ssl": self.ssl_context,
}
resp = await self.session. | (url, **kwargs)
data = (await resp.json())["auth_state"]["oauth_user"]
if (
"dask_gateway_developer" not in data["roles"]
and "dask_gateway_admin" not in data["roles"]
):
raise web.HTTPInternalServerError(
reason="Permission failure user does not have required dask_gateway roles"
)
user.admin = "dask_gateway_admin" in data["roles"]
user.groups = [
os.path.basename(group)
for group in data["groups"]
if os.path.dirname(group) == "/projects"
]
return user
c.DaskGateway.authenticator_class = QHubAuthentication
c.JupyterHubAuthenticator.jupyterhub_api_url = config["jupyterhub_api_url"]
c.JupyterHubAuthenticator.jupyterhub_api_token = config["jupyterhub_api_token"]
# ==================== Profiles =======================
def get_packages(conda_prefix):
packages = set()
for filename in os.listdir(os.path.join(conda_prefix, "conda-meta")):
if filename.endswith(".json"):
with open(os.path.join(conda_prefix, "conda-meta", filename)) as f:
packages.add(json.load(f).get("name"))
return packages
def get_conda_prefixes(conda_store_mount):
for namespace in os.listdir(conda_store_mount):
if os.path.isdir(os.path.join(conda_store_mount, namespace, "envs")):
for name in os.listdir(os.path.join(conda_store_mount, namespace, "envs")):
yield namespace, name, os.path.join(
conda_store_mount, namespace, "envs", name
)
def list_dask_environments(conda_store_mount):
for namespace, name, conda_prefix in get_conda_prefixes(conda_store_mount):
if {"dask", "distributed"} <= get_packages(conda_prefix):
yield namespace, name, conda_prefix
def base_node_group():
worker_node_group = {
config["worker-node-group"]["key"]: config["worker-node-group"]["value"]
}
return {
"scheduler_extra_pod_config": {"nodeSelector": worker_node_group},
"worker_extra_pod_config": {"nodeSelector": worker_node_group},
}
def base_conda_store_mounts(namespace, name):
conda_store_pvc_name = config["conda-store-pvc"]
conda_store_mount = config["conda-store-mount"]
return {
"scheduler_extra_pod_config": {
"volumes": [
{
"name": "conda-store",
"persistentVolumeClaim": {
"claimName": conda_store_pvc_name,
},
}
]
},
"scheduler_extra_container_config": {
"volumeMounts": [
{
"mountPath": os.path.join(conda_store_mount, namespace),
"name": "conda-store",
"subPath": namespace,
}
]
},
"worker_extra_pod_config": {
"volumes": [
{
"name": "conda-store",
"persistentVolumeClaim": {
"claimName": conda_store_pvc_name,
},
}
]
},
"worker_extra_container_config": {
"volumeMounts": [
{
"mountPath": os.path.join(conda_store_mount, namespace),
"name": "conda-store",
"subPath": namespace,
}
]
},
"worker_cmd": "/opt/conda-run-worker",
"scheduler_cmd": "/opt/conda-run-scheduler",
"environment": {
"CONDA_ENVIRONMENT": os.path.join(
conda_store_mount, namespace, "envs", name
),
},
}
def base_username_mount(username, uid=1000, gid=100):
return {
"scheduler_extra_pod_config": {"volumes": [{"name": "home", "emptyDir": {}}]},
"scheduler_extra_container_config": {
"securityContext": {"runAsUser": uid, "runAsGroup": gid, "fsGroup": gid},
"workingDir": f"/home/{username}",
"volumeMounts": [
{
"mountPath": f"/home/{username}",
"name": "home",
}
],
},
"worker_extra_pod_config": {"volumes": [{"name": "home", "emptyDir": {}}]},
"worker_extra_container_config": {
"securityContext": {"runAsUser": uid, "runAsGroup": gid, "fsGroup": gid},
"workingDir": f"/home/{username}",
"volumeMounts": [
{
"mountPath": f"/home/{username}",
"name": "home",
}
],
},
"environment": {
"HOME": f"/home/{username}",
},
}
def worker_profile(options, user):
namespace, name = options.conda_environment.split("/")
return functools.reduce(
deep_merge,
[
base_node_group(),
base_conda_store_mounts(namespace, name),
base_username_mount(user.name),
config["profiles"][options.profile],
{"environment": {**options.environment_vars}},
],
{},
)
def user_options(user):
allowed_namespaces = set(["filesystem", "default", user.name] + list(user.groups))
environments = {
f"{namespace}/{name}": conda_prefix
for namespace, name, conda_prefix in list_dask_environments(
config["conda-store-mount"]
)
if namespace in allowed_namespaces
}
args = []
if environments:
args += [
Select(
"conda_environment",
list(environments.keys()),
default=list(environments.keys())[0],
label="Environment",
)
]
if config["profiles"]:
args += [
Select(
"profile",
list(config["profiles"].keys()),
default=list(config["profiles"].keys())[0],
label="Cluster Profile",
)
]
args += [
Mapping("environment_vars", {}, label="Environment Variables"),
]
return Options(
*args,
handler=worker_profile,
)
c.Backend.cluster_options = user_options
# ============== utils ============
def deep_merge(d1, d2):
"""Deep merge two dictionaries.
>>> value_1 = {
'a': [1, 2],
'b': {'c': 1, 'z': [5, 6]},
'e': {'f': {'g': {}}},
'm': 1,
}
>>> value_2 = {
'a': [3, 4],
'b': {'d': 2, 'z': [7]},
'e': {'f': {'h': 1}},
'm': [1],
}
>>> print(deep_merge(value_1, value_2))
{'m': 1, 'e': {'f': {'g': {}, 'h': 1}}, 'b': {'d': 2, 'c': 1, 'z': [5, 6, 7]}, 'a': [1, 2, 3, 4]}
"""
if isinstance(d1, dict) and isinstance(d2, dict):
d3 = {}
for key in d1.keys() | d2.keys():
if key in d1 and key in d2:
d3[key] = deep_merge(d1[key], d2[key])
elif key in d1:
d3[key] = d1[key]
elif key in d2:
d3[key] = d2[key]
return d3
elif isinstance(d1, list) and isinstance(d2, list):
return [*d1, *d2]
else: # if they don't match use left one
return d1
| nebari-dev__nebari |
30 | 30-94-20 | random | endswith | [
"capitalize",
"casefold",
"center",
"count",
"encode",
"endswith",
"expandtabs",
"find",
"format",
"format_map",
"index",
"isalnum",
"isalpha",
"isascii",
"isdecimal",
"isdigit",
"isidentifier",
"islower",
"isnumeric",
"isprintable",
"isspace",
"istitle",
"isupper",
"join",
"ljust",
"lower",
"lstrip",
"maketrans",
"partition",
"removeprefix",
"removesuffix",
"replace",
"rfind",
"rindex",
"rjust",
"rpartition",
"rsplit",
"rstrip",
"split",
"splitlines",
"startswith",
"strip",
"swapcase",
"title",
"translate",
"upper",
"zfill",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__getitem__",
"__getnewargs__",
"__gt__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__le__",
"__len__",
"__lt__",
"__mod__",
"__module__",
"__mul__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rmul__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import os
import json
import functools
from aiohttp import web
from dask_gateway_server.options import Options, Select, Mapping
from dask_gateway_server.auth import JupyterHubAuthenticator
def dask_gateway_config(path="/var/lib/dask-gateway/config.json"):
with open(path) as f:
return json.load(f)
config = dask_gateway_config()
c.DaskGateway.log_level = config["gateway"]["loglevel"]
# Configure addresses
c.DaskGateway.address = ":8000"
c.KubeBackend.api_url = f'http://{config["gateway_service_name"]}.{config["gateway_service_namespace"]}:8000/api'
c.DaskGateway.backend_class = "dask_gateway_server.backends.kubernetes.KubeBackend"
c.KubeBackend.gateway_instance = config["gateway_service_name"]
# ========= Dask Cluster Default Configuration =========
c.KubeClusterConfig.image = (
f"{config['cluster-image']['name']}:{config['cluster-image']['tag']}"
)
c.KubeClusterConfig.image_pull_policy = config["cluster"]["image_pull_policy"]
c.KubeClusterConfig.environment = config["cluster"]["environment"]
c.KubeClusterConfig.scheduler_cores = config["cluster"]["scheduler_cores"]
c.KubeClusterConfig.scheduler_cores_limit = config["cluster"]["scheduler_cores_limit"]
c.KubeClusterConfig.scheduler_memory = config["cluster"]["scheduler_memory"]
c.KubeClusterConfig.scheduler_memory_limit = config["cluster"]["scheduler_memory_limit"]
c.KubeClusterConfig.scheduler_extra_container_config = config["cluster"][
"scheduler_extra_container_config"
]
c.KubeClusterConfig.scheduler_extra_pod_config = config["cluster"][
"scheduler_extra_pod_config"
]
c.KubeClusterConfig.worker_cores = config["cluster"]["worker_cores"]
c.KubeClusterConfig.worker_cores_limit = config["cluster"]["worker_cores_limit"]
c.KubeClusterConfig.worker_memory = config["cluster"]["worker_memory"]
c.KubeClusterConfig.worker_memory_limit = config["cluster"]["worker_memory_limit"]
c.KubeClusterConfig.worker_extra_container_config = config["cluster"][
"worker_extra_container_config"
]
c.KubeClusterConfig.worker_extra_pod_config = config["cluster"][
"worker_extra_pod_config"
]
# ============ Authentication =================
class QHubAuthentication(JupyterHubAuthenticator):
async def authenticate(self, request):
user = await super().authenticate(request)
url = f"{self.jupyterhub_api_url}/users/{user.name}"
kwargs = {
"headers": {"Authorization": "token %s" % self.jupyterhub_api_token},
"ssl": self.ssl_context,
}
resp = await self.session.get(url, **kwargs)
data = (await resp.json())["auth_state"]["oauth_user"]
if (
"dask_gateway_developer" not in data["roles"]
and "dask_gateway_admin" not in data["roles"]
):
raise web.HTTPInternalServerError(
reason="Permission failure user does not have required dask_gateway roles"
)
user.admin = "dask_gateway_admin" in data["roles"]
user.groups = [
os.path.basename(group)
for group in data["groups"]
if os.path.dirname(group) == "/projects"
]
return user
c.DaskGateway.authenticator_class = QHubAuthentication
c.JupyterHubAuthenticator.jupyterhub_api_url = config["jupyterhub_api_url"]
c.JupyterHubAuthenticator.jupyterhub_api_token = config["jupyterhub_api_token"]
# ==================== Profiles =======================
def get_packages(conda_prefix):
packages = set()
for filename in os.listdir(os.path.join(conda_prefix, "conda-meta")):
if filename. | (".json"):
with open(os.path.join(conda_prefix, "conda-meta", filename)) as f:
packages.add(json.load(f).get("name"))
return packages
def get_conda_prefixes(conda_store_mount):
for namespace in os.listdir(conda_store_mount):
if os.path.isdir(os.path.join(conda_store_mount, namespace, "envs")):
for name in os.listdir(os.path.join(conda_store_mount, namespace, "envs")):
yield namespace, name, os.path.join(
conda_store_mount, namespace, "envs", name
)
def list_dask_environments(conda_store_mount):
for namespace, name, conda_prefix in get_conda_prefixes(conda_store_mount):
if {"dask", "distributed"} <= get_packages(conda_prefix):
yield namespace, name, conda_prefix
def base_node_group():
worker_node_group = {
config["worker-node-group"]["key"]: config["worker-node-group"]["value"]
}
return {
"scheduler_extra_pod_config": {"nodeSelector": worker_node_group},
"worker_extra_pod_config": {"nodeSelector": worker_node_group},
}
def base_conda_store_mounts(namespace, name):
conda_store_pvc_name = config["conda-store-pvc"]
conda_store_mount = config["conda-store-mount"]
return {
"scheduler_extra_pod_config": {
"volumes": [
{
"name": "conda-store",
"persistentVolumeClaim": {
"claimName": conda_store_pvc_name,
},
}
]
},
"scheduler_extra_container_config": {
"volumeMounts": [
{
"mountPath": os.path.join(conda_store_mount, namespace),
"name": "conda-store",
"subPath": namespace,
}
]
},
"worker_extra_pod_config": {
"volumes": [
{
"name": "conda-store",
"persistentVolumeClaim": {
"claimName": conda_store_pvc_name,
},
}
]
},
"worker_extra_container_config": {
"volumeMounts": [
{
"mountPath": os.path.join(conda_store_mount, namespace),
"name": "conda-store",
"subPath": namespace,
}
]
},
"worker_cmd": "/opt/conda-run-worker",
"scheduler_cmd": "/opt/conda-run-scheduler",
"environment": {
"CONDA_ENVIRONMENT": os.path.join(
conda_store_mount, namespace, "envs", name
),
},
}
def base_username_mount(username, uid=1000, gid=100):
return {
"scheduler_extra_pod_config": {"volumes": [{"name": "home", "emptyDir": {}}]},
"scheduler_extra_container_config": {
"securityContext": {"runAsUser": uid, "runAsGroup": gid, "fsGroup": gid},
"workingDir": f"/home/{username}",
"volumeMounts": [
{
"mountPath": f"/home/{username}",
"name": "home",
}
],
},
"worker_extra_pod_config": {"volumes": [{"name": "home", "emptyDir": {}}]},
"worker_extra_container_config": {
"securityContext": {"runAsUser": uid, "runAsGroup": gid, "fsGroup": gid},
"workingDir": f"/home/{username}",
"volumeMounts": [
{
"mountPath": f"/home/{username}",
"name": "home",
}
],
},
"environment": {
"HOME": f"/home/{username}",
},
}
def worker_profile(options, user):
namespace, name = options.conda_environment.split("/")
return functools.reduce(
deep_merge,
[
base_node_group(),
base_conda_store_mounts(namespace, name),
base_username_mount(user.name),
config["profiles"][options.profile],
{"environment": {**options.environment_vars}},
],
{},
)
def user_options(user):
allowed_namespaces = set(["filesystem", "default", user.name] + list(user.groups))
environments = {
f"{namespace}/{name}": conda_prefix
for namespace, name, conda_prefix in list_dask_environments(
config["conda-store-mount"]
)
if namespace in allowed_namespaces
}
args = []
if environments:
args += [
Select(
"conda_environment",
list(environments.keys()),
default=list(environments.keys())[0],
label="Environment",
)
]
if config["profiles"]:
args += [
Select(
"profile",
list(config["profiles"].keys()),
default=list(config["profiles"].keys())[0],
label="Cluster Profile",
)
]
args += [
Mapping("environment_vars", {}, label="Environment Variables"),
]
return Options(
*args,
handler=worker_profile,
)
c.Backend.cluster_options = user_options
# ============== utils ============
def deep_merge(d1, d2):
"""Deep merge two dictionaries.
>>> value_1 = {
'a': [1, 2],
'b': {'c': 1, 'z': [5, 6]},
'e': {'f': {'g': {}}},
'm': 1,
}
>>> value_2 = {
'a': [3, 4],
'b': {'d': 2, 'z': [7]},
'e': {'f': {'h': 1}},
'm': [1],
}
>>> print(deep_merge(value_1, value_2))
{'m': 1, 'e': {'f': {'g': {}, 'h': 1}}, 'b': {'d': 2, 'c': 1, 'z': [5, 6, 7]}, 'a': [1, 2, 3, 4]}
"""
if isinstance(d1, dict) and isinstance(d2, dict):
d3 = {}
for key in d1.keys() | d2.keys():
if key in d1 and key in d2:
d3[key] = deep_merge(d1[key], d2[key])
elif key in d1:
d3[key] = d1[key]
elif key in d2:
d3[key] = d2[key]
return d3
elif isinstance(d1, list) and isinstance(d2, list):
return [*d1, *d2]
else: # if they don't match use left one
return d1
| nebari-dev__nebari |
30 | 30-96-25 | common | add | [
"add",
"clear",
"copy",
"difference",
"difference_update",
"discard",
"intersection",
"intersection_update",
"isdisjoint",
"issubset",
"issuperset",
"pop",
"remove",
"symmetric_difference",
"symmetric_difference_update",
"union",
"update",
"__and__",
"__annotations__",
"__class__",
"__class_getitem__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__gt__",
"__hash__",
"__iand__",
"__init__",
"__init_subclass__",
"__ior__",
"__isub__",
"__iter__",
"__ixor__",
"__le__",
"__len__",
"__lt__",
"__module__",
"__ne__",
"__new__",
"__or__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__",
"__sub__",
"__xor__"
] | import os
import json
import functools
from aiohttp import web
from dask_gateway_server.options import Options, Select, Mapping
from dask_gateway_server.auth import JupyterHubAuthenticator
def dask_gateway_config(path="/var/lib/dask-gateway/config.json"):
with open(path) as f:
return json.load(f)
config = dask_gateway_config()
c.DaskGateway.log_level = config["gateway"]["loglevel"]
# Configure addresses
c.DaskGateway.address = ":8000"
c.KubeBackend.api_url = f'http://{config["gateway_service_name"]}.{config["gateway_service_namespace"]}:8000/api'
c.DaskGateway.backend_class = "dask_gateway_server.backends.kubernetes.KubeBackend"
c.KubeBackend.gateway_instance = config["gateway_service_name"]
# ========= Dask Cluster Default Configuration =========
c.KubeClusterConfig.image = (
f"{config['cluster-image']['name']}:{config['cluster-image']['tag']}"
)
c.KubeClusterConfig.image_pull_policy = config["cluster"]["image_pull_policy"]
c.KubeClusterConfig.environment = config["cluster"]["environment"]
c.KubeClusterConfig.scheduler_cores = config["cluster"]["scheduler_cores"]
c.KubeClusterConfig.scheduler_cores_limit = config["cluster"]["scheduler_cores_limit"]
c.KubeClusterConfig.scheduler_memory = config["cluster"]["scheduler_memory"]
c.KubeClusterConfig.scheduler_memory_limit = config["cluster"]["scheduler_memory_limit"]
c.KubeClusterConfig.scheduler_extra_container_config = config["cluster"][
"scheduler_extra_container_config"
]
c.KubeClusterConfig.scheduler_extra_pod_config = config["cluster"][
"scheduler_extra_pod_config"
]
c.KubeClusterConfig.worker_cores = config["cluster"]["worker_cores"]
c.KubeClusterConfig.worker_cores_limit = config["cluster"]["worker_cores_limit"]
c.KubeClusterConfig.worker_memory = config["cluster"]["worker_memory"]
c.KubeClusterConfig.worker_memory_limit = config["cluster"]["worker_memory_limit"]
c.KubeClusterConfig.worker_extra_container_config = config["cluster"][
"worker_extra_container_config"
]
c.KubeClusterConfig.worker_extra_pod_config = config["cluster"][
"worker_extra_pod_config"
]
# ============ Authentication =================
class QHubAuthentication(JupyterHubAuthenticator):
async def authenticate(self, request):
user = await super().authenticate(request)
url = f"{self.jupyterhub_api_url}/users/{user.name}"
kwargs = {
"headers": {"Authorization": "token %s" % self.jupyterhub_api_token},
"ssl": self.ssl_context,
}
resp = await self.session.get(url, **kwargs)
data = (await resp.json())["auth_state"]["oauth_user"]
if (
"dask_gateway_developer" not in data["roles"]
and "dask_gateway_admin" not in data["roles"]
):
raise web.HTTPInternalServerError(
reason="Permission failure user does not have required dask_gateway roles"
)
user.admin = "dask_gateway_admin" in data["roles"]
user.groups = [
os.path.basename(group)
for group in data["groups"]
if os.path.dirname(group) == "/projects"
]
return user
c.DaskGateway.authenticator_class = QHubAuthentication
c.JupyterHubAuthenticator.jupyterhub_api_url = config["jupyterhub_api_url"]
c.JupyterHubAuthenticator.jupyterhub_api_token = config["jupyterhub_api_token"]
# ==================== Profiles =======================
def get_packages(conda_prefix):
packages = set()
for filename in os.listdir(os.path.join(conda_prefix, "conda-meta")):
if filename.endswith(".json"):
with open(os.path.join(conda_prefix, "conda-meta", filename)) as f:
packages. | (json.load(f).get("name"))
return packages
def get_conda_prefixes(conda_store_mount):
for namespace in os.listdir(conda_store_mount):
if os.path.isdir(os.path.join(conda_store_mount, namespace, "envs")):
for name in os.listdir(os.path.join(conda_store_mount, namespace, "envs")):
yield namespace, name, os.path.join(
conda_store_mount, namespace, "envs", name
)
def list_dask_environments(conda_store_mount):
for namespace, name, conda_prefix in get_conda_prefixes(conda_store_mount):
if {"dask", "distributed"} <= get_packages(conda_prefix):
yield namespace, name, conda_prefix
def base_node_group():
worker_node_group = {
config["worker-node-group"]["key"]: config["worker-node-group"]["value"]
}
return {
"scheduler_extra_pod_config": {"nodeSelector": worker_node_group},
"worker_extra_pod_config": {"nodeSelector": worker_node_group},
}
def base_conda_store_mounts(namespace, name):
conda_store_pvc_name = config["conda-store-pvc"]
conda_store_mount = config["conda-store-mount"]
return {
"scheduler_extra_pod_config": {
"volumes": [
{
"name": "conda-store",
"persistentVolumeClaim": {
"claimName": conda_store_pvc_name,
},
}
]
},
"scheduler_extra_container_config": {
"volumeMounts": [
{
"mountPath": os.path.join(conda_store_mount, namespace),
"name": "conda-store",
"subPath": namespace,
}
]
},
"worker_extra_pod_config": {
"volumes": [
{
"name": "conda-store",
"persistentVolumeClaim": {
"claimName": conda_store_pvc_name,
},
}
]
},
"worker_extra_container_config": {
"volumeMounts": [
{
"mountPath": os.path.join(conda_store_mount, namespace),
"name": "conda-store",
"subPath": namespace,
}
]
},
"worker_cmd": "/opt/conda-run-worker",
"scheduler_cmd": "/opt/conda-run-scheduler",
"environment": {
"CONDA_ENVIRONMENT": os.path.join(
conda_store_mount, namespace, "envs", name
),
},
}
def base_username_mount(username, uid=1000, gid=100):
return {
"scheduler_extra_pod_config": {"volumes": [{"name": "home", "emptyDir": {}}]},
"scheduler_extra_container_config": {
"securityContext": {"runAsUser": uid, "runAsGroup": gid, "fsGroup": gid},
"workingDir": f"/home/{username}",
"volumeMounts": [
{
"mountPath": f"/home/{username}",
"name": "home",
}
],
},
"worker_extra_pod_config": {"volumes": [{"name": "home", "emptyDir": {}}]},
"worker_extra_container_config": {
"securityContext": {"runAsUser": uid, "runAsGroup": gid, "fsGroup": gid},
"workingDir": f"/home/{username}",
"volumeMounts": [
{
"mountPath": f"/home/{username}",
"name": "home",
}
],
},
"environment": {
"HOME": f"/home/{username}",
},
}
def worker_profile(options, user):
namespace, name = options.conda_environment.split("/")
return functools.reduce(
deep_merge,
[
base_node_group(),
base_conda_store_mounts(namespace, name),
base_username_mount(user.name),
config["profiles"][options.profile],
{"environment": {**options.environment_vars}},
],
{},
)
def user_options(user):
allowed_namespaces = set(["filesystem", "default", user.name] + list(user.groups))
environments = {
f"{namespace}/{name}": conda_prefix
for namespace, name, conda_prefix in list_dask_environments(
config["conda-store-mount"]
)
if namespace in allowed_namespaces
}
args = []
if environments:
args += [
Select(
"conda_environment",
list(environments.keys()),
default=list(environments.keys())[0],
label="Environment",
)
]
if config["profiles"]:
args += [
Select(
"profile",
list(config["profiles"].keys()),
default=list(config["profiles"].keys())[0],
label="Cluster Profile",
)
]
args += [
Mapping("environment_vars", {}, label="Environment Variables"),
]
return Options(
*args,
handler=worker_profile,
)
c.Backend.cluster_options = user_options
# ============== utils ============
def deep_merge(d1, d2):
"""Deep merge two dictionaries.
>>> value_1 = {
'a': [1, 2],
'b': {'c': 1, 'z': [5, 6]},
'e': {'f': {'g': {}}},
'm': 1,
}
>>> value_2 = {
'a': [3, 4],
'b': {'d': 2, 'z': [7]},
'e': {'f': {'h': 1}},
'm': [1],
}
>>> print(deep_merge(value_1, value_2))
{'m': 1, 'e': {'f': {'g': {}, 'h': 1}}, 'b': {'d': 2, 'c': 1, 'z': [5, 6, 7]}, 'a': [1, 2, 3, 4]}
"""
if isinstance(d1, dict) and isinstance(d2, dict):
d3 = {}
for key in d1.keys() | d2.keys():
if key in d1 and key in d2:
d3[key] = deep_merge(d1[key], d2[key])
elif key in d1:
d3[key] = d1[key]
elif key in d2:
d3[key] = d2[key]
return d3
elif isinstance(d1, list) and isinstance(d2, list):
return [*d1, *d2]
else: # if they don't match use left one
return d1
| nebari-dev__nebari |
30 | 30-96-34 | common | load | [
"codecs",
"decoder",
"detect_encoding",
"dump",
"dumps",
"encoder",
"JSONDecodeError",
"JSONDecoder",
"JSONEncoder",
"load",
"loads",
"scanner",
"tool",
"_default_decoder",
"_default_encoder",
"__all__",
"__author__",
"__doc__",
"__file__",
"__name__",
"__package__",
"__version__"
] | import os
import json
import functools
from aiohttp import web
from dask_gateway_server.options import Options, Select, Mapping
from dask_gateway_server.auth import JupyterHubAuthenticator
def dask_gateway_config(path="/var/lib/dask-gateway/config.json"):
with open(path) as f:
return json.load(f)
config = dask_gateway_config()
c.DaskGateway.log_level = config["gateway"]["loglevel"]
# Configure addresses
c.DaskGateway.address = ":8000"
c.KubeBackend.api_url = f'http://{config["gateway_service_name"]}.{config["gateway_service_namespace"]}:8000/api'
c.DaskGateway.backend_class = "dask_gateway_server.backends.kubernetes.KubeBackend"
c.KubeBackend.gateway_instance = config["gateway_service_name"]
# ========= Dask Cluster Default Configuration =========
c.KubeClusterConfig.image = (
f"{config['cluster-image']['name']}:{config['cluster-image']['tag']}"
)
c.KubeClusterConfig.image_pull_policy = config["cluster"]["image_pull_policy"]
c.KubeClusterConfig.environment = config["cluster"]["environment"]
c.KubeClusterConfig.scheduler_cores = config["cluster"]["scheduler_cores"]
c.KubeClusterConfig.scheduler_cores_limit = config["cluster"]["scheduler_cores_limit"]
c.KubeClusterConfig.scheduler_memory = config["cluster"]["scheduler_memory"]
c.KubeClusterConfig.scheduler_memory_limit = config["cluster"]["scheduler_memory_limit"]
c.KubeClusterConfig.scheduler_extra_container_config = config["cluster"][
"scheduler_extra_container_config"
]
c.KubeClusterConfig.scheduler_extra_pod_config = config["cluster"][
"scheduler_extra_pod_config"
]
c.KubeClusterConfig.worker_cores = config["cluster"]["worker_cores"]
c.KubeClusterConfig.worker_cores_limit = config["cluster"]["worker_cores_limit"]
c.KubeClusterConfig.worker_memory = config["cluster"]["worker_memory"]
c.KubeClusterConfig.worker_memory_limit = config["cluster"]["worker_memory_limit"]
c.KubeClusterConfig.worker_extra_container_config = config["cluster"][
"worker_extra_container_config"
]
c.KubeClusterConfig.worker_extra_pod_config = config["cluster"][
"worker_extra_pod_config"
]
# ============ Authentication =================
class QHubAuthentication(JupyterHubAuthenticator):
async def authenticate(self, request):
user = await super().authenticate(request)
url = f"{self.jupyterhub_api_url}/users/{user.name}"
kwargs = {
"headers": {"Authorization": "token %s" % self.jupyterhub_api_token},
"ssl": self.ssl_context,
}
resp = await self.session.get(url, **kwargs)
data = (await resp.json())["auth_state"]["oauth_user"]
if (
"dask_gateway_developer" not in data["roles"]
and "dask_gateway_admin" not in data["roles"]
):
raise web.HTTPInternalServerError(
reason="Permission failure user does not have required dask_gateway roles"
)
user.admin = "dask_gateway_admin" in data["roles"]
user.groups = [
os.path.basename(group)
for group in data["groups"]
if os.path.dirname(group) == "/projects"
]
return user
c.DaskGateway.authenticator_class = QHubAuthentication
c.JupyterHubAuthenticator.jupyterhub_api_url = config["jupyterhub_api_url"]
c.JupyterHubAuthenticator.jupyterhub_api_token = config["jupyterhub_api_token"]
# ==================== Profiles =======================
def get_packages(conda_prefix):
packages = set()
for filename in os.listdir(os.path.join(conda_prefix, "conda-meta")):
if filename.endswith(".json"):
with open(os.path.join(conda_prefix, "conda-meta", filename)) as f:
packages.add(json. | (f).get("name"))
return packages
def get_conda_prefixes(conda_store_mount):
for namespace in os.listdir(conda_store_mount):
if os.path.isdir(os.path.join(conda_store_mount, namespace, "envs")):
for name in os.listdir(os.path.join(conda_store_mount, namespace, "envs")):
yield namespace, name, os.path.join(
conda_store_mount, namespace, "envs", name
)
def list_dask_environments(conda_store_mount):
for namespace, name, conda_prefix in get_conda_prefixes(conda_store_mount):
if {"dask", "distributed"} <= get_packages(conda_prefix):
yield namespace, name, conda_prefix
def base_node_group():
worker_node_group = {
config["worker-node-group"]["key"]: config["worker-node-group"]["value"]
}
return {
"scheduler_extra_pod_config": {"nodeSelector": worker_node_group},
"worker_extra_pod_config": {"nodeSelector": worker_node_group},
}
def base_conda_store_mounts(namespace, name):
conda_store_pvc_name = config["conda-store-pvc"]
conda_store_mount = config["conda-store-mount"]
return {
"scheduler_extra_pod_config": {
"volumes": [
{
"name": "conda-store",
"persistentVolumeClaim": {
"claimName": conda_store_pvc_name,
},
}
]
},
"scheduler_extra_container_config": {
"volumeMounts": [
{
"mountPath": os.path.join(conda_store_mount, namespace),
"name": "conda-store",
"subPath": namespace,
}
]
},
"worker_extra_pod_config": {
"volumes": [
{
"name": "conda-store",
"persistentVolumeClaim": {
"claimName": conda_store_pvc_name,
},
}
]
},
"worker_extra_container_config": {
"volumeMounts": [
{
"mountPath": os.path.join(conda_store_mount, namespace),
"name": "conda-store",
"subPath": namespace,
}
]
},
"worker_cmd": "/opt/conda-run-worker",
"scheduler_cmd": "/opt/conda-run-scheduler",
"environment": {
"CONDA_ENVIRONMENT": os.path.join(
conda_store_mount, namespace, "envs", name
),
},
}
def base_username_mount(username, uid=1000, gid=100):
return {
"scheduler_extra_pod_config": {"volumes": [{"name": "home", "emptyDir": {}}]},
"scheduler_extra_container_config": {
"securityContext": {"runAsUser": uid, "runAsGroup": gid, "fsGroup": gid},
"workingDir": f"/home/{username}",
"volumeMounts": [
{
"mountPath": f"/home/{username}",
"name": "home",
}
],
},
"worker_extra_pod_config": {"volumes": [{"name": "home", "emptyDir": {}}]},
"worker_extra_container_config": {
"securityContext": {"runAsUser": uid, "runAsGroup": gid, "fsGroup": gid},
"workingDir": f"/home/{username}",
"volumeMounts": [
{
"mountPath": f"/home/{username}",
"name": "home",
}
],
},
"environment": {
"HOME": f"/home/{username}",
},
}
def worker_profile(options, user):
namespace, name = options.conda_environment.split("/")
return functools.reduce(
deep_merge,
[
base_node_group(),
base_conda_store_mounts(namespace, name),
base_username_mount(user.name),
config["profiles"][options.profile],
{"environment": {**options.environment_vars}},
],
{},
)
def user_options(user):
allowed_namespaces = set(["filesystem", "default", user.name] + list(user.groups))
environments = {
f"{namespace}/{name}": conda_prefix
for namespace, name, conda_prefix in list_dask_environments(
config["conda-store-mount"]
)
if namespace in allowed_namespaces
}
args = []
if environments:
args += [
Select(
"conda_environment",
list(environments.keys()),
default=list(environments.keys())[0],
label="Environment",
)
]
if config["profiles"]:
args += [
Select(
"profile",
list(config["profiles"].keys()),
default=list(config["profiles"].keys())[0],
label="Cluster Profile",
)
]
args += [
Mapping("environment_vars", {}, label="Environment Variables"),
]
return Options(
*args,
handler=worker_profile,
)
c.Backend.cluster_options = user_options
# ============== utils ============
def deep_merge(d1, d2):
"""Deep merge two dictionaries.
>>> value_1 = {
'a': [1, 2],
'b': {'c': 1, 'z': [5, 6]},
'e': {'f': {'g': {}}},
'm': 1,
}
>>> value_2 = {
'a': [3, 4],
'b': {'d': 2, 'z': [7]},
'e': {'f': {'h': 1}},
'm': [1],
}
>>> print(deep_merge(value_1, value_2))
{'m': 1, 'e': {'f': {'g': {}, 'h': 1}}, 'b': {'d': 2, 'c': 1, 'z': [5, 6, 7]}, 'a': [1, 2, 3, 4]}
"""
if isinstance(d1, dict) and isinstance(d2, dict):
d3 = {}
for key in d1.keys() | d2.keys():
if key in d1 and key in d2:
d3[key] = deep_merge(d1[key], d2[key])
elif key in d1:
d3[key] = d1[key]
elif key in d2:
d3[key] = d2[key]
return d3
elif isinstance(d1, list) and isinstance(d2, list):
return [*d1, *d2]
else: # if they don't match use left one
return d1
| nebari-dev__nebari |
41 | 41-22-13 | infile | _load_source | [
"console",
"content",
"copy_report",
"execute_custom_assertions",
"name",
"refine_ydata_result",
"run",
"source_file",
"stage_file",
"stage_file_obj",
"tests",
"update_report",
"_load_source",
"_show_progress",
"_show_result",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self. | ()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path.join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-60-17 | infile | _show_progress | [
"console",
"content",
"copy_report",
"execute_custom_assertions",
"name",
"refine_ydata_result",
"run",
"source_file",
"stage_file",
"stage_file_obj",
"tests",
"update_report",
"_load_source",
"_show_progress",
"_show_result",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self. | ()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path.join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-62-34 | infile | copy_report | [
"console",
"content",
"copy_report",
"execute_custom_assertions",
"name",
"refine_ydata_result",
"run",
"source_file",
"stage_file",
"stage_file_obj",
"tests",
"update_report",
"_load_source",
"_show_progress",
"_show_result",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self. | (ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path.join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-65-17 | infile | execute_custom_assertions | [
"console",
"content",
"copy_report",
"execute_custom_assertions",
"name",
"refine_ydata_result",
"run",
"source_file",
"stage_file",
"stage_file_obj",
"tests",
"update_report",
"_load_source",
"_show_progress",
"_show_result",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self. | (ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path.join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-68-20 | inproject | DataFrame | [
"annotations",
"api",
"array",
"arrays",
"ArrowDtype",
"bdate_range",
"BooleanDtype",
"Categorical",
"CategoricalDtype",
"CategoricalIndex",
"compat",
"concat",
"conftest",
"core",
"crosstab",
"cut",
"DataFrame",
"date_range",
"DateOffset",
"DatetimeIndex",
"DatetimeTZDtype",
"describe_option",
"errors",
"eval",
"ExcelFile",
"ExcelWriter",
"factorize",
"Flags",
"Float32Dtype",
"Float64Dtype",
"from_dummies",
"get_dummies",
"get_option",
"Grouper",
"HDFStore",
"Index",
"IndexSlice",
"infer_freq",
"Int16Dtype",
"Int32Dtype",
"Int64Dtype",
"Int8Dtype",
"Interval",
"interval_range",
"IntervalDtype",
"IntervalIndex",
"io",
"isna",
"isnull",
"json_normalize",
"lreshape",
"melt",
"merge",
"merge_asof",
"merge_ordered",
"MultiIndex",
"NA",
"NamedAgg",
"NaT",
"notna",
"notnull",
"offsets",
"option_context",
"options",
"pandas",
"Period",
"period_range",
"PeriodDtype",
"PeriodIndex",
"pivot",
"pivot_table",
"plotting",
"qcut",
"RangeIndex",
"read_clipboard",
"read_csv",
"read_excel",
"read_feather",
"read_fwf",
"read_gbq",
"read_hdf",
"read_html",
"read_json",
"read_orc",
"read_parquet",
"read_pickle",
"read_sas",
"read_spss",
"read_sql",
"read_sql_query",
"read_sql_table",
"read_stata",
"read_table",
"read_xml",
"reset_option",
"Series",
"set_eng_float_format",
"set_option",
"show_versions",
"SparseDtype",
"StringDtype",
"test",
"testing",
"tests",
"Timedelta",
"timedelta_range",
"TimedeltaIndex",
"Timestamp",
"to_datetime",
"to_numeric",
"to_pickle",
"to_timedelta",
"tseries",
"UInt16Dtype",
"UInt32Dtype",
"UInt64Dtype",
"UInt8Dtype",
"unique",
"util",
"value_counts",
"wide_to_long",
"_built_with_meson",
"_config",
"_e",
"_err",
"_is_numpy_dev",
"_libs",
"_module",
"_testing",
"_typing",
"_version",
"_version_meson",
"__all__",
"__doc__",
"__docformat__",
"__file__",
"__git_version__",
"__name__",
"__package__",
"__version__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd. | (columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path.join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-71-26 | inproject | evaluate | [
"df",
"df_type",
"dtypes",
"evaluate",
"get_warnings",
"label",
"random_state",
"store_warning",
"tests",
"_clean_warnings",
"_coverage_fraction",
"_df",
"_df_type",
"_dtypes",
"_expectation_level_assessment",
"_label",
"_logger",
"_overall_assessment",
"_random_state",
"_report",
"_summarize_results",
"_tests",
"_warnings",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der. | (ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path.join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-91-31 | infile | refine_ydata_result | [
"console",
"content",
"copy_report",
"execute_custom_assertions",
"name",
"refine_ydata_result",
"run",
"source_file",
"stage_file",
"stage_file_obj",
"tests",
"update_report",
"_load_source",
"_show_progress",
"_show_result",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self. | (results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path.join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-94-17 | infile | _show_result | [
"console",
"content",
"copy_report",
"execute_custom_assertions",
"name",
"refine_ydata_result",
"run",
"source_file",
"stage_file",
"stage_file_obj",
"tests",
"update_report",
"_load_source",
"_show_progress",
"_show_result",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self. | ()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path.join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-99-17 | infile | _show_result | [
"console",
"content",
"copy_report",
"execute_custom_assertions",
"name",
"refine_ydata_result",
"run",
"source_file",
"stage_file",
"stage_file_obj",
"tests",
"update_report",
"_load_source",
"_show_progress",
"_show_result",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self. | (e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path.join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-103-35 | random | path | [
"abc",
"abort",
"access",
"add_dll_directory",
"altsep",
"chdir",
"chflags",
"chmod",
"chown",
"chroot",
"CLD_CONTINUED",
"CLD_DUMPED",
"CLD_EXITED",
"CLD_TRAPPED",
"close",
"closerange",
"confstr",
"confstr_names",
"cpu_count",
"ctermid",
"curdir",
"defpath",
"device_encoding",
"devnull",
"DirEntry",
"dup",
"dup2",
"environ",
"environb",
"error",
"EX_CANTCREAT",
"EX_CONFIG",
"EX_DATAERR",
"EX_IOERR",
"EX_NOHOST",
"EX_NOINPUT",
"EX_NOPERM",
"EX_NOTFOUND",
"EX_NOUSER",
"EX_OK",
"EX_OSERR",
"EX_OSFILE",
"EX_PROTOCOL",
"EX_SOFTWARE",
"EX_TEMPFAIL",
"EX_UNAVAILABLE",
"EX_USAGE",
"execl",
"execle",
"execlp",
"execlpe",
"execv",
"execve",
"execvp",
"execvpe",
"extsep",
"F_LOCK",
"F_OK",
"F_TEST",
"F_TLOCK",
"F_ULOCK",
"fchdir",
"fchmod",
"fchown",
"fdatasync",
"fdopen",
"fork",
"forkpty",
"fpathconf",
"fsdecode",
"fsencode",
"fspath",
"fstat",
"fstatvfs",
"fsync",
"ftruncate",
"fwalk",
"GenericAlias",
"get_blocking",
"get_exec_path",
"get_inheritable",
"get_terminal_size",
"getcwd",
"getcwdb",
"getegid",
"getenv",
"getenvb",
"geteuid",
"getgid",
"getgrouplist",
"getgroups",
"getloadavg",
"getlogin",
"getpgid",
"getpgrp",
"getpid",
"getppid",
"getpriority",
"getrandom",
"getresgid",
"getresuid",
"getsid",
"getuid",
"getxattr",
"GRND_NONBLOCK",
"GRND_RANDOM",
"initgroups",
"isatty",
"kill",
"killpg",
"lchflags",
"lchmod",
"lchown",
"linesep",
"link",
"listdir",
"listxattr",
"lockf",
"lseek",
"lstat",
"major",
"makedev",
"makedirs",
"Mapping",
"memfd_create",
"MFD_ALLOW_SEALING",
"MFD_CLOEXEC",
"MFD_HUGE_16GB",
"MFD_HUGE_16MB",
"MFD_HUGE_1GB",
"MFD_HUGE_1MB",
"MFD_HUGE_256MB",
"MFD_HUGE_2GB",
"MFD_HUGE_2MB",
"MFD_HUGE_32MB",
"MFD_HUGE_512KB",
"MFD_HUGE_512MB",
"MFD_HUGE_64KB",
"MFD_HUGE_8MB",
"MFD_HUGE_MASK",
"MFD_HUGE_SHIFT",
"MFD_HUGETLB",
"minor",
"mkdir",
"mkfifo",
"mknod",
"MutableMapping",
"name",
"NGROUPS_MAX",
"nice",
"O_ACCMODE",
"O_APPEND",
"O_ASYNC",
"O_BINARY",
"O_CLOEXEC",
"O_CREAT",
"O_DIRECT",
"O_DIRECTORY",
"O_DSYNC",
"O_EXCL",
"O_EXLOCK",
"O_LARGEFILE",
"O_NDELAY",
"O_NOATIME",
"O_NOCTTY",
"O_NOFOLLOW",
"O_NOINHERIT",
"O_NONBLOCK",
"O_PATH",
"O_RANDOM",
"O_RDONLY",
"O_RDWR",
"O_RSYNC",
"O_SEQUENTIAL",
"O_SHLOCK",
"O_SHORT_LIVED",
"O_SYNC",
"O_TEMPORARY",
"O_TEXT",
"O_TMPFILE",
"O_TRUNC",
"O_WRONLY",
"open",
"openpty",
"P_ALL",
"P_DETACH",
"P_NOWAIT",
"P_NOWAITO",
"P_OVERLAY",
"P_PGID",
"P_PID",
"P_WAIT",
"pardir",
"path",
"pathconf",
"pathconf_names",
"PathLike",
"pathsep",
"pipe",
"pipe2",
"plock",
"popen",
"POSIX_FADV_DONTNEED",
"POSIX_FADV_NOREUSE",
"POSIX_FADV_NORMAL",
"POSIX_FADV_RANDOM",
"POSIX_FADV_SEQUENTIAL",
"POSIX_FADV_WILLNEED",
"posix_fadvise",
"posix_fallocate",
"pread",
"PRIO_PGRP",
"PRIO_PROCESS",
"PRIO_USER",
"putenv",
"pwrite",
"R_OK",
"read",
"readlink",
"readv",
"register_at_fork",
"remove",
"removedirs",
"removexattr",
"rename",
"renames",
"replace",
"rmdir",
"RTLD_DEEPBIND",
"RTLD_GLOBAL",
"RTLD_LAZY",
"RTLD_LOCAL",
"RTLD_NODELETE",
"RTLD_NOLOAD",
"RTLD_NOW",
"scandir",
"SCHED_BATCH",
"SCHED_FIFO",
"sched_get_priority_max",
"sched_get_priority_min",
"sched_getaffinity",
"sched_getparam",
"sched_getscheduler",
"SCHED_IDLE",
"SCHED_OTHER",
"sched_param",
"SCHED_RESET_ON_FORK",
"SCHED_RR",
"sched_rr_get_interval",
"sched_setaffinity",
"sched_setparam",
"sched_setscheduler",
"SCHED_SPORADIC",
"sched_yield",
"SEEK_CUR",
"SEEK_DATA",
"SEEK_END",
"SEEK_HOLE",
"SEEK_SET",
"sendfile",
"sep",
"set_blocking",
"set_inheritable",
"setegid",
"seteuid",
"setgid",
"setgroups",
"setpgid",
"setpgrp",
"setpriority",
"setregid",
"setresgid",
"setresuid",
"setreuid",
"setsid",
"setuid",
"setxattr",
"SF_MNOWAIT",
"SF_NODISKIO",
"SF_SYNC",
"spawnl",
"spawnle",
"spawnlp",
"spawnlpe",
"spawnv",
"spawnve",
"spawnvp",
"spawnvpe",
"st",
"ST_APPEND",
"ST_MANDLOCK",
"ST_NOATIME",
"ST_NODEV",
"ST_NODIRATIME",
"ST_NOEXEC",
"ST_NOSUID",
"ST_RDONLY",
"ST_RELATIME",
"ST_SYNCHRONOUS",
"ST_WRITE",
"startfile",
"stat",
"stat_result",
"statvfs",
"statvfs_result",
"strerror",
"supports_bytes_environ",
"supports_dir_fd",
"supports_effective_ids",
"supports_fd",
"supports_follow_symlinks",
"symlink",
"sync",
"sys",
"sysconf",
"sysconf_names",
"system",
"tcgetpgrp",
"tcsetpgrp",
"terminal_size",
"times",
"times_result",
"TMP_MAX",
"truncate",
"ttyname",
"umask",
"uname",
"uname_result",
"unlink",
"unsetenv",
"urandom",
"utime",
"W_OK",
"wait",
"wait3",
"wait4",
"waitid",
"waitid_result",
"waitpid",
"walk",
"WCONTINUED",
"WCOREDUMP",
"WEXITED",
"WEXITSTATUS",
"WIFCONTINUED",
"WIFEXITED",
"WIFSIGNALED",
"WIFSTOPPED",
"WNOHANG",
"WNOWAIT",
"write",
"writev",
"WSTOPPED",
"WSTOPSIG",
"WTERMSIG",
"WUNTRACED",
"X_OK",
"XATTR_CREATE",
"XATTR_REPLACE",
"XATTR_SIZE_MAX",
"_AddedDllDirectory",
"_check_methods",
"_Environ",
"_execvpe",
"_exists",
"_exit",
"_fspath",
"_fwalk",
"_get_exports_list",
"_spawnvef",
"_walk",
"_wrap_close",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os. | .join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-103-40 | random | join | [
"abspath",
"altsep",
"basename",
"commonpath",
"commonprefix",
"curdir",
"defpath",
"devnull",
"dirname",
"exists",
"expanduser",
"expandvars",
"extsep",
"genericpath",
"getatime",
"getctime",
"getmtime",
"getsize",
"isabs",
"isdir",
"isfile",
"islink",
"ismount",
"join",
"lexists",
"normcase",
"normpath",
"os",
"pardir",
"pathsep",
"realpath",
"relpath",
"samefile",
"sameopenfile",
"samestat",
"sep",
"split",
"splitdrive",
"splitext",
"stat",
"supports_unicode_filenames",
"sys",
"_abspath_fallback",
"_get_bothseps",
"_get_sep",
"_getfinalpathname",
"_getfinalpathname_nonstrict",
"_getfullpathname",
"_getvolumepathname",
"_joinrealpath",
"_LCMAP_LOWERCASE",
"_LCMapStringEx",
"_LOCALE_NAME_INVARIANT",
"_nt_readlink",
"_readlink_deep",
"_varprog",
"_varprogb",
"__all__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path. | (ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-117-36 | random | items | [
"clear",
"copy",
"fromkeys",
"get",
"items",
"keys",
"pop",
"popitem",
"setdefault",
"update",
"values",
"__annotations__",
"__class__",
"__class_getitem__",
"__contains__",
"__delattr__",
"__delitem__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__getitem__",
"__hash__",
"__init__",
"__init_subclass__",
"__ior__",
"__iter__",
"__len__",
"__module__",
"__ne__",
"__new__",
"__or__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__setattr__",
"__setitem__",
"__sizeof__",
"__slots__",
"__str__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path.join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests. | ():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-120-34 | inproject | execute_and_remove_from_queue | [
"assertion",
"dataframe_from_source",
"execute_and_remove_from_queue",
"function_name",
"key",
"stage_file",
"stage_name",
"test_definition",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path.join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v. | (ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-122-25 | infile | update_report | [
"console",
"content",
"copy_report",
"execute_custom_assertions",
"name",
"refine_ydata_result",
"run",
"source_file",
"stage_file",
"stage_file_obj",
"tests",
"update_report",
"_load_source",
"_show_progress",
"_show_result",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path.join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self. | (report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-126-29 | infile | update_report | [
"console",
"content",
"copy_report",
"execute_custom_assertions",
"name",
"refine_ydata_result",
"run",
"source_file",
"stage_file",
"stage_file_obj",
"tests",
"update_report",
"_load_source",
"_show_progress",
"_show_result",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path.join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self. | (report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-128-29 | infile | update_report | [
"console",
"content",
"copy_report",
"execute_custom_assertions",
"name",
"refine_ydata_result",
"run",
"source_file",
"stage_file",
"stage_file_obj",
"tests",
"update_report",
"_load_source",
"_show_progress",
"_show_result",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path.join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self. | (report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-204-13 | inproject | stage_content | [
"filename",
"get",
"stage_content",
"stage_file",
"stages",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path.join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self. | : dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-209-38 | infile | stage_content | [
"filename",
"get",
"stage_content",
"stage_file",
"stages",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path.join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self. | [k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self.stage_content[name])
| infuseai__piperider |
41 | 41-213-42 | infile | stage_content | [
"filename",
"get",
"stage_content",
"stage_file",
"stages",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import json
import os
import shutil
from glob import glob
from time import time
import click
import pandas as pd
from rich.console import Console
from rich.markdown import Markdown
class Stage(object):
def __init__(self, stage_file, name, content):
self.stage_file_obj = stage_file
self.stage_file = stage_file.stage_file
self.name = name
self.content = content
self.source_file = None
self.console = Console()
self._load_source()
def _show_progress(self):
self.console.rule(f'[bold green][Process stage] {os.path.basename(self.stage_file).split(".")[0]}:{self.name}',
align='left')
def _show_result(self, error=None):
stage_name = f'{os.path.basename(self.stage_file).split(".")[0]}:{self.name}'
if error is not None:
click.echo(f'Skipped stage [{stage_name}] Error: {error}')
self.console.rule(f'[bold red][Failed] {stage_name}', align='left')
else:
self.console.rule(f'[bold green][Pass] {stage_name}', align='left')
def _load_source(self):
if 'data' not in self.content:
raise ValueError('data is required field')
source_name = self.content['data']
self.source_file = os.path.abspath(
os.path.join(os.path.dirname(self.stage_file), '../sources', f'{source_name}.yaml'))
def tests(self):
return self.content['tests']
def run(self, keep_ge_workspace=False):
from piperider_cli.data import execute_ge_checkpoint
from piperider_cli.ydata.data_expectations import DataExpectationsReporter
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp_dir:
ge_workspace = tmp_dir
if keep_ge_workspace:
ge_workspace = os.path.join(os.getcwd(), f'ge_dir_{int(time())}')
click.echo(f'Keep ge workspace at {ge_workspace}')
try:
self._show_progress()
all_columns, ge_context = execute_ge_checkpoint(ge_workspace, self)
ge_report_file = self.copy_report(ge_workspace)
ydata_report_file = ge_report_file.replace('.json', '_ydata.json')
self.execute_custom_assertions(ge_context, ge_report_file)
# generate ydata report
df = pd.DataFrame(columns=all_columns)
datasource_name = self.source_file.split('/')[-1]
der = DataExpectationsReporter()
results = der.evaluate(ge_report_file, df)
expectations_report, expectations_dense = results['Expectation Level Assessment']
markdown_template = f'''
# Status
* Data Source : {datasource_name}
* Data Columns : {all_columns}
* Output Reports
* Test report: {ge_report_file}
* Ydata report: {ydata_report_file}
# Output
``` text
{expectations_report}
```
'''
self.console.print(Markdown(markdown_template))
# save ydata report
with open(ydata_report_file, 'w') as fh:
outputs = self.refine_ydata_result(results)
fh.write(json.dumps(outputs))
self._show_result()
return outputs['has_error'], {'ge': ge_report_file, 'ydata': ydata_report_file}
except Exception as e:
# mark as error
self.console.print_exception(show_locals=True)
self._show_result(e)
return True, None
def copy_report(self, ge_workspace):
for report_json in glob(os.path.join(ge_workspace, 'great_expectations', 'uncommitted', '**', '*.json'),
recursive=True):
filename = os.path.basename(self.stage_file).split('.')[0]
report_name = f'{filename}_{self.name}_{os.path.basename(report_json)}'
shutil.copy(report_json, os.path.join(os.environ['PIPERIDER_REPORT_DIR'], report_name))
return report_name
def execute_custom_assertions(self, ge_context, report_file):
from piperider_cli.data.convert_to_exp import get_scheduled_tests
scheduled_tests = get_scheduled_tests()
if not scheduled_tests:
return
print(f"executing {len(scheduled_tests)} scheduled tests", )
for k, v in scheduled_tests.items():
try:
# execute the scheduled test
action_result = v.execute_and_remove_from_queue(ge_context)
if isinstance(action_result, bool):
self.update_report(report_file, v, action_result)
elif isinstance(action_result, pd.DataFrame):
values = action_result.all().values
if len(values) == 1 and values[0]:
self.update_report(report_file, v, True if values[0] else False)
else:
self.update_report(report_file, v, False)
except Exception as e:
click.echo(f'Error: {e}')
raise
finally:
# TODO update the report to ge's output
pass
def update_report(self, report_file, custom_assertion, action_result):
with open(report_file) as fh:
report_data = json.loads(fh.read())
results = report_data['results']
kwargs = {
"batch_id": "68826d1fc4627a6685f0291acd9c54bb",
}
if 'column' in custom_assertion.test_definition:
kwargs['column'] = custom_assertion.test_definition['column']
results.append(
{
"exception_info": {
"exception_message": None,
"exception_traceback": None,
"raised_exception": False
},
"expectation_config": {
"expectation_type": f"custom-assertion::{custom_assertion.function_name}",
"kwargs": kwargs,
"meta": {
"test_definition": custom_assertion.test_definition,
"function_name": custom_assertion.function_name
}
},
"meta": {},
"result": {},
"success": action_result
}
)
if not action_result:
report_data['success'] = False
all_count = len(results)
success_count = len([r for r in results if r['success']])
report_data['statistics'] = {
'evaluated_expectations': all_count,
'success_percent': 100 * (success_count / all_count),
'successful_expectations': success_count,
'unsuccessful_expectations': all_count - success_count}
# write back to file
with open(report_file, 'w') as fd:
fd.write(json.dumps(report_data, indent=2))
pass
def refine_ydata_result(self, results: dict):
outputs = {'has_error': True}
for k, v in results.items():
if 'Expectation Level Assessment' == k:
refined_assessment = list(v)
for idx, elem in enumerate(refined_assessment):
if isinstance(elem, pd.DataFrame):
refined_assessment[idx] = elem.to_json(orient='table')
outputs['has_error'] = False if elem['Successful?'].all() else True
outputs[k] = refined_assessment
else:
outputs[k] = v
return outputs
class StageFile(object):
def __init__(self, stage_file):
self.stage_file = stage_file
from piperider_cli.config import load_stages
self.stage_content: dict = load_stages(stage_file)
self.filename = stage_file
def stages(self):
for k in self.stage_content.keys():
yield Stage(self, k, self.stage_content[k])
def get(self, name):
if name in self.stage_content:
return Stage(self, name, self. | [name])
| infuseai__piperider |
47 | 47-34-31 | inproject | markdown | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui. | (content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-34-49 | inproject | classes | [
"apply_tailwind",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"content",
"extras",
"page",
"parent_view",
"props",
"set_content",
"style",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content). | ('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-36-26 | commited | __doc__ | [
"capitalize",
"casefold",
"center",
"count",
"encode",
"endswith",
"expandtabs",
"find",
"format",
"format_map",
"index",
"isalnum",
"isalpha",
"isascii",
"isdecimal",
"isdigit",
"isidentifier",
"islower",
"isnumeric",
"isprintable",
"isspace",
"istitle",
"isupper",
"join",
"ljust",
"lower",
"lstrip",
"maketrans",
"partition",
"removeprefix",
"removesuffix",
"replace",
"rfind",
"rindex",
"rjust",
"rpartition",
"rsplit",
"rstrip",
"split",
"splitlines",
"startswith",
"strip",
"swapcase",
"title",
"translate",
"upper",
"zfill",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__getitem__",
"__getnewargs__",
"__gt__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__le__",
"__len__",
"__lt__",
"__mod__",
"__module__",
"__mul__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rmul__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content. | or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-36-45 | commited | __init__ | [
"capitalize",
"casefold",
"center",
"count",
"encode",
"endswith",
"expandtabs",
"find",
"format",
"format_map",
"index",
"isalnum",
"isalpha",
"isascii",
"isdecimal",
"isdigit",
"isidentifier",
"islower",
"isnumeric",
"isprintable",
"isspace",
"istitle",
"isupper",
"join",
"ljust",
"lower",
"lstrip",
"maketrans",
"partition",
"removeprefix",
"removesuffix",
"replace",
"rfind",
"rindex",
"rjust",
"rpartition",
"rsplit",
"rstrip",
"split",
"splitlines",
"startswith",
"strip",
"swapcase",
"title",
"translate",
"upper",
"zfill",
"__add__",
"__annotations__",
"__class__",
"__contains__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__getitem__",
"__getnewargs__",
"__gt__",
"__hash__",
"__init__",
"__init_subclass__",
"__iter__",
"__le__",
"__len__",
"__lt__",
"__mod__",
"__module__",
"__mul__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rmul__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content. | .__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-36-54 | commited | __doc__ | [
"__annotations__",
"__call__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__func__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__name__",
"__ne__",
"__new__",
"__qualname__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__self__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__. |
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-45-24 | inproject | column | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui. | ().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-45-33 | inproject | classes | [
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"clear",
"page",
"parent_view",
"props",
"style",
"tight",
"tooltip",
"update",
"view",
"visible",
"_child_count_on_enter",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__enter__",
"__eq__",
"__exit__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column(). | ('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-55-27 | inproject | indentsize | [
"abc",
"ArgInfo",
"ArgSpec",
"Arguments",
"ast",
"attrgetter",
"Attribute",
"BlockFinder",
"BoundArguments",
"builtins",
"ClassFoundException",
"classify_class_attrs",
"cleandoc",
"ClosureVars",
"CO_ASYNC_GENERATOR",
"CO_COROUTINE",
"CO_GENERATOR",
"CO_ITERABLE_COROUTINE",
"CO_NESTED",
"CO_NEWLOCALS",
"CO_NOFREE",
"CO_OPTIMIZED",
"CO_VARARGS",
"CO_VARKEYWORDS",
"collections",
"CORO_CLOSED",
"CORO_CREATED",
"CORO_RUNNING",
"CORO_SUSPENDED",
"currentframe",
"dis",
"EndOfBlock",
"enum",
"findsource",
"formatannotation",
"formatannotationrelativeto",
"formatargspec",
"formatargvalues",
"FrameInfo",
"FullArgSpec",
"functools",
"GEN_CLOSED",
"GEN_CREATED",
"GEN_RUNNING",
"GEN_SUSPENDED",
"get_annotations",
"getabsfile",
"getargs",
"getargspec",
"getargvalues",
"getattr_static",
"getblock",
"getcallargs",
"getclasstree",
"getclosurevars",
"getcomments",
"getcoroutinelocals",
"getcoroutinestate",
"getdoc",
"getfile",
"getframeinfo",
"getfullargspec",
"getgeneratorlocals",
"getgeneratorstate",
"getinnerframes",
"getlineno",
"getmembers",
"getmodule",
"getmodulename",
"getmro",
"getouterframes",
"getsource",
"getsourcefile",
"getsourcelines",
"importlib",
"indentsize",
"isabstract",
"isasyncgen",
"isasyncgenfunction",
"isawaitable",
"isbuiltin",
"isclass",
"iscode",
"iscoroutine",
"iscoroutinefunction",
"isdatadescriptor",
"isframe",
"isfunction",
"isgenerator",
"isgeneratorfunction",
"isgetsetdescriptor",
"ismemberdescriptor",
"ismethod",
"ismethoddescriptor",
"ismodule",
"isroutine",
"istraceback",
"itertools",
"k",
"linecache",
"mod_dict",
"modulesbyfile",
"namedtuple",
"OrderedDict",
"os",
"Parameter",
"re",
"signature",
"Signature",
"stack",
"sys",
"token",
"tokenize",
"TPFLAGS_IS_ABSTRACT",
"trace",
"Traceback",
"types",
"unwrap",
"v",
"walktree",
"warnings",
"_check_class",
"_check_instance",
"_ClassFinder",
"_ClassMethodWrapper",
"_empty",
"_filesbymodname",
"_findclass",
"_finddoc",
"_has_code_flag",
"_is_type",
"_KEYWORD_ONLY",
"_main",
"_MethodWrapper",
"_missing_arguments",
"_NonUserDefinedCallables",
"_PARAM_NAME_MAPPING",
"_ParameterKind",
"_POSITIONAL_ONLY",
"_POSITIONAL_OR_KEYWORD",
"_sentinel",
"_shadowed_dict",
"_signature_bound_method",
"_signature_from_builtin",
"_signature_from_callable",
"_signature_from_function",
"_signature_fromstr",
"_signature_get_bound_param",
"_signature_get_partial",
"_signature_get_user_defined_method",
"_signature_is_builtin",
"_signature_is_functionlike",
"_signature_strip_non_python_syntax",
"_static_getmro",
"_too_many",
"_VAR_KEYWORD",
"_VAR_POSITIONAL",
"_void",
"_WrapperDescriptor",
"__author__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect. | (lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-55-60 | inproject | indentsize | [
"abc",
"ArgInfo",
"ArgSpec",
"Arguments",
"ast",
"attrgetter",
"Attribute",
"BlockFinder",
"BoundArguments",
"builtins",
"ClassFoundException",
"classify_class_attrs",
"cleandoc",
"ClosureVars",
"CO_ASYNC_GENERATOR",
"CO_COROUTINE",
"CO_GENERATOR",
"CO_ITERABLE_COROUTINE",
"CO_NESTED",
"CO_NEWLOCALS",
"CO_NOFREE",
"CO_OPTIMIZED",
"CO_VARARGS",
"CO_VARKEYWORDS",
"collections",
"CORO_CLOSED",
"CORO_CREATED",
"CORO_RUNNING",
"CORO_SUSPENDED",
"currentframe",
"dis",
"EndOfBlock",
"enum",
"findsource",
"formatannotation",
"formatannotationrelativeto",
"formatargspec",
"formatargvalues",
"FrameInfo",
"FullArgSpec",
"functools",
"GEN_CLOSED",
"GEN_CREATED",
"GEN_RUNNING",
"GEN_SUSPENDED",
"get_annotations",
"getabsfile",
"getargs",
"getargspec",
"getargvalues",
"getattr_static",
"getblock",
"getcallargs",
"getclasstree",
"getclosurevars",
"getcomments",
"getcoroutinelocals",
"getcoroutinestate",
"getdoc",
"getfile",
"getframeinfo",
"getfullargspec",
"getgeneratorlocals",
"getgeneratorstate",
"getinnerframes",
"getlineno",
"getmembers",
"getmodule",
"getmodulename",
"getmro",
"getouterframes",
"getsource",
"getsourcefile",
"getsourcelines",
"importlib",
"indentsize",
"isabstract",
"isasyncgen",
"isasyncgenfunction",
"isawaitable",
"isbuiltin",
"isclass",
"iscode",
"iscoroutine",
"iscoroutinefunction",
"isdatadescriptor",
"isframe",
"isfunction",
"isgenerator",
"isgeneratorfunction",
"isgetsetdescriptor",
"ismemberdescriptor",
"ismethod",
"ismethoddescriptor",
"ismodule",
"isroutine",
"istraceback",
"itertools",
"k",
"linecache",
"mod_dict",
"modulesbyfile",
"namedtuple",
"OrderedDict",
"os",
"Parameter",
"re",
"signature",
"Signature",
"stack",
"sys",
"token",
"tokenize",
"TPFLAGS_IS_ABSTRACT",
"trace",
"Traceback",
"types",
"unwrap",
"v",
"walktree",
"warnings",
"_check_class",
"_check_instance",
"_ClassFinder",
"_ClassMethodWrapper",
"_empty",
"_filesbymodname",
"_findclass",
"_finddoc",
"_has_code_flag",
"_is_type",
"_KEYWORD_ONLY",
"_main",
"_MethodWrapper",
"_missing_arguments",
"_NonUserDefinedCallables",
"_PARAM_NAME_MAPPING",
"_ParameterKind",
"_POSITIONAL_ONLY",
"_POSITIONAL_OR_KEYWORD",
"_sentinel",
"_shadowed_dict",
"_signature_bound_method",
"_signature_from_builtin",
"_signature_from_callable",
"_signature_from_function",
"_signature_fromstr",
"_signature_get_bound_param",
"_signature_get_partial",
"_signature_get_user_defined_method",
"_signature_is_builtin",
"_signature_is_functionlike",
"_signature_strip_non_python_syntax",
"_static_getmro",
"_too_many",
"_VAR_KEYWORD",
"_VAR_POSITIONAL",
"_void",
"_WrapperDescriptor",
"__author__",
"__doc__",
"__file__",
"__name__",
"__package__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect. | (lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-66-15 | inproject | markdown | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui. | (code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-66-30 | inproject | classes | [
"apply_tailwind",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"content",
"extras",
"page",
"parent_view",
"props",
"set_content",
"style",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code). | ('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-74-11 | inproject | label | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui. | (text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-74-23 | inproject | style | [
"bind_text",
"bind_text_from",
"bind_text_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"page",
"parent_view",
"props",
"set_text",
"style",
"text",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text). | ('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-84-20 | infile | link | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui. | ):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-90-20 | infile | toggle | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui. | ):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-95-20 | inproject | radio | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui. | ([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-95-46 | inproject | props | [
"bind_value",
"bind_value_from",
"bind_value_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"change_handler",
"classes",
"handle_change",
"page",
"parent_view",
"props",
"set_value",
"style",
"tooltip",
"update",
"value",
"value_to_view",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1). | ('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-99-21 | random | select | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui. | ([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-102-20 | infile | checkbox | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui. | ):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-104-11 | inproject | label | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui. | ('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-104-27 | inproject | bind_visibility_from | [
"bind_text",
"bind_text_from",
"bind_text_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"page",
"parent_view",
"props",
"set_text",
"style",
"text",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!'). | (checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-107-20 | random | switch | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui. | ('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-108-11 | inproject | label | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui. | ('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-108-28 | inproject | bind_visibility_from | [
"bind_text",
"bind_text_from",
"bind_text_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"page",
"parent_view",
"props",
"set_text",
"style",
"text",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!'). | (switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-111-20 | inproject | slider | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui. | (min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-111-53 | inproject | props | [
"bind_value",
"bind_value_from",
"bind_value_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"change_handler",
"classes",
"format",
"handle_change",
"page",
"parent_view",
"props",
"set_value",
"style",
"tooltip",
"update",
"value",
"value_to_view",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50). | ('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-112-11 | inproject | label | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui. | ().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-112-19 | inproject | bind_text_from | [
"bind_text",
"bind_text_from",
"bind_text_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"page",
"parent_view",
"props",
"set_text",
"style",
"text",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label(). | (slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-117-51 | inproject | set_text | [
"bind_text",
"bind_text_from",
"bind_text_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"page",
"parent_view",
"props",
"set_text",
"style",
"text",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates. | ('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-125-20 | inproject | number | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui. | ):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-126-11 | inproject | number | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui. | (label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-127-52 | inproject | set_text | [
"bind_text",
"bind_text_from",
"bind_text_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"page",
"parent_view",
"props",
"set_text",
"style",
"text",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result. | (f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-130-20 | infile | color_input | [
"add_body_html",
"add_head_html",
"add_route",
"add_static_files",
"await_javascript",
"button",
"card",
"card_section",
"chart",
"checkbox",
"color_input",
"color_picker",
"colors",
"column",
"custom_example",
"dialog",
"expansion",
"get",
"html",
"icon",
"image",
"input",
"interactive_image",
"joystick",
"keyboard",
"label",
"line_plot",
"link",
"log",
"markdown",
"menu",
"menu_item",
"menu_separator",
"notify",
"number",
"on_connect",
"on_disconnect",
"on_shutdown",
"on_startup",
"open",
"open_async",
"page",
"plot",
"radio",
"row",
"run",
"run_javascript",
"scene",
"select",
"shutdown",
"slider",
"switch",
"table",
"timer",
"toggle",
"tree",
"update",
"upload",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui. | ):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label.style(f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |
47 | 47-133-55 | inproject | style | [
"bind_text",
"bind_text_from",
"bind_text_to",
"bind_visibility",
"bind_visibility_from",
"bind_visibility_to",
"classes",
"page",
"parent_view",
"props",
"set_text",
"style",
"text",
"tooltip",
"update",
"view",
"visible",
"__annotations__",
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__slots__",
"__str__"
] | import asyncio
import inspect
import re
from contextlib import contextmanager
from typing import Callable, Union
import docutils.core
from nicegui import ui
@contextmanager
def example(content: Union[Callable, type, str]):
callFrame = inspect.currentframe().f_back.f_back
begin = callFrame.f_lineno
def add_html_anchor(element: ui.html):
html = element.content
match = re.search(r'<h4.*?>(.*?)</h4>', html)
if not match:
return
headline_id = re.sub('[^(a-z)(A-Z)(0-9)-]', '_', match.groups()[0].strip()).lower()
if not headline_id:
return
icon = '<span class="material-icons">link</span>'
anchor = f'<a href="#{headline_id}" class="text-gray-300 hover:text-black">{icon}</a>'
html = html.replace('<h4', f'<h4 id="{headline_id}"', 1)
html = html.replace('</h4>', f' {anchor}</h4>', 1)
element.view.inner_html = html
with ui.row().classes('flex w-full'):
if isinstance(content, str):
add_html_anchor(ui.markdown(content).classes('mr-8 w-4/12'))
else:
doc = content.__doc__ or content.__init__.__doc__
html = docutils.core.publish_parts(doc, writer_name='html')['html_body']
html = html.replace('<p>', '<h4>', 1)
html = html.replace('</p>', '</h4>', 1)
html = ui.markdown.apply_tailwind(html)
add_html_anchor(ui.html(html).classes('mr-8 w-4/12'))
try:
with ui.card().classes('mt-12 w-2/12'):
with ui.column().classes('flex w-full'):
yield
finally:
code: str = open(__file__).read()
end = begin + 1
lines = code.splitlines()
while True:
end += 1
if end >= len(lines):
break
if inspect.indentsize(lines[end]) < inspect.indentsize(lines[begin]) and lines[end]:
break
code = lines[begin:end]
code = [l[8:] for l in code]
code.insert(0, '```python')
code.insert(1, 'from nicegui import ui')
if code[2].split()[0] not in ['from', 'import']:
code.insert(2, '')
code.append('ui.run()')
code.append('```')
code = '\n'.join(code)
ui.markdown(code).classes('mt-12 w-5/12 overflow-auto')
async def create():
ui.markdown('## API Documentation and Examples')
def h3(text: str) -> None:
ui.label(text).style('width: 100%; border-bottom: 1px solid silver; font-size: 200%; font-weight: 200')
h3('Basic Elements')
with example(ui.label):
ui.label('some label')
with example(ui.icon):
ui.icon('thumb_up')
with example(ui.link):
ui.link('NiceGUI on GitHub', 'https://github.com/zauberzeug/nicegui')
with example(ui.button):
ui.button('Click me!', on_click=lambda: ui.notify(f'You clicked me!'))
with example(ui.toggle):
toggle1 = ui.toggle([1, 2, 3], value=1)
toggle2 = ui.toggle({1: 'A', 2: 'B', 3: 'C'}).bind_value(toggle1, 'value')
with example(ui.radio):
radio1 = ui.radio([1, 2, 3], value=1).props('inline')
radio2 = ui.radio({1: 'A', 2: 'B', 3: 'C'}).props('inline').bind_value(radio1, 'value')
with example(ui.select):
select1 = ui.select([1, 2, 3], value=1)
select2 = ui.select({1: 'One', 2: 'Two', 3: 'Three'}).bind_value(select1, 'value')
with example(ui.checkbox):
checkbox = ui.checkbox('check me')
ui.label('Check!').bind_visibility_from(checkbox, 'value')
with example(ui.switch):
switch = ui.switch('switch me')
ui.label('Switch!').bind_visibility_from(switch, 'value')
with example(ui.slider):
slider = ui.slider(min=0, max=100, value=50).props('label')
ui.label().bind_text_from(slider, 'value')
with example(ui.joystick):
ui.joystick(color='blue', size=50,
on_move=lambda msg: coordinates.set_text(f'{msg.data.vector.x:.3f}, {msg.data.vector.y:.3f}'),
on_end=lambda msg: coordinates.set_text('0, 0'))
coordinates = ui.label('0, 0')
with example(ui.input):
ui.input(label='Text', placeholder='press ENTER to apply',
on_change=lambda e: input_result.set_text('you typed: ' + e.value))
input_result = ui.label()
with example(ui.number):
ui.number(label='Number', value=3.1415927, format='%.2f',
on_change=lambda e: number_result.set_text(f'you entered: {e.value}'))
number_result = ui.label()
with example(ui.color_input):
color_label = ui.label('Change my color!')
ui.color_input(label='Color', value='#000000',
on_change=lambda e: color_label. | (f'color:{e.value}'))
with example(ui.color_picker):
picker = ui.color_picker(on_pick=lambda e: button.style(f'background-color:{e.color}!important'))
button = ui.button(on_click=picker.open).props('icon=colorize')
with example(ui.upload):
ui.upload(on_upload=lambda e: ui.notify(f'{len(e.files[0])} bytes'))
h3('Markdown and HTML')
with example(ui.markdown):
ui.markdown('''This is **Markdown**.''')
with example(ui.html):
ui.html('This is <strong>HTML</strong>.')
svg = '''#### SVG
You can add Scalable Vector Graphics using the `ui.html` element.
'''
with example(svg):
content = '''
<svg viewBox="0 0 200 200" width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="78" fill="#ffde34" stroke="black" stroke-width="3" />
<circle cx="80" cy="85" r="8" />
<circle cx="120" cy="85" r="8" />
<path d="m60,120 C75,150 125,150 140,120" style="fill:none; stroke:black; stroke-width:8; stroke-linecap:round" />
</svg>'''
ui.html(content)
h3('Images')
with example(ui.image):
ui.image('http://placeimg.com/640/360/tech')
captions_and_overlays = '''#### Captions and Overlays
By nesting elements inside a `ui.image` you can create augmentations.
Use [Quasar classes](https://quasar.dev/vue-components/img) for positioning and styling captions.
To overlay an SVG, make the `viewBox` exactly the size of the image and provide `100%` width/height to match the actual rendered size.
'''
with example(captions_and_overlays):
with ui.image('http://placeimg.com/640/360/nature'):
ui.label('Nice!').classes('absolute-bottom text-subtitle2 text-center')
with ui.image('https://cdn.stocksnap.io/img-thumbs/960w/airplane-sky_DYPWDEEILG.jpg'):
content = '''
<svg viewBox="0 0 960 638" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<circle cx="445" cy="300" r="100" fill="none" stroke="red" stroke-width="20" />
</svg>'''
ui.html(content).style('background:transparent')
with example(ui.interactive_image):
from nicegui.events import MouseEventArguments
def mouse_handler(e: MouseEventArguments):
color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
ii.svg_content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="20" fill="{color}"/>'
ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')
src = 'https://cdn.stocksnap.io/img-thumbs/960w/corn-cob_YSZZZEC59W.jpg'
ii = ui.interactive_image(src, on_mouse=mouse_handler, events=['mousedown', 'mouseup'], cross=True)
h3('Data Elements')
with example(ui.table):
table = ui.table({
'columnDefs': [
{'headerName': 'Name', 'field': 'name'},
{'headerName': 'Age', 'field': 'age'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
}).classes('max-h-40')
def update():
table.options.rowData[0].age += 1
table.update()
ui.button('Update', on_click=update)
with example(ui.chart):
from numpy.random import random
chart = ui.chart({
'title': False,
'chart': {'type': 'bar'},
'xAxis': {'categories': ['A', 'B']},
'series': [
{'name': 'Alpha', 'data': [0.1, 0.2]},
{'name': 'Beta', 'data': [0.3, 0.4]},
],
}).classes('max-w-full h-64')
def update():
chart.options.series[0].data[:] = random(2)
chart.update()
ui.button('Update', on_click=update)
with example(ui.plot):
import numpy as np
from matplotlib import pyplot as plt
with ui.plot(figsize=(2.5, 1.8)):
x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, '-')
plt.xlabel('time (s)')
plt.ylabel('Damped oscillation')
with example(ui.line_plot):
from datetime import datetime
import numpy as np
line_plot = ui.line_plot(n=2, limit=20, figsize=(2.5, 1.8)) \
.with_legend(['sin', 'cos'], loc='upper center', ncol=2)
def update_line_plot() -> None:
now = datetime.now()
x = now.timestamp()
y1 = np.sin(x)
y2 = np.cos(x)
line_plot.push([now], [[y1], [y2]])
line_updates = ui.timer(0.1, update_line_plot, active=False)
ui.checkbox('active').bind_value(line_updates, 'active')
with example(ui.scene):
with ui.scene(width=200, height=200) as scene:
scene.sphere().material('#4488ff')
scene.cylinder(1, 0.5, 2, 20).material('#ff8800', opacity=0.5).move(-2, 1)
scene.extrusion([[0, 0], [0, 1], [1, 0.5]], 0.1).material('#ff8888').move(-2, -2)
with scene.group().move(z=2):
box1 = scene.box().move(x=2)
scene.box().move(y=2).rotate(0.25, 0.5, 0.75)
scene.box(wireframe=True).material('#888888').move(x=2, y=2)
scene.line([-4, 0, 0], [-4, 2, 0]).material('#ff0000')
scene.curve([-4, 0, 0], [-4, -1, 0], [-3, -1, 0], [-3, -2, 0]).material('#008800')
logo = "https://avatars.githubusercontent.com/u/2843826"
scene.texture(logo, [[[0.5, 2, 0], [2.5, 2, 0]],
[[0.5, 0, 0], [2.5, 0, 0]]]).move(1, -2)
teapot = 'https://upload.wikimedia.org/wikipedia/commons/9/93/Utah_teapot_(solid).stl'
scene.stl(teapot).scale(0.2).move(-3, 4)
scene.text('2D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(z=2)
scene.text3d('3D', 'background: rgba(0, 0, 0, 0.2); border-radius: 5px; padding: 5px').move(y=-2).scale(.05)
with example(ui.tree):
ui.tree([
{'id': 'numbers', 'children': [{'id': '1'}, {'id': '2'}]},
{'id': 'letters', 'children': [{'id': 'A'}, {'id': 'B'}]},
], label_key='id', on_select=lambda e: ui.notify(e.value))
with example(ui.log):
from datetime import datetime
log = ui.log(max_lines=10).classes('h-16')
ui.button('Log time', on_click=lambda: log.push(datetime.now().strftime("%X.%f")[:-5]))
h3('Layout')
with example(ui.card):
with ui.card().tight():
ui.image('http://placeimg.com/640/360/nature')
with ui.card_section():
ui.label('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...')
with example(ui.column):
with ui.column():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
with example(ui.row):
with ui.row():
ui.label('label 1')
ui.label('label 2')
ui.label('label 3')
clear_containers = '''#### Clear Containers
To remove all elements from a row, column or card container, use the `clear()` method.
'''
with example(clear_containers):
container = ui.row()
def add_face():
with container:
ui.icon('face')
add_face()
ui.button('Add', on_click=add_face)
ui.button('Clear', on_click=container.clear)
with example(ui.expansion):
with ui.expansion('Expand!', icon='work').classes('w-full'):
ui.label('inside the expansion')
with example(ui.menu):
choice = ui.label('Try the menu.')
with ui.menu() as menu:
ui.menu_item('Menu item 1', lambda: choice.set_text('Selected item 1.'))
ui.menu_item('Menu item 2', lambda: choice.set_text('Selected item 2.'))
ui.menu_item('Menu item 3 (keep open)', lambda: choice.set_text('Selected item 3.'), auto_close=False)
ui.menu_separator()
ui.menu_item('Close', on_click=menu.close)
ui.button('Open menu', on_click=menu.open)
tooltips = '''#### Tooltips
Simply call the `tooltip(text:str)` method on UI elements to provide a tooltip.
'''
with example(tooltips):
ui.label('Tooltips...').tooltip('...are shown on mouse over')
ui.button().props('icon=thumb_up').tooltip('I like this')
with example(ui.notify):
ui.button('Say hi!', on_click=lambda: ui.notify('Hi!', close_button='OK'))
with example(ui.dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Hello world!')
ui.button('Close', on_click=dialog.close)
ui.button('Open a dialog', on_click=dialog.open)
async_dialog = '''#### Awaitable dialog
Dialogs can be awaited.
Use the `submit` method to close the dialog and return a result.
Canceling the dialog by clicking in the background or pressing the escape key yields `None`.
'''
with example(async_dialog):
with ui.dialog() as dialog, ui.card():
ui.label('Are you sure?')
with ui.row():
ui.button('Yes', on_click=lambda: dialog.submit('Yes'))
ui.button('No', on_click=lambda: dialog.submit('No'))
async def show():
result = await dialog
ui.notify(f'You chose {result}')
ui.button('Await a dialog', on_click=show)
h3('Appearance')
design = '''#### Styling
NiceGUI uses the [Quasar Framework](https://quasar.dev/) version 1.0 and hence has its full design power.
Each NiceGUI element provides a `props` method whose content is passed [to the Quasar component](https://justpy.io/quasar_tutorial/introduction/#props-of-quasar-components):
Have a look at [the Quasar documentation](https://quasar.dev/vue-components/button#design) for all styling props.
You can also apply [Tailwind](https://tailwindcss.com/) utility classes with the `classes` method.
If you really need to apply CSS, you can use the `styles` method. Here the delimiter is `;` instead of a blank space.
All three functions also provide `remove` and `replace` parameters in case the predefined look is not wanted in a particular styling.
'''
with example(design):
ui.radio(['x', 'y', 'z'], value='x').props('inline color=green')
ui.button().props('icon=touch_app outline round').classes('shadow-lg')
ui.label('Stylish!').style('color: #6E93D6; font-size: 200%; font-weight: 300')
with example(ui.colors):
ui.colors()
ui.button('Default', on_click=lambda: ui.colors())
ui.button('Gray', on_click=lambda: ui.colors(primary='#555'))
h3('Action')
lifecycle = '''#### Lifecycle
You can run a function or coroutine as a parallel task by passing it to one of the following register methods:
- `ui.on_startup`: Called when NiceGUI is started or restarted.
- `ui.on_shutdown`: Called when NiceGUI is shut down or restarted.
- `ui.on_connect`: Called when a client connects to NiceGUI. (Optional argument: Starlette request)
- `ui.on_page_ready`: Called when the page is ready and the websocket is connected. (Optional argument: socket)
- `ui.on_disconnect`: Called when a client disconnects from NiceGUI. (Optional argument: socket)
When NiceGUI is shut down or restarted, the startup tasks will be automatically canceled.
'''
with example(lifecycle):
import time
l = ui.label()
async def run_clock():
while True:
l.text = f'unix time: {time.time():.1f}'
await asyncio.sleep(1)
ui.on_startup(run_clock)
ui.on_connect(lambda: l.set_text('new connection'))
with example(ui.timer):
from datetime import datetime
with ui.row().classes('items-center'):
clock = ui.label()
t = ui.timer(interval=0.1, callback=lambda: clock.set_text(datetime.now().strftime("%X.%f")[:-5]))
ui.checkbox('active').bind_value(t, 'active')
with ui.row():
def lazy_update() -> None:
new_text = datetime.now().strftime('%X.%f')[:-5]
if lazy_clock.text[:8] == new_text[:8]:
return
lazy_clock.text = new_text
lazy_clock = ui.label()
ui.timer(interval=0.1, callback=lazy_update)
with example(ui.keyboard):
from nicegui.events import KeyEventArguments
def handle_key(e: KeyEventArguments):
if e.key == 'f' and not e.action.repeat:
if e.action.keyup:
ui.notify('f was just released')
elif e.action.keydown:
ui.notify('f was just pressed')
if e.modifiers.shift and e.action.keydown:
if e.key.arrow_left:
ui.notify('going left')
elif e.key.arrow_right:
ui.notify('going right')
elif e.key.arrow_up:
ui.notify('going up')
elif e.key.arrow_down:
ui.notify('going down')
keyboard = ui.keyboard(on_key=handle_key)
ui.label('Key events can be caught globally by using the keyboard element.')
ui.checkbox('Track key events').bind_value_to(keyboard, 'active')
bindings = '''#### Bindings
NiceGUI is able to directly bind UI elements to models.
Binding is possible for UI element properties like text, value or visibility and for model properties that are (nested) class attributes.
Each element provides methods like `bind_value` and `bind_visibility` to create a two-way binding with the corresponding property.
To define a one-way binding use the `_from` and `_to` variants of these methods.
Just pass a property of the model as parameter to these methods to create the binding.
'''
with example(bindings):
class Demo:
def __init__(self):
self.number = 1
demo = Demo()
v = ui.checkbox('visible', value=True)
with ui.column().bind_visibility_from(v, 'value'):
ui.slider(min=1, max=3).bind_value(demo, 'number')
ui.toggle({1: 'a', 2: 'b', 3: 'c'}).bind_value(demo, 'number')
ui.number().bind_value(demo, 'number')
ui_updates = '''#### UI Updates
NiceGUI tries to automatically synchronize the state of UI elements with the client, e.g. when a label text, an input value or style/classes/props of an element have changed.
In other cases, you can explicitly call `element.update()` or `ui.update(*elements)` to update.
The example code shows both methods for a `ui.table`, where it is difficult to automatically detect changes in the `options` dictionary.
'''
with example(ui_updates):
from random import randint
def add():
numbers.options.rowData.append({'numbers': randint(0, 100)})
numbers.update()
def clear():
numbers.options.rowData.clear()
ui.update(numbers)
numbers = ui.table({'columnDefs': [{'field': 'numbers'}], 'rowData': []}).classes('max-h-40')
ui.button('Add', on_click=add)
ui.button('Clear', on_click=clear)
async_handlers = '''#### Async event handlers
Most elements also support asynchronous event handlers.
Note: You can also pass a `functools.partial` into the `on_click` property to wrap async functions with parameters.
'''
with example(async_handlers):
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
h3('Pages and Routes')
with example(ui.page):
@ui.page('/other_page')
def other_page():
ui.label('Welcome to the other side')
ui.link('Back to main page', '#page')
@ui.page('/dark_page', dark=True)
def dark_page():
ui.label('Welcome to the dark side')
ui.link('Back to main page', '#page')
ui.link('Visit other page', other_page)
ui.link('Visit dark page', dark_page)
shared_and_private_pages = '''#### Shared and Private Pages
By default, pages created with the `@ui.page` decorator are "private".
Their content is re-created for each client.
Thus, in the example to the right, the displayed ID changes when the browser reloads the page.
With `shared=True` you can create a shared page.
Its content is created once at startup and each client sees the *same* elements.
Here, the displayed ID remains constant when the browser reloads the page.
# Index page
All elements that are not created within a decorated page function are automatically added to a new, *shared* index page at route "/".
To make it "private" or to change other attributes like title, favicon etc. you can wrap it in a page function with `@ui.page('/', ...)` decorator.
'''
with example(shared_and_private_pages):
from uuid import uuid4
@ui.page('/private_page')
async def private_page():
ui.label(f'private page with ID {uuid4()}')
@ui.page('/shared_page', shared=True)
async def shared_page():
ui.label(f'shared page with ID {uuid4()}')
ui.link('private page', private_page)
ui.link('shared page', shared_page)
with example(ui.open):
@ui.page('/yet_another_page')
def yet_another_page():
ui.label('Welcome to yet another page')
ui.button('RETURN', on_click=lambda e: ui.open('#open', e.socket))
ui.button('REDIRECT', on_click=lambda e: ui.open(yet_another_page, e.socket))
add_route = '''#### Route
Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called.
Routed paths must start with a `'/'`.
'''
with example(add_route):
import starlette
ui.add_route(starlette.routing.Route(
'/new/route', lambda _: starlette.responses.PlainTextResponse('Response')
))
ui.link('Try the new route!', 'new/route')
get_decorator = '''#### Get decorator
Syntactic sugar to add routes.
Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
An optional `request` argument gives access to the complete request object.
'''
with example(get_decorator):
from starlette import requests, responses
@ui.get('/another/route/{id}')
def produce_plain_response(id: str, request: requests.Request):
return responses.PlainTextResponse(f'{request.client.host} asked for id={id}')
ui.link('Try yet another route!', 'another/route/42')
sessions = '''#### Sessions
`ui.page` provides an optional `on_connect` argument to register a callback.
It is invoked for each new connection to the page.
The optional `request` argument provides insights about the clients URL parameters etc. (see [the JustPy docs](https://justpy.io/tutorial/request_object/) for more details).
It also enables you to identify sessions over [longer time spans by configuring cookies](https://justpy.io/tutorial/sessions/).
'''
with example(sessions):
from collections import Counter
from datetime import datetime
from starlette.requests import Request
id_counter = Counter()
creation = datetime.now().strftime('%H:%M, %d %B %Y')
def handle_connection(request: Request):
id_counter[request.session_id] += 1
visits.set_text(f'{len(id_counter)} unique views ({sum(id_counter.values())} overall) since {creation}')
@ui.page('/session_demo', on_connect=handle_connection)
def session_demo():
global visits
visits = ui.label()
ui.link('Visit session demo', session_demo)
javascript = '''#### JavaScript
With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
The asynchronous function will return after sending the command.
With `ui.await_javascript()` you can send a JavaScript command and wait for its response.
The asynchronous function will only return after receiving the result.
'''
with example(javascript):
async def run_javascript():
await ui.run_javascript('alert("Hello!")')
async def await_javascript():
response = await ui.await_javascript('Date()')
ui.notify(f'Browser time: {response}')
ui.button('run JavaScript', on_click=run_javascript)
ui.button('await JavaScript', on_click=await_javascript)
| zauberzeug__nicegui |