code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def managers_one_page_two_components_two_controls(vizro_app, dash_data_table_with_id): """Instantiates managers with one page that contains two controls and two components.""" vm.Dashboard( pages=[ vm.Page( id="test_page", title="First page", c...
Instantiates managers with one page that contains two controls and two components.
managers_one_page_two_components_two_controls
python
mckinsey/vizro
vizro-core/tests/unit/vizro/actions/_action_loop/test_get_action_loop_components.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/_action_loop/test_get_action_loop_components.py
Apache-2.0
def managers_one_page_no_actions(vizro_app): """Instantiates managers with one "empty" page.""" vm.Dashboard( pages=[ vm.Page( id="test_page_no_actions", title="Second page", components=[ vm.Card(text=""), ],...
Instantiates managers with one "empty" page.
managers_one_page_no_actions
python
mckinsey/vizro
vizro-core/tests/unit/vizro/actions/_action_loop/test_get_action_loop_components.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/actions/_action_loop/test_get_action_loop_components.py
Apache-2.0
def test_model_type_none_root_model_none(self): """model_type is None | page is None -> return all elements.""" result = [model.id for model in model_manager._get_models()] expected = { "page_1_id", "page_1_button_id", "page_1_graph_id", "page_2_i...
model_type is None | page is None -> return all elements.
test_model_type_none_root_model_none
python
mckinsey/vizro
vizro-core/tests/unit/vizro/managers/test_model_manager.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/managers/test_model_manager.py
Apache-2.0
def test_model_type_root_model_none(self): """model_type is vm.Button | root_model is None -> return all vm.Button from the dashboard.""" result = [model.id for model in model_manager._get_models(model_type=vm.Button)] expected = {"page_1_button_id", "page_2_button_id"} excluded = {"pag...
model_type is vm.Button | root_model is None -> return all vm.Button from the dashboard.
test_model_type_root_model_none
python
mckinsey/vizro
vizro-core/tests/unit/vizro/managers/test_model_manager.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/managers/test_model_manager.py
Apache-2.0
def test_model_type_none_root_model_not_none(self, page_1): """model_type is None | root_model is page_1 -> return all elements from the page_1.""" result = [model.id for model in model_manager._get_models(root_model=page_1)] expected = {"page_1_id", "page_1_button_id", "page_1_graph_id"} ...
model_type is None | root_model is page_1 -> return all elements from the page_1.
test_model_type_none_root_model_not_none
python
mckinsey/vizro
vizro-core/tests/unit/vizro/managers/test_model_manager.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/managers/test_model_manager.py
Apache-2.0
def test_model_type_not_none_page_not_none(self, page_1): """model_type is vm.Button | page is page_1 -> return all vm.Button from the page_1.""" result = [model.id for model in model_manager._get_models(model_type=vm.Button, root_model=page_1)] expected = {"page_1_button_id"} excluded ...
model_type is vm.Button | page is page_1 -> return all vm.Button from the page_1.
test_model_type_not_none_page_not_none
python
mckinsey/vizro
vizro-core/tests/unit/vizro/managers/test_model_manager.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/managers/test_model_manager.py
Apache-2.0
def test_model_type_no_match_root_model_none(self): """model_type matches no type | root_model is None -> return empty list.""" # There is no AgGrid in the dashboard result = [model.id for model in model_manager._get_models(model_type=vm.AgGrid)] assert result == []
model_type matches no type | root_model is None -> return empty list.
test_model_type_no_match_root_model_none
python
mckinsey/vizro
vizro-core/tests/unit/vizro/managers/test_model_manager.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/managers/test_model_manager.py
Apache-2.0
def test_model_type_no_match_root_model_not_none(self, page_1): """model_type matches no type | root_model is page_1 -> return empty list.""" # There is no AgGrid in the page_1 result = [model.id for model in model_manager._get_models(model_type=vm.AgGrid, root_model=page_1)] assert res...
model_type matches no type | root_model is page_1 -> return empty list.
test_model_type_no_match_root_model_not_none
python
mckinsey/vizro
vizro-core/tests/unit/vizro/managers/test_model_manager.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/managers/test_model_manager.py
Apache-2.0
def test_model_type_tuple_of_models(self): """model_type is tuple of models -> return all elements of the specified types from the dashboard.""" result = [model.id for model in model_manager._get_models(model_type=(vm.Button, vm.Graph))] expected = {"page_1_button_id", "page_1_graph_id", "page_...
model_type is tuple of models -> return all elements of the specified types from the dashboard.
test_model_type_tuple_of_models
python
mckinsey/vizro
vizro-core/tests/unit/vizro/managers/test_model_manager.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/managers/test_model_manager.py
Apache-2.0
def test_model_type_figure_models(self): """model_type is FIGURE_MODELS | root_model is None -> return all figure elements from the dashboard.""" result = [model.id for model in model_manager._get_models(model_type=FIGURE_MODELS)] expected = {"page_1_graph_id", "page_2_figure_id"} exclu...
model_type is FIGURE_MODELS | root_model is None -> return all figure elements from the dashboard.
test_model_type_figure_models
python
mckinsey/vizro
vizro-core/tests/unit/vizro/managers/test_model_manager.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/managers/test_model_manager.py
Apache-2.0
def test_subclass_model_type(self, page_1, standard_px_chart): """model_type is subclass of vm.Graph -> return all elements of the specified type and its subclasses.""" class CustomGraph(vm.Graph): pass page_1.components.append(CustomGraph(id="page_1_custom_graph_id", figure=standa...
model_type is subclass of vm.Graph -> return all elements of the specified type and its subclasses.
test_subclass_model_type
python
mckinsey/vizro
vizro-core/tests/unit/vizro/managers/test_model_manager.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/managers/test_model_manager.py
Apache-2.0
def test_nested_models(self, page_1, make_nested_control): """Model is nested under another model and known property in different ways -> return the model.""" class ControlGroup(vm.VizroBaseModel): controls: Any page_1.controls.append( ControlGroup(controls=make_nested_...
Model is nested under another model and known property in different ways -> return the model.
test_nested_models
python
mckinsey/vizro
vizro-core/tests/unit/vizro/managers/test_model_manager.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/managers/test_model_manager.py
Apache-2.0
def test_model_under_unknown_field(self, page_1): """Model is nested under another model but under an unknown field -> don't return the model.""" class ControlGroup(vm.VizroBaseModel): unknown_field: Any page_1.controls.append(ControlGroup(unknown_field=vm.Filter(id="page_1_control...
Model is nested under another model but under an unknown field -> don't return the model.
test_model_under_unknown_field
python
mckinsey/vizro
vizro-core/tests/unit/vizro/managers/test_model_manager.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/managers/test_model_manager.py
Apache-2.0
def test_root_model_container(self, container_1): """model_type is None | root_model is container_1 -> return all elements from the container_1.""" result = [model.id for model in model_manager._get_models(root_model=container_1)] expected = {"container_1_id", "container_1_button_id", "containe...
model_type is None | root_model is container_1 -> return all elements from the container_1.
test_root_model_container
python
mckinsey/vizro
vizro-core/tests/unit/vizro/managers/test_model_manager.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/managers/test_model_manager.py
Apache-2.0
def test_model_in_page(self, page_1): """Model is in page -> return page.""" result = model_manager._get_model_page(page_1.components[0]) assert result == page_1
Model is in page -> return page.
test_model_in_page
python
mckinsey/vizro
vizro-core/tests/unit/vizro/managers/test_model_manager.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/managers/test_model_manager.py
Apache-2.0
def test_model_not_in_page(self, page_1): """Model is not in page -> return None.""" # Instantiate standalone model button = vm.Button(id="standalone_button_id") result = model_manager._get_model_page(button) assert result is None
Model is not in page -> return None.
test_model_not_in_page
python
mckinsey/vizro
vizro-core/tests/unit/vizro/managers/test_model_manager.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/managers/test_model_manager.py
Apache-2.0
def test_model_is_page(self, page_1): """Model is Page -> return that page.""" result = model_manager._get_model_page(page_1) assert result == page_1
Model is Page -> return that page.
test_model_is_page
python
mckinsey/vizro
vizro-core/tests/unit/vizro/managers/test_model_manager.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/managers/test_model_manager.py
Apache-2.0
def test_add_same_model(self, Parent): """Test whether adding same model re-defined avoids pydantic discriminator error.""" class MultipleChild(vm.VizroBaseModel): type: Literal["derived"] = "derived" Parent.add_type("child", MultipleChild) class MultipleChild(vm.VizroBase...
Test whether adding same model re-defined avoids pydantic discriminator error.
test_add_same_model
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/test_base.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/test_base.py
Apache-2.0
def test_add_duplicate_type(self, Parent): """Test whether adding model of same type avoids pydantic discriminator error.""" class MultipleChild(ChildX): pass Parent.add_type("child", MultipleChild)
Test whether adding model of same type avoids pydantic discriminator error.
test_add_duplicate_type
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/test_base.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/test_base.py
Apache-2.0
def test_button_build_with_extra(self): """Test that extra arguments correctly override defaults.""" result = vm.Button( id="button", text="Click me!", extra={"color": "success", "outline": True, "href": "www.google.com"} ).build() assert_component_equal( result, ...
Test that extra arguments correctly override defaults.
test_button_build_with_extra
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_components/test_button.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_components/test_button.py
Apache-2.0
def test_button_build_with_description(self): """Test that description argument correctly builds icon and tooltip.""" result = vm.Button( id="button", text="Click me", description=vm.Tooltip(text="Test description", icon="info", id="info"), ).build() ...
Test that description argument correctly builds icon and tooltip.
test_button_build_with_description
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_components/test_button.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_components/test_button.py
Apache-2.0
def test_card_build_with_extra(self): """Test that extra arguments correctly override defaults.""" card = vm.Card(id="card_id", text="Hello", extra={"class_name": "bg-primary p-1 mt-2 text-center h2"}).build() assert_component_equal( card, dbc.Card( id="ca...
Test that extra arguments correctly override defaults.
test_card_build_with_extra
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_components/test_card.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_components/test_card.py
Apache-2.0
def test_container_build_with_extra(self): """Test that extra arguments correctly override defaults.""" result = vm.Container( id="container", title="Title", components=[vm.Button()], extra={"fluid": False, "class_name": "bg-container"}, ).build() ...
Test that extra arguments correctly override defaults.
test_container_build_with_extra
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_components/test_container.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_components/test_container.py
Apache-2.0
def test_text_build_with_extra(self): """Test that extra arguments correctly override defaults.""" text = vm.Text(id="text_id", text="Test", extra={"className": "bg-primary p-1 mt-2 text-center h2"}) text = text.build() expected = dcc.Markdown( id="text_id", chil...
Test that extra arguments correctly override defaults.
test_text_build_with_extra
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_components/test_text.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_components/test_text.py
Apache-2.0
def test_checklist_build_with_extra(self): """Test that extra arguments correctly override defaults.""" checklist = Checklist( id="checklist_id", options=["A", "B", "C"], value=["A"], title="Title", extra={ "switch": True, ...
Test that extra arguments correctly override defaults.
test_checklist_build_with_extra
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_components/form/test_checklist.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_components/form/test_checklist.py
Apache-2.0
def test_checklist_build_with_description(self): """Test that description arguments correctly builds icon and tooltip.""" checklist = Checklist( options=["A", "B", "C"], value=["A"], title="Title", description=Tooltip(text="Test description", icon="info", ...
Test that description arguments correctly builds icon and tooltip.
test_checklist_build_with_description
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_components/form/test_checklist.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_components/form/test_checklist.py
Apache-2.0
def test_datepicker_build_with_extra(self): """Test that extra arguments correctly override defaults.""" date_picker = vm.DatePicker( id="datepicker_id", min="2023-01-01", max="2023-07-01", value="2023-01-05", range=False, title="Ti...
Test that extra arguments correctly override defaults.
test_datepicker_build_with_extra
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_components/form/test_date_picker.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_components/form/test_date_picker.py
Apache-2.0
def test_datepicker_build_with_description(self): """Test that extra arguments correctly override defaults.""" date_picker = vm.DatePicker( id="datepicker_id", min="2023-01-01", max="2023-07-01", value="2023-01-05", range=False, tit...
Test that extra arguments correctly override defaults.
test_datepicker_build_with_description
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_components/form/test_date_picker.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_components/form/test_date_picker.py
Apache-2.0
def test_dropdown_build_with_extra(self): """Test that extra arguments correctly override defaults.""" dropdown = Dropdown( options=["A", "B", "C"], title="Title", id="dropdown_id", extra={ "clearable": True, "optionHeight":...
Test that extra arguments correctly override defaults.
test_dropdown_build_with_extra
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_components/form/test_dropdown.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_components/form/test_dropdown.py
Apache-2.0
def test_radio_items_build_with_extra(self): """Test that extra arguments correctly override defaults.""" radio_items = RadioItems( id="radio_items", options=["A", "B", "C"], title="Title", extra={ "inline": True, "id": "ove...
Test that extra arguments correctly override defaults.
test_radio_items_build_with_extra
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_components/form/test_radio_items.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_components/form/test_radio_items.py
Apache-2.0
def test_range_slider_build_with_extra(self, expected_range_slider_with_extra): """Test that extra arguments correctly override defaults.""" range_slider = vm.RangeSlider( id="range_slider", min=0.0, max=10.0, step=2, marks={1: "1", 5: "5", 10:...
Test that extra arguments correctly override defaults.
test_range_slider_build_with_extra
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_components/form/test_range_slider.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_components/form/test_range_slider.py
Apache-2.0
def test_range_slider_build_with_description(self, expected_range_slider_with_description): """Test that description arguments correctly builds icon and tooltip.""" range_slider = vm.RangeSlider( id="range_slider", min=0.0, max=10.0, step=2, ma...
Test that description arguments correctly builds icon and tooltip.
test_range_slider_build_with_description
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_components/form/test_range_slider.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_components/form/test_range_slider.py
Apache-2.0
def test_slider_build_with_extra(self, expected_slider_extra): """Test that extra arguments correctly override defaults.""" slider = vm.Slider( id="slider_id", min=0, max=10, step=1, value=5, title="Title", extra={ ...
Test that extra arguments correctly override defaults.
test_slider_build_with_extra
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_components/form/test_slider.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_components/form/test_slider.py
Apache-2.0
def managers_one_page_two_graphs(gapminder): """Instantiates a simple model_manager and data_manager with a page, and two graph models and gapminder data.""" vm.Page( id="test_page", title="My first dashboard", components=[ vm.Graph(id="scatter_chart", figure=px.scatter(gapmi...
Instantiates a simple model_manager and data_manager with a page, and two graph models and gapminder data.
managers_one_page_two_graphs
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_controls/conftest.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_controls/conftest.py
Apache-2.0
def managers_one_page_container_controls(gapminder): """Instantiates a simple model_manager and data_manager with a page, and two graph models and gapminder data.""" vm.Page( id="test_container", title="My first dashboard", components=[ vm.Container( title="",...
Instantiates a simple model_manager and data_manager with a page, and two graph models and gapminder data.
managers_one_page_container_controls
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_controls/conftest.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_controls/conftest.py
Apache-2.0
def managers_one_page_container_controls_invalid(gapminder): """Instantiates a simple model_manager and data_manager with a page, and two graph models and gapminder data.""" vm.Page( id="test_container", title="My first dashboard", components=[ vm.Container( i...
Instantiates a simple model_manager and data_manager with a page, and two graph models and gapminder data.
managers_one_page_container_controls_invalid
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_controls/conftest.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_controls/conftest.py
Apache-2.0
def managers_column_different_type(): """Instantiates the managers with a page and two graphs sharing the same column but of different data types.""" df_numerical = pd.DataFrame({"shared_column": [1]}) df_temporal = pd.DataFrame({"shared_column": [datetime(2024, 1, 1)]}) df_categorical = pd.DataFrame({"...
Instantiates the managers with a page and two graphs sharing the same column but of different data types.
managers_column_different_type
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_controls/test_filter.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_controls/test_filter.py
Apache-2.0
def managers_column_only_exists_in_some(): """Dataframes with column_numerical and column_categorical, which can be different lengths.""" vm.Page( id="test_page", title="Page Title", components=[ vm.Graph(id="column_numerical_exists_1", figure=px.scatter(pd.DataFrame({"column...
Dataframes with column_numerical and column_categorical, which can be different lengths.
managers_column_only_exists_in_some
python
mckinsey/vizro
vizro-core/tests/unit/vizro/models/_controls/test_filter.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tests/unit/vizro/models/_controls/test_filter.py
Apache-2.0
def fetch_extracted_url(source_url: str, pattern: str, headers: dict[str, str]) -> bytes: """Look at the file at source_url, search for pattern and then download `url_to_download`.""" response = requests.get(source_url, timeout=TIMEOUT, headers=headers) response.raise_for_status() match = re.search(pat...
Look at the file at source_url, search for pattern and then download `url_to_download`.
fetch_extracted_url
python
mckinsey/vizro
vizro-core/tools/download_static_files.py
https://github.com/mckinsey/vizro/blob/master/vizro-core/tools/download_static_files.py
Apache-2.0
def get_sample_data_info(data_name: Literal["iris", "tips", "stocks", "gapminder"]) -> DFMetaData: """If user provides no data, use this tool to get sample data information. Use the following data for the below purposes: - iris: mostly numerical with one categorical column, good for scatter, histogram,...
If user provides no data, use this tool to get sample data information. Use the following data for the below purposes: - iris: mostly numerical with one categorical column, good for scatter, histogram, boxplot, etc. - tips: contains mix of numerical and categorical columns, good for bar, pie, etc. ...
get_sample_data_info
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/server.py
Apache-2.0
def validate_model_config( dashboard_config: dict[str, Any], data_infos: list[DFMetaData], # Should be Optional[..]=None, but Cursor complains.. auto_open: bool = True, ) -> ValidationResults: """Validate Vizro model configuration. Run ALWAYS when you have a complete dashboard configuration. If su...
Validate Vizro model configuration. Run ALWAYS when you have a complete dashboard configuration. If successful, the tool will return the python code and, if it is a remote file, the py.cafe link to the chart. The PyCafe link will be automatically opened in your default browser if auto_open is True. Args: ...
validate_model_config
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/server.py
Apache-2.0
def get_model_json_schema(model_name: str) -> dict[str, Any]: """Get the JSON schema for the specified Vizro model. Args: model_name: Name of the Vizro model to get schema for (e.g., 'Card', 'Dashboard', 'Page') Returns: JSON schema of the requested Vizro model """ # Dictionary map...
Get the JSON schema for the specified Vizro model. Args: model_name: Name of the Vizro model to get schema for (e.g., 'Card', 'Dashboard', 'Page') Returns: JSON schema of the requested Vizro model
get_model_json_schema
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/server.py
Apache-2.0
def get_vizro_chart_or_dashboard_plan(user_plan: Literal["chart", "dashboard"]) -> str: """Get instructions for creating a Vizro chart or dashboard. Call FIRST when asked to create Vizro things.""" if user_plan == "chart": return """ IMPORTANT: - KEEP IT SIMPLE: rather than iterating yourself, ask t...
Get instructions for creating a Vizro chart or dashboard. Call FIRST when asked to create Vizro things.
get_vizro_chart_or_dashboard_plan
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/server.py
Apache-2.0
def load_and_analyze_data(path_or_url: str) -> DataAnalysisResults: """Load data from various file formats into a pandas DataFrame and analyze its structure. Supported formats: - CSV (.csv) - JSON (.json) - HTML (.html, .htm) - Excel (.xls, .xlsx) - OpenDocument Spreadsheet (.ods) - Par...
Load data from various file formats into a pandas DataFrame and analyze its structure. Supported formats: - CSV (.csv) - JSON (.json) - HTML (.html, .htm) - Excel (.xls, .xlsx) - OpenDocument Spreadsheet (.ods) - Parquet (.parquet) Args: path_or_url: Local file path or URL to a...
load_and_analyze_data
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/server.py
Apache-2.0
def create_starter_dashboard(): """Prompt template for getting started with Vizro.""" content = f""" Create a super simple Vizro dashboard with one page and one chart and one filter: - No need to call any tools except for validate_model_config - Call this tool with the precise config as shown below - The PyCafe...
Prompt template for getting started with Vizro.
create_starter_dashboard
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/server.py
Apache-2.0
def create_eda_dashboard( file_path_or_url: str, ) -> str: """Prompt template for creating an EDA dashboard based on one dataset.""" content = f""" Create an EDA dashboard based on the following dataset:{file_path_or_url}. Proceed as follows: 1. Analyze the data using the load_and_analyze_data tool first, p...
Prompt template for creating an EDA dashboard based on one dataset.
create_eda_dashboard
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/server.py
Apache-2.0
def validate_chart_code( chart_config: ChartPlan, data_info: DFMetaData, auto_open: bool = True, ) -> ValidationResults: """Validate the chart code created by the user and optionally open the PyCafe link in a browser. Args: chart_config: A ChartPlan object with the chart configuration ...
Validate the chart code created by the user and optionally open the PyCafe link in a browser. Args: chart_config: A ChartPlan object with the chart configuration data_info: Metadata for the dataset to be used in the chart auto_open: Whether to automatically open the PyCafe link in a browser...
validate_chart_code
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/server.py
Apache-2.0
def create_vizro_chart( chart_type: str, file_path_or_url: Optional[str] = None, ) -> str: """Prompt template for creating a Vizro chart.""" content = f""" - Create a chart using the following chart type: {chart_type}. - You MUST name the function containing the fig `custom_chart` - Make sure to anal...
Prompt template for creating a Vizro chart.
create_vizro_chart
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/server.py
Apache-2.0
def main(): """Run the Vizro MCP server - makes charts and dashboards available to AI assistants.""" # Configure logging to show warnings by default logging.basicConfig(level=logging.WARNING, stream=sys.stderr) # Run the MCP server mcp.run()
Run the Vizro MCP server - makes charts and dashboards available to AI assistants.
main
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/__init__.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/__init__.py
Apache-2.0
def _strip_markdown(code_string: str) -> str: """Remove any code block wrappers (markdown or triple quotes).""" wrappers = [("```python\n", "```"), ("```py\n", "```"), ("```\n", "```"), ('"""', '"""'), ("'''", "'''")] for start, end in wrappers: if code_string.startswith(start) and code_string.ends...
Remove any code block wrappers (markdown or triple quotes).
_strip_markdown
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/_schemas/schemas.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/_schemas/schemas.py
Apache-2.0
def get_dashboard_template(self, data_info: DFMetaData) -> str: """Create a simple dashboard template for displaying the chart. Args: data_info: The metadata of the dataset to use. Returns: Complete Python code for a Vizro dashboard displaying the chart. """ ...
Create a simple dashboard template for displaying the chart. Args: data_info: The metadata of the dataset to use. Returns: Complete Python code for a Vizro dashboard displaying the chart.
get_dashboard_template
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/_schemas/schemas.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/_schemas/schemas.py
Apache-2.0
def get_overview_vizro_models() -> dict[str, list[dict[str, str]]]: """Get all available models in the vizro.models namespace. Returns: Dictionary with categories of models and their descriptions """ result: dict[str, list[dict[str, str]]] = {} for category, models_list in MODEL_GROUPS.item...
Get all available models in the vizro.models namespace. Returns: Dictionary with categories of models and their descriptions
get_overview_vizro_models
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/_schemas/schemas.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/_schemas/schemas.py
Apache-2.0
def convert_github_url_to_raw(path_or_url: str) -> str: """Convert a GitHub URL to a raw URL if it's a GitHub URL, otherwise return the original path or URL.""" github_pattern = r"https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/(?:blob|raw)/([^/]+)/(.+)" github_match = re.match(github_pattern, path_or_url) ...
Convert a GitHub URL to a raw URL if it's a GitHub URL, otherwise return the original path or URL.
convert_github_url_to_raw
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/_utils/utils.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/_utils/utils.py
Apache-2.0
def load_dataframe_by_format( path_or_url: Union[str, Path], mime_type: Optional[str] = None ) -> tuple[pd.DataFrame, Literal["pd.read_csv", "pd.read_json", "pd.read_html", "pd.read_excel", "pd.read_parquet"]]: """Load a dataframe based on file format determined by MIME type or file extension.""" file_path_...
Load a dataframe based on file format determined by MIME type or file extension.
load_dataframe_by_format
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/_utils/utils.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/_utils/utils.py
Apache-2.0
def path_or_url_check(string: str) -> str: """Check if a string is a link or a file path.""" if string.startswith(("http://", "https://", "www.")): return "remote" if Path(string).is_file(): return "local" return "invalid"
Check if a string is a link or a file path.
path_or_url_check
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/_utils/utils.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/_utils/utils.py
Apache-2.0
def create_pycafe_url(python_code: str) -> str: """Create a PyCafe URL for a given Python code.""" # Create JSON object for py.cafe json_object = { "code": python_code, "requirements": "vizro==0.1.38", "files": [], } # Convert to compressed base64 URL json_text = json.du...
Create a PyCafe URL for a given Python code.
create_pycafe_url
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/_utils/utils.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/_utils/utils.py
Apache-2.0
def get_python_code_and_preview_link( model_object: vm.VizroBaseModel, data_infos: list[DFMetaData] ) -> VizroCodeAndPreviewLink: """Get the Python code and preview link for a Vizro model object.""" # Get the Python code python_code = model_object._to_python() # Add imports after the first empty li...
Get the Python code and preview link for a Vizro model object.
get_python_code_and_preview_link
python
mckinsey/vizro
vizro-mcp/src/vizro_mcp/_utils/utils.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/_utils/utils.py
Apache-2.0
def dashboard_config_validation_result() -> ValidationResults: """Fixture for a dashboard configuration validation result.""" return ValidationResults( valid=True, message="Configuration is valid for Dashboard!", python_code="""############ Imports ############## import vizro.models as v...
Fixture for a dashboard configuration validation result.
dashboard_config_validation_result
python
mckinsey/vizro
vizro-mcp/tests/unit/vizro_mcp/test_server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py
Apache-2.0
def graph_dashboard_config() -> dict[str, Any]: """Fixture for a dashboard configuration with a scatter graph.""" return { "title": "Graph Dashboard", "pages": [ { "id": "graph_page", "title": "Scatter Graph Page", "components": [ ...
Fixture for a dashboard configuration with a scatter graph.
graph_dashboard_config
python
mckinsey/vizro
vizro-mcp/tests/unit/vizro_mcp/test_server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py
Apache-2.0
def graph_dashboard_validation_result() -> ValidationResults: """Fixture for a dashboard configuration with graph validation result.""" return ValidationResults( valid=True, message="Configuration is valid for Dashboard!", python_code="""############ Imports ############## import vizro.p...
Fixture for a dashboard configuration with graph validation result.
graph_dashboard_validation_result
python
mckinsey/vizro
vizro-mcp/tests/unit/vizro_mcp/test_server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py
Apache-2.0
def invalid_chart_plan() -> dict[str, Any]: """Fixture for an invalid chart plan.""" return { "chart_type": "scatter", "imports": ["import pandas as pd", "import plotly.express as px"], "chart_code": """def scatter_chart(data_frame): return px.scatter(data_frame, x="sepal_length"...
Fixture for an invalid chart plan.
invalid_chart_plan
python
mckinsey/vizro
vizro-mcp/tests/unit/vizro_mcp/test_server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py
Apache-2.0
def chart_plan_validation_result() -> ValidationResults: """Fixture for a chart plan validation result.""" return ValidationResults( valid=True, message="Chart only dashboard created successfully!", python_code="""@capture('graph') def custom_chart(data_frame): return px.scatter(...
Fixture for a chart plan validation result.
chart_plan_validation_result
python
mckinsey/vizro
vizro-mcp/tests/unit/vizro_mcp/test_server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py
Apache-2.0
def test_successful_validation( self, valid_dashboard_config: dict[str, Any], dashboard_config_validation_result: ValidationResults ) -> None: """Test successful validation of a dashboard configuration.""" result = validate_model_config(dashboard_config=valid_dashboard_config, data_infos=[],...
Test successful validation of a dashboard configuration.
test_successful_validation
python
mckinsey/vizro
vizro-mcp/tests/unit/vizro_mcp/test_server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py
Apache-2.0
def test_graph_dashboard_validation( self, graph_dashboard_config: dict[str, Any], graph_dashboard_validation_result: ValidationResults, iris_metadata: DFMetaData, ) -> None: """Test validation of a dashboard with a scatter graph component.""" result = validate_model_...
Test validation of a dashboard with a scatter graph component.
test_graph_dashboard_validation
python
mckinsey/vizro
vizro-mcp/tests/unit/vizro_mcp/test_server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py
Apache-2.0
def test_validation_error(self, valid_dashboard_config: dict[str, Any], iris_metadata: DFMetaData) -> None: """Test validation error for an invalid dashboard configuration.""" # Create an invalid config by removing a required field invalid_config = valid_dashboard_config.copy() invalid_c...
Test validation error for an invalid dashboard configuration.
test_validation_error
python
mckinsey/vizro
vizro-mcp/tests/unit/vizro_mcp/test_server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py
Apache-2.0
def test_successful_validation( self, valid_chart_plan: dict[str, Any], iris_metadata: DFMetaData, chart_plan_validation_result: ValidationResults, ) -> None: """Test successful validation of chart code.""" result = validate_chart_code(chart_config=valid_chart_plan, d...
Test successful validation of chart code.
test_successful_validation
python
mckinsey/vizro
vizro-mcp/tests/unit/vizro_mcp/test_server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py
Apache-2.0
def test_validation_error( self, invalid_chart_plan: dict[str, Any], iris_metadata: DFMetaData, ) -> None: """Test validation error for an invalid chart plan.""" result = validate_chart_code(chart_config=invalid_chart_plan, data_info=iris_metadata, auto_open=False) a...
Test validation error for an invalid chart plan.
test_validation_error
python
mckinsey/vizro
vizro-mcp/tests/unit/vizro_mcp/test_server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py
Apache-2.0
def test_model_json_schema(self, model_name: str, model_class: type) -> None: """Test getting JSON schema for various models.""" schema = get_model_json_schema(model_name=model_name) # Get the schema directly from the model class expected_schema = model_class.model_json_schema() ...
Test getting JSON schema for various models.
test_model_json_schema
python
mckinsey/vizro
vizro-mcp/tests/unit/vizro_mcp/test_server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py
Apache-2.0
def test_nonexistent_model(self) -> None: """Test getting schema for a nonexistent model.""" schema = get_model_json_schema("NonExistentModel") assert isinstance(schema, dict) assert "error" in schema assert "not found" in schema["error"]
Test getting schema for a nonexistent model.
test_nonexistent_model
python
mckinsey/vizro
vizro-mcp/tests/unit/vizro_mcp/test_server.py
https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py
Apache-2.0
def setup(self) -> None: """Load the model into memory to make running multiple predictions efficient""" # Download the model weights if not os.path.exists(MODEL_CACHE): download_weights(MODEL_URL, MODEL_CACHE) # Soft links for the auxiliary models os.system("mkdir -...
Load the model into memory to make running multiple predictions efficient
setup
python
bytedance/LatentSync
predict.py
https://github.com/bytedance/LatentSync/blob/master/predict.py
Apache-2.0
def predict( self, video: Path = Input(description="Input video", default=None), audio: Path = Input(description="Input audio to ", default=None), guidance_scale: float = Input(description="Guidance scale", ge=1, le=3, default=2.0), inference_steps: int = Input(description="Infer...
Run a single prediction on the model
predict
python
bytedance/LatentSync
predict.py
https://github.com/bytedance/LatentSync/blob/master/predict.py
Apache-2.0
def resnet50_backbone(lda_out_channels, in_chn, pretrained=False, **kwargs): """Constructs a ResNet-50 model_hyper. Args: pretrained (bool): If True, returns a model_hyper pre-trained on ImageNet """ model = ResNetBackbone(lda_out_channels, in_chn, Bottleneck, [3, 4, 6, 3], **kwargs) if pre...
Constructs a ResNet-50 model_hyper. Args: pretrained (bool): If True, returns a model_hyper pre-trained on ImageNet
resnet50_backbone
python
bytedance/LatentSync
eval/hyper_iqa.py
https://github.com/bytedance/LatentSync/blob/master/eval/hyper_iqa.py
Apache-2.0
def nms_(dets, thresh): """ Courtesy of Ross Girshick [https://github.com/rbgirshick/py-faster-rcnn/blob/master/lib/nms/py_cpu_nms.py] """ x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] areas = (x2 - x1) * (y2 - y1) order = scores.argsort...
Courtesy of Ross Girshick [https://github.com/rbgirshick/py-faster-rcnn/blob/master/lib/nms/py_cpu_nms.py]
nms_
python
bytedance/LatentSync
eval/detectors/s3fd/box_utils.py
https://github.com/bytedance/LatentSync/blob/master/eval/detectors/s3fd/box_utils.py
Apache-2.0
def decode(loc, priors, variances): """Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc (tensor): location predictions for loc layers, Shape: [num_priors,4] priors (tensor): Prior boxes in center-offset form...
Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc (tensor): location predictions for loc layers, Shape: [num_priors,4] priors (tensor): Prior boxes in center-offset form. Shape: [num_priors,4]. ...
decode
python
bytedance/LatentSync
eval/detectors/s3fd/box_utils.py
https://github.com/bytedance/LatentSync/blob/master/eval/detectors/s3fd/box_utils.py
Apache-2.0
def nms(boxes, scores, overlap=0.5, top_k=200): """Apply non-maximum suppression at test time to avoid detecting too many overlapping bounding boxes for a given object. Args: boxes: (tensor) The location preds for the img, Shape: [num_priors,4]. scores: (tensor) The class predscores for the ...
Apply non-maximum suppression at test time to avoid detecting too many overlapping bounding boxes for a given object. Args: boxes: (tensor) The location preds for the img, Shape: [num_priors,4]. scores: (tensor) The class predscores for the img, Shape:[num_priors]. overlap: (float) The o...
nms
python
bytedance/LatentSync
eval/detectors/s3fd/box_utils.py
https://github.com/bytedance/LatentSync/blob/master/eval/detectors/s3fd/box_utils.py
Apache-2.0
def set_attention_slice(self, slice_size): r""" Enable sliced attention computation. When this option is enabled, the attention module will split the input tensor in slices, to compute attention in several steps. This is useful to save some memory in exchange for a small speed decrease....
Enable sliced attention computation. When this option is enabled, the attention module will split the input tensor in slices, to compute attention in several steps. This is useful to save some memory in exchange for a small speed decrease. Args: slice_size (`str` or `int` ...
set_attention_slice
python
bytedance/LatentSync
latentsync/models/unet.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/models/unet.py
Apache-2.0
def forward( self, sample: torch.FloatTensor, timestep: Union[torch.Tensor, float, int], encoder_hidden_states: torch.Tensor = None, class_labels: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, # support controlnet down_block...
Args: sample (`torch.FloatTensor`): (batch, channel, height, width) noisy inputs tensor timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states ...
forward
python
bytedance/LatentSync
latentsync/models/unet.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/models/unet.py
Apache-2.0
def get_random_clip_from_video(self, idx: int) -> tuple: ''' Sample a random clip starting index from the video. Args: idx: Index of the video. ''' # Note that some videos may not contain enough frames, we skip those videos here. while self._clips.clips[idx]....
Sample a random clip starting index from the video. Args: idx: Index of the video.
get_random_clip_from_video
python
bytedance/LatentSync
latentsync/trepa/utils/data_utils.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/data_utils.py
Apache-2.0
def load_video_frames(self, dataroot: str) -> list: ''' Loads all the video frames under the dataroot and returns a list of all the video frames. Args: dataroot: The root directory containing the video frames. Returns: A list of all the video frames. ''...
Loads all the video frames under the dataroot and returns a list of all the video frames. Args: dataroot: The root directory containing the video frames. Returns: A list of all the video frames.
load_video_frames
python
bytedance/LatentSync
latentsync/trepa/utils/data_utils.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/data_utils.py
Apache-2.0
def getTensor(self, index: int) -> torch.Tensor: ''' Returns a tensor of the video frames at the given index. Args: index: The index of the video frames to return. Returns: A BCTHW tensor in the range `[0, 1]` of the video frames at the given index. '''...
Returns a tensor of the video frames at the given index. Args: index: The index of the video frames to return. Returns: A BCTHW tensor in the range `[0, 1]` of the video frames at the given index.
getTensor
python
bytedance/LatentSync
latentsync/trepa/utils/data_utils.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/data_utils.py
Apache-2.0
def set_num_features(self, num_features: int): ''' Set the number of features diminsions. Args: num_features: Number of features diminsions. ''' if self.num_features is not None: assert num_features == self.num_features else: self.num_...
Set the number of features diminsions. Args: num_features: Number of features diminsions.
set_num_features
python
bytedance/LatentSync
latentsync/trepa/utils/metric_utils.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/metric_utils.py
Apache-2.0
def append(self, x: np.ndarray): ''' Add the newly computed features to the list. Update the mean and covariance. Args: x: New features to record. ''' x = np.asarray(x, dtype=np.float32) assert x.ndim == 2 if (self.max_items is not None) and (self.num...
Add the newly computed features to the list. Update the mean and covariance. Args: x: New features to record.
append
python
bytedance/LatentSync
latentsync/trepa/utils/metric_utils.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/metric_utils.py
Apache-2.0
def append_torch(self, x: torch.Tensor, rank: int, num_gpus: int): ''' Add the newly computed PyTorch features to the list. Update the mean and covariance. Args: x: New features to record. rank: Rank of the current GPU. num_gpus: Total number of GPUs. ...
Add the newly computed PyTorch features to the list. Update the mean and covariance. Args: x: New features to record. rank: Rank of the current GPU. num_gpus: Total number of GPUs.
append_torch
python
bytedance/LatentSync
latentsync/trepa/utils/metric_utils.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/metric_utils.py
Apache-2.0
def get_all(self) -> np.ndarray: ''' Get all the stored features as NumPy Array. Returns: Concatenation of the stored features. ''' assert self.capture_all return np.concatenate(self.all_features, axis=0)
Get all the stored features as NumPy Array. Returns: Concatenation of the stored features.
get_all
python
bytedance/LatentSync
latentsync/trepa/utils/metric_utils.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/metric_utils.py
Apache-2.0
def get_mean_cov(self) -> Tuple[np.ndarray, np.ndarray]: ''' Get the mean and covariance of the stored features. Returns: Mean and covariance of the stored features. ''' assert self.capture_mean_cov mean = self.raw_mean / self.num_items cov = self.raw...
Get the mean and covariance of the stored features. Returns: Mean and covariance of the stored features.
get_mean_cov
python
bytedance/LatentSync
latentsync/trepa/utils/metric_utils.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/metric_utils.py
Apache-2.0
def load(pkl_file: str) -> 'FeatureStats': ''' Load the features and statistics from a pickle file. Args: pkl_file: Path to the pickle file. ''' with open(pkl_file, 'rb') as f: s = pickle.load(f) obj = FeatureStats(capture_all=s['capture_all'], ma...
Load the features and statistics from a pickle file. Args: pkl_file: Path to the pickle file.
load
python
bytedance/LatentSync
latentsync/trepa/utils/metric_utils.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/metric_utils.py
Apache-2.0
def num_frames(length, fsize, fshift): """Compute number of time frames of spectrogram""" pad = fsize - fshift if length % fshift == 0: M = (length + pad * 2 - fsize) // fshift + 1 else: M = (length + pad * 2 - fsize) // fshift + 2 return M
Compute number of time frames of spectrogram
num_frames
python
bytedance/LatentSync
latentsync/utils/audio.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/utils/audio.py
Apache-2.0
def __getitem__(self, idx): """Get audio samples and video frame at `idx`. Parameters ---------- idx : int or slice The frame index, can be negative which means it will index backwards, or slice of frame indices. Returns ------- (ndarray/...
Get audio samples and video frame at `idx`. Parameters ---------- idx : int or slice The frame index, can be negative which means it will index backwards, or slice of frame indices. Returns ------- (ndarray/list of ndarray, ndarray) F...
__getitem__
python
bytedance/LatentSync
latentsync/utils/av_reader.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/utils/av_reader.py
Apache-2.0
def get_batch(self, indices): """Get entire batch of audio samples and video frames. Parameters ---------- indices : list of integers A list of frame indices. If negative indices detected, the indices will be indexed from backward Returns ------- (lis...
Get entire batch of audio samples and video frames. Parameters ---------- indices : list of integers A list of frame indices. If negative indices detected, the indices will be indexed from backward Returns ------- (list of ndarray, ndarray) First ...
get_batch
python
bytedance/LatentSync
latentsync/utils/av_reader.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/utils/av_reader.py
Apache-2.0
def _validate_indices(self, indices): """Validate int64 integers and convert negative integers to positive by backward search""" assert self.__video_reader is not None and self.__audio_reader is not None indices = np.array(indices, dtype=np.int64) # process negative indices indic...
Validate int64 integers and convert negative integers to positive by backward search
_validate_indices
python
bytedance/LatentSync
latentsync/utils/av_reader.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/utils/av_reader.py
Apache-2.0
def cuda_to_int(cuda_str: str) -> int: """ Convert the string with format "cuda:X" to integer X. """ if cuda_str == "cuda": return 0 device = torch.device(cuda_str) if device.type != "cuda": raise ValueError(f"Device type must be 'cuda', got: {device.type}") return device.ind...
Convert the string with format "cuda:X" to integer X.
cuda_to_int
python
bytedance/LatentSync
latentsync/utils/face_detector.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/utils/face_detector.py
Apache-2.0
def get_sliced_feature(self, feature_array, vid_idx, fps=25): """ Get sliced features based on a given index :param feature_array: :param start_idx: the start index of the feature :param audio_feat_length: :return: """ length = len(feature_array) s...
Get sliced features based on a given index :param feature_array: :param start_idx: the start index of the feature :param audio_feat_length: :return:
get_sliced_feature
python
bytedance/LatentSync
latentsync/whisper/audio2feature.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/audio2feature.py
Apache-2.0
def get_sliced_feature_sparse(self, feature_array, vid_idx, fps=25): """ Get sliced features based on a given index :param feature_array: :param start_idx: the start index of the feature :param audio_feat_length: :return: """ length = len(feature_array) ...
Get sliced features based on a given index :param feature_array: :param start_idx: the start index of the feature :param audio_feat_length: :return:
get_sliced_feature_sparse
python
bytedance/LatentSync
latentsync/whisper/audio2feature.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/audio2feature.py
Apache-2.0
def load_audio(file: str, sr: int = SAMPLE_RATE): """ Open an audio file and read as mono waveform, resampling as necessary Parameters ---------- file: str The audio file to open sr: int The sample rate to resample the audio if necessary Returns ------- A NumPy arr...
Open an audio file and read as mono waveform, resampling as necessary Parameters ---------- file: str The audio file to open sr: int The sample rate to resample the audio if necessary Returns ------- A NumPy array containing the audio waveform, in float32 dtype.
load_audio
python
bytedance/LatentSync
latentsync/whisper/whisper/audio.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/whisper/audio.py
Apache-2.0
def pad_or_trim(array, length: int = N_SAMPLES, *, axis: int = -1): """ Pad or trim the audio array to N_SAMPLES, as expected by the encoder. """ if torch.is_tensor(array): if array.shape[axis] > length: array = array.index_select(dim=axis, index=torch.arange(length)) if arr...
Pad or trim the audio array to N_SAMPLES, as expected by the encoder.
pad_or_trim
python
bytedance/LatentSync
latentsync/whisper/whisper/audio.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/whisper/audio.py
Apache-2.0
def mel_filters(device, n_mels: int = N_MELS) -> torch.Tensor: """ load the mel filterbank matrix for projecting STFT into a Mel spectrogram. Allows decoupling librosa dependency; saved using: np.savez_compressed( "mel_filters.npz", mel_80=librosa.filters.mel(sr=16000, n_fft...
load the mel filterbank matrix for projecting STFT into a Mel spectrogram. Allows decoupling librosa dependency; saved using: np.savez_compressed( "mel_filters.npz", mel_80=librosa.filters.mel(sr=16000, n_fft=400, n_mels=80), )
mel_filters
python
bytedance/LatentSync
latentsync/whisper/whisper/audio.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/whisper/audio.py
Apache-2.0
def log_mel_spectrogram(audio: Union[str, np.ndarray, torch.Tensor], n_mels: int = N_MELS): """ Compute the log-Mel spectrogram of Parameters ---------- audio: Union[str, np.ndarray, torch.Tensor], shape = (*) The path to audio or either a NumPy array or Tensor containing the audio waveform...
Compute the log-Mel spectrogram of Parameters ---------- audio: Union[str, np.ndarray, torch.Tensor], shape = (*) The path to audio or either a NumPy array or Tensor containing the audio waveform in 16 kHz n_mels: int The number of Mel-frequency filters, only 80 is supported ...
log_mel_spectrogram
python
bytedance/LatentSync
latentsync/whisper/whisper/audio.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/whisper/audio.py
Apache-2.0
def detect_language(model: "Whisper", mel: Tensor, tokenizer: Tokenizer = None) -> Tuple[Tensor, List[dict]]: """ Detect the spoken language in the audio, and return them as list of strings, along with the ids of the most probable language tokens and the probability distribution over all language tokens. ...
Detect the spoken language in the audio, and return them as list of strings, along with the ids of the most probable language tokens and the probability distribution over all language tokens. This is performed outside the main decode loop in order to not interfere with kv-caching. Returns ------- ...
detect_language
python
bytedance/LatentSync
latentsync/whisper/whisper/decoding.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/whisper/decoding.py
Apache-2.0
def finalize( self, tokens: Tensor, sum_logprobs: Tensor ) -> Tuple[Sequence[Sequence[Tensor]], List[List[float]]]: """Finalize search and return the final candidate sequences Parameters ---------- tokens : Tensor, shape = (n_audio, n_group, current_sequence_length) ...
Finalize search and return the final candidate sequences Parameters ---------- tokens : Tensor, shape = (n_audio, n_group, current_sequence_length) all tokens in the context so far, including the prefix and sot_sequence sum_logprobs : Tensor, shape = (n_audio, n_group) ...
finalize
python
bytedance/LatentSync
latentsync/whisper/whisper/decoding.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/whisper/decoding.py
Apache-2.0
def decode(model: "Whisper", mel: Tensor, options: DecodingOptions = DecodingOptions()) -> Union[DecodingResult, List[DecodingResult]]: """ Performs decoding of 30-second audio segment(s), provided as Mel spectrogram(s). Parameters ---------- model: Whisper the Whisper model instance m...
Performs decoding of 30-second audio segment(s), provided as Mel spectrogram(s). Parameters ---------- model: Whisper the Whisper model instance mel: torch.Tensor, shape = (80, 3000) or (*, 80, 3000) A tensor containing the Mel spectrogram(s) options: DecodingOptions ...
decode
python
bytedance/LatentSync
latentsync/whisper/whisper/decoding.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/whisper/decoding.py
Apache-2.0