Skip to content

Commit

Permalink
Merge pull request #74 from Kludex/refactor/print-multiline
Browse files Browse the repository at this point in the history
refactor: improve code readability on kloppy-query cli
  • Loading branch information
koenvo authored Nov 11, 2020
2 parents 0a4bde5 + 1398f80 commit e9478da
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 49 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ env
.ipynb_checkpoints
.DS_Store
kloppy/.DS_Store

# Downloaded data files
examples/pattern_matching/repository/*.json
12 changes: 6 additions & 6 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,14 @@ Other pull requests merged:

- Code formatting & typos in docs ([#39](https://github.com/PySport/kloppy/pull/39), [#40](https://github.com/PySport/kloppy/pull/40))
- Add Metrica Json event serializer ([#44](https://github.com/PySport/kloppy/pull/44))
- Infer ball_owning_team from Opta events ([#49](https://github.com/PySport/kloppy/pull/49)
- Infer ball_owning_team from Opta events ([#49](https://github.com/PySport/kloppy/pull/49)

## 1.0.0 (2020-07-26)
In this major release we introduce metadata. The metadata is part of a dataset and can be accessed via `Dataset.metadata`.
There are a couple of breaking changes:

1. All attributes except `records` / `frames` are moved from `Dataset` to `Metadata` class.
2. All `position` properties are renamed to `coordinates`.
1. All attributes except `records` / `frames` are moved from `Dataset` to `Metadata` class.
2. All `position` properties are renamed to `coordinates`.
3. The `players_coordinates` property is indexed by `Player` instances instead of by `jersey_number` strings.
4. On the `Event` class the `player_jersey_number` is replaced by `player` which is a `Player` instance.
5. `to_pandas` changes:
Expand Down Expand Up @@ -96,7 +96,7 @@ Other pull requests merged:
## 0.5.0 (2020-06-13)
- Add pattern matching based on regular expressions
- Add kloppy-query: command line tool to search for patterns

## 0.4.1 (2020-06-05)
- Fix for StatsBomb Serializer when location contains z coordinate

Expand All @@ -111,7 +111,7 @@ Other pull requests merged:
- Add FIFA EPTS Tracking Serializer
- Add some examples
- Add datasets loader to directly load dataset from your python code
- Add limit argument to all loaders
- Add limit argument to all loaders

## 0.2.1 (2020-05-12)
- Add some helpers functions to directly load a dataset by filenames
Expand All @@ -122,4 +122,4 @@ Other pull requests merged:
- Cleanup some import statements

## 0.1.0 (2020-04-23)
- Initial release (TRACAB)
- Initial release (TRACAB)
64 changes: 39 additions & 25 deletions kloppy/cmdline.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
import argparse
import sys
import logging
import sys
import textwrap
from collections import Counter
from dataclasses import dataclass
from typing import List

from xml.etree import ElementTree as ET

from kloppy import (
load_statsbomb_event_data,
load_opta_event_data,
event_pattern_matching as pm,
)
from kloppy import event_pattern_matching as pm
from kloppy import load_opta_event_data, load_statsbomb_event_data
from kloppy.utils import performance_logging

sys.path.append(".")
Expand Down Expand Up @@ -80,8 +77,7 @@ def run_query(argv=sys.argv[1:]):
help="StatsBomb event input files (events.json,lineup.json)",
)
parser.add_argument(
"--input-opta",
help="Opta event input files (f24.xml,f7.xml)",
"--input-opta", help="Opta event input files (f24.xml,f7.xml)"
)
parser.add_argument("--output-xml", help="Output file")
parser.add_argument(
Expand Down Expand Up @@ -206,23 +202,41 @@ def run_query(argv=sys.argv[1:]):
logger.info(f"Wrote {len(video_fragments)} video fragments to file")

if opts.stats == "text":
print("Home:")
print(f" total count: {counter['home_total']}")
print(
f" success: {counter['home_success']} ({counter['home_success'] / counter['home_total'] * 100:.0f}%)"
)
print(
f" no success: {counter['home_total'] - counter['home_success']} ({(counter['home_total'] - counter['home_success']) / counter['home_total'] * 100:.0f}%)"
)
print("")
print("Away:")
print(f" total count: {counter['away_total']}")
print(
f" success: {counter['away_success']} ({counter['away_success'] / counter['away_total'] * 100:.0f}%)"
)
print(
f" no success: {counter['away_total'] - counter['away_success']} ({(counter['away_total'] - counter['away_success']) / counter['away_total'] * 100:.0f}%)"
text_stats = """\
Home:
total count: {home_total}
success: {home_success} ({home_success_rate:.0f}%)
no success: {home_failure} ({home_failure_rate:.0f}%)
Away:
total count: {away_total}
success: {away_success} ({away_success_rate:.0f}%)
no success: {away_failure} ({away_failure_rate:.0f}%)
""".format(
home_total=counter["home_total"],
home_success=counter["home_success"],
home_success_rate=(
counter["home_success"] / counter["home_total"] * 100
),
home_failure=counter["home_total"] - counter["home_success"],
home_failure_rate=(
(counter["home_total"] - counter["home_success"])
/ counter["home_total"]
* 100
),
away_total=counter["away_total"],
away_success=counter["away_success"],
away_success_rate=(
counter["away_success"] / counter["away_total"] * 100
),
away_failure=counter["away_total"] - counter["away_success"],
away_failure_rate=(
(counter["away_total"] - counter["away_success"])
/ counter["away_total"]
* 100
),
)
print(textwrap.dedent(text_stats))
elif opts.stats == "json":
import json

Expand Down
30 changes: 14 additions & 16 deletions kloppy/helpers.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,28 @@
from typing import Callable, TypeVar, Dict, Union, List
from typing import Callable, Dict, List, TypeVar, Union

from . import (
TRACABSerializer,
MetricaTrackingSerializer,
MetricaEventsJsonSerializer,
EPTSSerializer,
StatsBombSerializer,
MetricaEventsJsonSerializer,
MetricaTrackingSerializer,
OptaSerializer,
StatsBombSerializer,
TRACABSerializer,
)
from .domain import (
CarryEvent,
DataRecord,
Dataset,
Frame,
Event,
TrackingDataset,
Transformer,
Orientation,
PitchDimensions,
Dimension,
Event,
EventDataset,
EventType,
Frame,
Orientation,
PassEvent,
CarryEvent,
PassResult,
EventType,
Player,
DataRecord,
SetPieceType,
PitchDimensions,
TrackingDataset,
Transformer,
)


Expand Down
4 changes: 2 additions & 2 deletions kloppy/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,13 @@ def performance_logging(description: str, counter: int = None, logger=None):
_all_cap_re = re.compile("([a-z0-9])([A-Z])")


def camelcase_to_snakecase(name):
def camelcase_to_snakecase(name: str) -> str:
"""Convert camel-case string to snake-case."""
s1 = _first_cap_re.sub(r"\1_\2", name)
return _all_cap_re.sub(r"\1_\2", s1).lower()


def removes_suffix(string, suffix):
def removes_suffix(string: str, suffix: str) -> str:
if string[-len(suffix) :] == suffix:
return string[: -len(suffix)]
else:
Expand Down

0 comments on commit e9478da

Please sign in to comment.