• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

IBM / unitxt / 12903822349

22 Jan 2025 08:07AM UTC coverage: 79.58%. Remained the same
12903822349

push

github

web-flow
Bugfix: indexed row major serialization fails with None cell values (#1540)

Bugfix: indexed row major table serialization fails if cell values are None

Signed-off-by: Yifan Mai <yifan@cs.stanford.edu>
Co-authored-by: Elron Bandel <elronbandel@gmail.com>

1395 of 1742 branches covered (80.08%)

Branch coverage included in aggregate %.

8827 of 11103 relevant lines covered (79.5%)

0.8 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.19
src/unitxt/struct_data_operators.py
1
"""This section describes unitxt operators for structured data.
2

3
These operators are specialized in handling structured data like tables.
4
For tables, expected input format is:
5

6
.. code-block:: text
7

8
    {
9
        "header": ["col1", "col2"],
10
        "rows": [["row11", "row12"], ["row21", "row22"], ["row31", "row32"]]
11
    }
12

13
For triples, expected input format is:
14

15
.. code-block:: text
16

17
    [[ "subject1", "relation1", "object1" ], [ "subject1", "relation2", "object2"]]
18

19
For key-value pairs, expected input format is:
20

21
.. code-block:: text
22

23
    {"key1": "value1", "key2": value2, "key3": "value3"}
24
"""
25

26
import json
1✔
27
import random
1✔
28
from abc import ABC, abstractmethod
1✔
29
from typing import (
1✔
30
    Any,
31
    Dict,
32
    List,
33
    Optional,
34
)
35

36
import pandas as pd
1✔
37

38
from .augmentors import TypeDependentAugmentor
1✔
39
from .dict_utils import dict_get
1✔
40
from .operators import FieldOperator, InstanceOperator
1✔
41
from .random_utils import new_random_generator
1✔
42
from .serializers import ImageSerializer, TableSerializer
1✔
43
from .types import Table
1✔
44
from .utils import recursive_copy
1✔
45

46

47
def shuffle_columns(table: Table, seed=0) -> Table:
1✔
48
    # extract header & rows from the dictionary
49
    header = table.get("header", [])
1✔
50
    rows = table.get("rows", [])
1✔
51
    # shuffle the indices first
52
    indices = list(range(len(header)))
1✔
53
    random_generator = new_random_generator({"table": table, "seed": seed})
1✔
54
    random_generator.shuffle(indices)
1✔
55

56
    # shuffle the header & rows based on that indices
57
    shuffled_header = [header[i] for i in indices]
1✔
58
    shuffled_rows = [[row[i] for i in indices] for row in rows]
1✔
59

60
    table["header"] = shuffled_header
1✔
61
    table["rows"] = shuffled_rows
1✔
62

63
    return table
1✔
64

65

66
def shuffle_rows(table: Table, seed=0) -> Table:
1✔
67
    # extract header & rows from the dictionary
68
    rows = table.get("rows", [])
1✔
69
    # shuffle rows
70
    random_generator = new_random_generator({"table": table, "seed": seed})
1✔
71
    random_generator.shuffle(rows)
1✔
72
    table["rows"] = rows
1✔
73

74
    return table
1✔
75

76

77
class SerializeTable(ABC, TableSerializer):
1✔
78
    """TableSerializer converts a given table into a flat sequence with special symbols.
79

80
    Output format varies depending on the chosen serializer. This abstract class defines structure of a typical table serializer that any concrete implementation should follow.
81
    """
82

83
    seed: int = 0
1✔
84
    shuffle_rows: bool = False
1✔
85
    shuffle_columns: bool = False
1✔
86

87
    def serialize(self, value: Table, instance: Dict[str, Any]) -> str:
1✔
88
        value = recursive_copy(value)
1✔
89
        if self.shuffle_columns:
1✔
90
            value = shuffle_columns(table=value, seed=self.seed)
1✔
91

92
        if self.shuffle_rows:
1✔
93
            value = shuffle_rows(table=value, seed=self.seed)
1✔
94

95
        return self.serialize_table(value)
1✔
96

97
    # main method to serialize a table
98
    @abstractmethod
1✔
99
    def serialize_table(self, table_content: Dict) -> str:
1✔
100
        pass
×
101

102
    # method to process table header
103
    def process_header(self, header: List):
1✔
104
        pass
×
105

106
    # method to process a table row
107
    def process_row(self, row: List, row_index: int):
1✔
108
        pass
×
109

110

111
# Concrete classes implementing table serializers
112
class SerializeTableAsIndexedRowMajor(SerializeTable):
1✔
113
    """Indexed Row Major Table Serializer.
114

115
    Commonly used row major serialization format.
116
    Format:  col : col1 | col2 | col 3 row 1 : val1 | val2 | val3 | val4 row 2 : val1 | ...
117
    """
118

119
    # main method that processes a table
120
    # table_content must be in the presribed input format
121
    def serialize_table(self, table_content: Dict) -> str:
1✔
122
        # Extract headers and rows from the dictionary
123
        header = table_content.get("header", [])
1✔
124
        rows = table_content.get("rows", [])
1✔
125

126
        assert header and rows, "Incorrect input table format"
1✔
127

128
        # Process table header first
129
        serialized_tbl_str = self.process_header(header) + " "
1✔
130

131
        # Process rows sequentially starting from row 1
132
        for i, row in enumerate(rows, start=1):
1✔
133
            serialized_tbl_str += self.process_row(row, row_index=i) + " "
1✔
134

135
        # return serialized table as a string
136
        return serialized_tbl_str.strip()
1✔
137

138
    # serialize header into a string containing the list of column names separated by '|' symbol
139
    def process_header(self, header: List):
1✔
140
        return "col : " + " | ".join(header)
1✔
141

142
    # serialize a table row into a string containing the list of cell values separated by '|'
143
    def process_row(self, row: List, row_index: int):
1✔
144
        serialized_row_str = ""
1✔
145
        row_cell_values = [
1✔
146
            str(value) if isinstance(value, (int, float)) else value for value in row
147
        ]
148
        serialized_row_str += " | ".join([str(value) for value in row_cell_values])
1✔
149

150
        return f"row {row_index} : {serialized_row_str}"
1✔
151

152

153
class SerializeTableAsMarkdown(SerializeTable):
1✔
154
    """Markdown Table Serializer.
155

156
    Markdown table format is used in GitHub code primarily.
157
    Format:
158

159
    .. code-block:: text
160

161
        |col1|col2|col3|
162
        |---|---|---|
163
        |A|4|1|
164
        |I|2|1|
165
        ...
166

167
    """
168

169
    # main method that serializes a table.
170
    # table_content must be in the presribed input format.
171
    def serialize_table(self, table_content: Dict) -> str:
1✔
172
        # Extract headers and rows from the dictionary
173
        header = table_content.get("header", [])
1✔
174
        rows = table_content.get("rows", [])
1✔
175

176
        assert header and rows, "Incorrect input table format"
1✔
177

178
        # Process table header first
179
        serialized_tbl_str = self.process_header(header)
1✔
180

181
        # Process rows sequentially starting from row 1
182
        for i, row in enumerate(rows, start=1):
1✔
183
            serialized_tbl_str += self.process_row(row, row_index=i)
1✔
184

185
        # return serialized table as a string
186
        return serialized_tbl_str.strip()
1✔
187

188
    # serialize header into a string containing the list of column names
189
    def process_header(self, header: List):
1✔
190
        header_str = "|{}|\n".format("|".join(header))
1✔
191
        header_str += "|{}|\n".format("|".join(["---"] * len(header)))
1✔
192
        return header_str
1✔
193

194
    # serialize a table row into a string containing the list of cell values
195
    def process_row(self, row: List, row_index: int):
1✔
196
        row_str = ""
1✔
197
        row_str += "|{}|\n".format("|".join(str(cell) for cell in row))
1✔
198
        return row_str
1✔
199

200

201
class SerializeTableAsDFLoader(SerializeTable):
1✔
202
    """DFLoader Table Serializer.
203

204
    Pandas dataframe based code snippet format serializer.
205
    Format(Sample):
206

207
    .. code-block:: python
208

209
        pd.DataFrame({
210
            "name" : ["Alex", "Diana", "Donald"],
211
            "age" : [26, 34, 39]
212
        },
213
        index=[0,1,2])
214
    """
215

216
    # main method that serializes a table.
217
    # table_content must be in the presribed input format.
218
    def serialize_table(self, table_content: Dict) -> str:
1✔
219
        # Extract headers and rows from the dictionary
220
        header = table_content.get("header", [])
1✔
221
        rows = table_content.get("rows", [])
1✔
222

223
        assert header and rows, "Incorrect input table format"
1✔
224

225
        # Fix duplicate columns, ensuring the first occurrence has no suffix
226
        header = [
1✔
227
            f"{col}_{header[:i].count(col)}" if header[:i].count(col) > 0 else col
228
            for i, col in enumerate(header)
229
        ]
230

231
        # Create a pandas DataFrame
232
        df = pd.DataFrame(rows, columns=header)
1✔
233

234
        # Generate output string in the desired format
235
        data_dict = df.to_dict(orient="list")
1✔
236

237
        return (
1✔
238
            "pd.DataFrame({\n"
239
            + json.dumps(data_dict)[1:-1]
240
            + "},\nindex="
241
            + str(list(range(len(rows))))
242
            + ")"
243
        )
244

245

246
class SerializeTableAsJson(SerializeTable):
1✔
247
    """JSON Table Serializer.
248

249
    Json format based serializer.
250
    Format(Sample):
251

252
    .. code-block:: json
253

254
        {
255
            "0":{"name":"Alex","age":26},
256
            "1":{"name":"Diana","age":34},
257
            "2":{"name":"Donald","age":39}
258
        }
259
    """
260

261
    # main method that serializes a table.
262
    # table_content must be in the presribed input format.
263
    def serialize_table(self, table_content: Dict) -> str:
1✔
264
        # Extract headers and rows from the dictionary
265
        header = table_content.get("header", [])
1✔
266
        rows = table_content.get("rows", [])
1✔
267

268
        assert header and rows, "Incorrect input table format"
1✔
269

270
        # Generate output dictionary
271
        output_dict = {}
1✔
272
        for i, row in enumerate(rows):
1✔
273
            output_dict[i] = {header[j]: value for j, value in enumerate(row)}
1✔
274

275
        # Convert dictionary to JSON string
276
        return json.dumps(output_dict)
1✔
277

278

279
class SerializeTableAsHTML(SerializeTable):
1✔
280
    """HTML Table Serializer.
281

282
    HTML table format used for rendering tables in web pages.
283
    Format(Sample):
284

285
    .. code-block:: html
286

287
        <table>
288
            <thead>
289
                <tr><th>name</th><th>age</th><th>sex</th></tr>
290
            </thead>
291
            <tbody>
292
                <tr><td>Alice</td><td>26</td><td>F</td></tr>
293
                <tr><td>Raj</td><td>34</td><td>M</td></tr>
294
            </tbody>
295
        </table>
296
    """
297

298
    # main method that serializes a table.
299
    # table_content must be in the prescribed input format.
300
    def serialize_table(self, table_content: Dict) -> str:
1✔
301
        # Extract headers and rows from the dictionary
302
        header = table_content.get("header", [])
1✔
303
        rows = table_content.get("rows", [])
1✔
304

305
        assert header and rows, "Incorrect input table format"
1✔
306

307
        # Build the HTML table structure
308
        serialized_tbl_str = "<table>\n"
1✔
309
        serialized_tbl_str += self.process_header(header) + "\n"
1✔
310
        serialized_tbl_str += self.process_rows(rows) + "\n"
1✔
311
        serialized_tbl_str += "</table>"
1✔
312

313
        return serialized_tbl_str.strip()
1✔
314

315
    # serialize the header into an HTML <thead> section
316
    def process_header(self, header: List) -> str:
1✔
317
        header_html = "  <thead>\n    <tr>"
1✔
318
        for col in header:
1✔
319
            header_html += f"<th>{col}</th>"
1✔
320
        header_html += "</tr>\n  </thead>"
1✔
321
        return header_html
1✔
322

323
    # serialize the rows into an HTML <tbody> section
324
    def process_rows(self, rows: List[List]) -> str:
1✔
325
        rows_html = "  <tbody>"
1✔
326
        for row in rows:
1✔
327
            rows_html += "\n    <tr>"
1✔
328
            for cell in row:
1✔
329
                rows_html += f"<td>{cell}</td>"
1✔
330
            rows_html += "</tr>"
1✔
331
        rows_html += "\n  </tbody>"
1✔
332
        return rows_html
1✔
333

334

335
class SerializeTableAsConcatenation(SerializeTable):
1✔
336
    """Concat Serializer.
337

338
    Concat all table content to one string of header and rows.
339
    Format(Sample):
340
    name age Alex 26 Diana 34
341
    """
342

343
    def serialize_table(self, table_content: Dict) -> str:
1✔
344
        # Extract headers and rows from the dictionary
345
        header = table_content["header"]
×
346
        rows = table_content["rows"]
×
347

348
        assert header and rows, "Incorrect input table format"
×
349

350
        # Process table header first
351
        serialized_tbl_str = " ".join([str(i) for i in header])
×
352

353
        # Process rows sequentially starting from row 1
354
        for row in rows:
×
355
            serialized_tbl_str += " " + " ".join([str(i) for i in row])
×
356

357
        # return serialized table as a string
358
        return serialized_tbl_str.strip()
×
359

360

361
class SerializeTableAsImage(SerializeTable):
1✔
362
    _requirements_list = ["matplotlib", "pillow"]
1✔
363

364
    def serialize_table(self, table_content: Dict) -> str:
1✔
365
        raise NotImplementedError()
×
366

367
    def serialize(self, value: Table, instance: Dict[str, Any]) -> str:
1✔
368
        table_content = recursive_copy(value)
×
369
        if self.shuffle_columns:
×
370
            table_content = shuffle_columns(table=table_content, seed=self.seed)
×
371

372
        if self.shuffle_rows:
×
373
            table_content = shuffle_rows(table=table_content, seed=self.seed)
×
374

375
        import io
×
376

377
        import matplotlib.pyplot as plt
×
378
        import pandas as pd
×
379
        from PIL import Image
×
380

381
        # Extract headers and rows from the dictionary
382
        header = table_content.get("header", [])
×
383
        rows = table_content.get("rows", [])
×
384

385
        assert header and rows, "Incorrect input table format"
×
386

387
        # Fix duplicate columns, ensuring the first occurrence has no suffix
388
        header = [
×
389
            f"{col}_{header[:i].count(col)}" if header[:i].count(col) > 0 else col
390
            for i, col in enumerate(header)
391
        ]
392

393
        # Create a pandas DataFrame
394
        df = pd.DataFrame(rows, columns=header)
×
395

396
        # Fix duplicate columns, ensuring the first occurrence has no suffix
397
        df.columns = [
×
398
            f"{col}_{i}" if df.columns.duplicated()[i] else col
399
            for i, col in enumerate(df.columns)
400
        ]
401

402
        # Create a matplotlib table
403
        plt.rcParams["font.family"] = "Serif"
×
404
        fig, ax = plt.subplots(figsize=(len(header) * 1.5, len(rows) * 0.5))
×
405
        ax.axis("off")  # Turn off the axes
×
406

407
        table = pd.plotting.table(ax, df, loc="center", cellLoc="center")
×
408
        table.auto_set_column_width(col=range(len(df.columns)))
×
409
        table.scale(1.5, 1.5)
×
410

411
        # Save the plot to a BytesIO buffer
412
        buf = io.BytesIO()
×
413
        plt.savefig(buf, format="png", bbox_inches="tight", dpi=150)
×
414
        plt.close(fig)  # Close the figure to free up memory
×
415
        buf.seek(0)
×
416

417
        # Load the image from the buffer using PIL
418
        image = Image.open(buf)
×
419
        return ImageSerializer().serialize({"image": image, "format": "png"}, instance)
×
420

421

422
# truncate cell value to maximum allowed length
423
def truncate_cell(cell_value, max_len):
1✔
424
    if cell_value is None:
1✔
425
        return None
×
426

427
    if isinstance(cell_value, int) or isinstance(cell_value, float):
1✔
428
        return None
×
429

430
    if cell_value.strip() == "":
1✔
431
        return None
×
432

433
    if len(cell_value) > max_len:
1✔
434
        return cell_value[:max_len]
1✔
435

436
    return None
1✔
437

438

439
class TruncateTableCells(InstanceOperator):
1✔
440
    """Limit the maximum length of cell values in a table to reduce the overall length.
441

442
    Args:
443
        max_length (int) - maximum allowed length of cell values
444
        For tasks that produce a cell value as answer, truncating a cell value should be replicated
445
        with truncating the corresponding answer as well. This has been addressed in the implementation.
446

447
    """
448

449
    max_length: int = 15
1✔
450
    table: str = None
1✔
451
    text_output: Optional[str] = None
1✔
452

453
    def process(
1✔
454
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
455
    ) -> Dict[str, Any]:
456
        table = dict_get(instance, self.table)
1✔
457

458
        answers = []
1✔
459
        if self.text_output is not None:
1✔
460
            answers = dict_get(instance, self.text_output)
×
461

462
        self.truncate_table(table_content=table, answers=answers)
1✔
463

464
        return instance
1✔
465

466
    # truncate table cells
467
    def truncate_table(self, table_content: Dict, answers: Optional[List]):
1✔
468
        cell_mapping = {}
1✔
469

470
        # One row at a time
471
        for row in table_content.get("rows", []):
1✔
472
            for i, cell in enumerate(row):
1✔
473
                truncated_cell = truncate_cell(cell, self.max_length)
1✔
474
                if truncated_cell is not None:
1✔
475
                    cell_mapping[cell] = truncated_cell
1✔
476
                    row[i] = truncated_cell
1✔
477

478
        # Update values in answer list to truncated values
479
        if answers is not None:
1✔
480
            for i, case in enumerate(answers):
1✔
481
                answers[i] = cell_mapping.get(case, case)
×
482

483

484
class TruncateTableRows(FieldOperator):
1✔
485
    """Limits table rows to specified limit by removing excess rows via random selection.
486

487
    Args:
488
        rows_to_keep (int): number of rows to keep.
489
    """
490

491
    rows_to_keep: int = 10
1✔
492

493
    def process_value(self, table: Any) -> Any:
1✔
494
        return self.truncate_table_rows(table_content=table)
1✔
495

496
    def truncate_table_rows(self, table_content: Dict):
1✔
497
        # Get rows from table
498
        rows = table_content.get("rows", [])
1✔
499

500
        num_rows = len(rows)
1✔
501

502
        # if number of rows are anyway lesser, return.
503
        if num_rows <= self.rows_to_keep:
1✔
504
            return table_content
×
505

506
        # calculate number of rows to delete, delete them
507
        rows_to_delete = num_rows - self.rows_to_keep
1✔
508

509
        # Randomly select rows to be deleted
510
        deleted_rows_indices = random.sample(range(len(rows)), rows_to_delete)
1✔
511

512
        remaining_rows = [
1✔
513
            row for i, row in enumerate(rows) if i not in deleted_rows_indices
514
        ]
515
        table_content["rows"] = remaining_rows
1✔
516

517
        return table_content
1✔
518

519

520
class SerializeTableRowAsText(InstanceOperator):
1✔
521
    """Serializes a table row as text.
522

523
    Args:
524
        fields (str) - list of fields to be included in serialization.
525
        to_field (str) - serialized text field name.
526
        max_cell_length (int) - limits cell length to be considered, optional.
527
    """
528

529
    fields: str
1✔
530
    to_field: str
1✔
531
    max_cell_length: Optional[int] = None
1✔
532

533
    def process(
1✔
534
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
535
    ) -> Dict[str, Any]:
536
        linearized_str = ""
1✔
537
        for field in self.fields:
1✔
538
            value = dict_get(instance, field)
1✔
539
            if self.max_cell_length is not None:
1✔
540
                truncated_value = truncate_cell(value, self.max_cell_length)
1✔
541
                if truncated_value is not None:
1✔
542
                    value = truncated_value
×
543

544
            linearized_str = linearized_str + field + " is " + str(value) + ", "
1✔
545

546
        instance[self.to_field] = linearized_str
1✔
547
        return instance
1✔
548

549

550
class SerializeTableRowAsList(InstanceOperator):
1✔
551
    """Serializes a table row as list.
552

553
    Args:
554
        fields (str) - list of fields to be included in serialization.
555
        to_field (str) - serialized text field name.
556
        max_cell_length (int) - limits cell length to be considered, optional.
557
    """
558

559
    fields: str
1✔
560
    to_field: str
1✔
561
    max_cell_length: Optional[int] = None
1✔
562

563
    def process(
1✔
564
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
565
    ) -> Dict[str, Any]:
566
        linearized_str = ""
1✔
567
        for field in self.fields:
1✔
568
            value = dict_get(instance, field)
1✔
569
            if self.max_cell_length is not None:
1✔
570
                truncated_value = truncate_cell(value, self.max_cell_length)
1✔
571
                if truncated_value is not None:
1✔
572
                    value = truncated_value
×
573

574
            linearized_str = linearized_str + field + ": " + str(value) + ", "
1✔
575

576
        instance[self.to_field] = linearized_str
1✔
577
        return instance
1✔
578

579

580
class SerializeTriples(FieldOperator):
1✔
581
    """Serializes triples into a flat sequence.
582

583
    Sample input in expected format:
584
    [[ "First Clearing", "LOCATION", "On NYS 52 1 Mi. Youngsville" ], [ "On NYS 52 1 Mi. Youngsville", "CITY_OR_TOWN", "Callicoon, New York"]]
585

586
    Sample output:
587
    First Clearing : LOCATION : On NYS 52 1 Mi. Youngsville | On NYS 52 1 Mi. Youngsville : CITY_OR_TOWN : Callicoon, New York
588

589
    """
590

591
    def process_value(self, tripleset: Any) -> Any:
1✔
592
        return self.serialize_triples(tripleset)
1✔
593

594
    def serialize_triples(self, tripleset) -> str:
1✔
595
        return " | ".join(
1✔
596
            f"{subj} : {rel.lower()} : {obj}" for subj, rel, obj in tripleset
597
        )
598

599

600
class SerializeKeyValPairs(FieldOperator):
1✔
601
    """Serializes key, value pairs into a flat sequence.
602

603
    Sample input in expected format: {"name": "Alex", "age": 31, "sex": "M"}
604
    Sample output: name is Alex, age is 31, sex is M
605
    """
606

607
    def process_value(self, kvpairs: Any) -> Any:
1✔
608
        return self.serialize_kvpairs(kvpairs)
1✔
609

610
    def serialize_kvpairs(self, kvpairs) -> str:
1✔
611
        serialized_str = ""
1✔
612
        for key, value in kvpairs.items():
1✔
613
            serialized_str += f"{key} is {value}, "
1✔
614

615
        # Remove the trailing comma and space then return
616
        return serialized_str[:-2]
1✔
617

618

619
class ListToKeyValPairs(InstanceOperator):
1✔
620
    """Maps list of keys and values into key:value pairs.
621

622
    Sample input in expected format: {"keys": ["name", "age", "sex"], "values": ["Alex", 31, "M"]}
623
    Sample output: {"name": "Alex", "age": 31, "sex": "M"}
624
    """
625

626
    fields: List[str]
1✔
627
    to_field: str
1✔
628

629
    def process(
1✔
630
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
631
    ) -> Dict[str, Any]:
632
        keylist = dict_get(instance, self.fields[0])
1✔
633
        valuelist = dict_get(instance, self.fields[1])
1✔
634

635
        output_dict = {}
1✔
636
        for key, value in zip(keylist, valuelist):
1✔
637
            output_dict[key] = value
1✔
638

639
        instance[self.to_field] = output_dict
1✔
640

641
        return instance
1✔
642

643

644
class ConvertTableColNamesToSequential(FieldOperator):
1✔
645
    """Replaces actual table column names with static sequential names like col_0, col_1,...
646

647
    .. code-block:: text
648

649
        Sample input:
650
        {
651
            "header": ["name", "age"],
652
            "rows": [["Alex", 21], ["Donald", 34]]
653
        }
654

655
        Sample output:
656
        {
657
            "header": ["col_0", "col_1"],
658
            "rows": [["Alex", 21], ["Donald", 34]]
659
        }
660
    """
661

662
    def process_value(self, table: Any) -> Any:
1✔
663
        table_input = recursive_copy(table)
1✔
664
        return self.replace_header(table_content=table_input)
1✔
665

666
    # replaces header with sequential column names
667
    def replace_header(self, table_content: Dict) -> str:
1✔
668
        # Extract header from the dictionary
669
        header = table_content.get("header", [])
1✔
670

671
        assert header, "Input table missing header"
1✔
672

673
        new_header = ["col_" + str(i) for i in range(len(header))]
1✔
674
        table_content["header"] = new_header
1✔
675

676
        return table_content
1✔
677

678

679
class ShuffleTableRows(TypeDependentAugmentor):
1✔
680
    """Shuffles the input table rows randomly.
681

682
    .. code-block:: text
683

684
        Sample Input:
685
        {
686
            "header": ["name", "age"],
687
            "rows": [["Alex", 26], ["Raj", 34], ["Donald", 39]],
688
        }
689

690
        Sample Output:
691
        {
692
            "header": ["name", "age"],
693
            "rows": [["Donald", 39], ["Raj", 34], ["Alex", 26]],
694
        }
695
    """
696

697
    augmented_type = Table
1✔
698
    seed = 0
1✔
699

700
    def process_value(self, table: Any) -> Any:
1✔
701
        table_input = recursive_copy(table)
1✔
702
        return shuffle_rows(table_input, self.seed)
1✔
703

704

705
class ShuffleTableColumns(TypeDependentAugmentor):
1✔
706
    """Shuffles the table columns randomly.
707

708
    .. code-block:: text
709

710
        Sample Input:
711
            {
712
                "header": ["name", "age"],
713
                "rows": [["Alex", 26], ["Raj", 34], ["Donald", 39]],
714
            }
715

716
        Sample Output:
717
            {
718
                "header": ["age", "name"],
719
                "rows": [[26, "Alex"], [34, "Raj"], [39, "Donald"]],
720
            }
721
    """
722

723
    augmented_type = Table
1✔
724
    seed = 0
1✔
725

726
    def process_value(self, table: Any) -> Any:
1✔
727
        table_input = recursive_copy(table)
1✔
728
        return shuffle_columns(table_input, self.seed)
1✔
729

730

731
class LoadJson(FieldOperator):
1✔
732
    failure_value: Any = None
1✔
733
    allow_failure: bool = False
1✔
734

735
    def process_value(self, value: str) -> Any:
1✔
736
        if self.allow_failure:
1✔
737
            try:
1✔
738
                return json.loads(value)
1✔
739
            except json.JSONDecodeError:
1✔
740
                return self.failure_value
1✔
741
        else:
742
            return json.loads(value, strict=False)
1✔
743

744

745
class DumpJson(FieldOperator):
1✔
746
    def process_value(self, value: str) -> str:
1✔
747
        return json.dumps(value)
1✔
748

749

750
class MapHTMLTableToJSON(FieldOperator):
1✔
751
    """Converts HTML table format to the basic one (JSON).
752

753
    JSON format:
754

755
    .. code-block:: json
756

757
        {
758
            "header": ["col1", "col2"],
759
            "rows": [["row11", "row12"], ["row21", "row22"], ["row31", "row32"]]
760
        }
761
    """
762

763
    _requirements_list = ["bs4"]
1✔
764

765
    def process_value(self, table: Any) -> Any:
1✔
766
        return self.convert_to_json(table_content=table)
1✔
767

768
    def convert_to_json(self, table_content: str) -> Dict:
1✔
769
        from bs4 import BeautifulSoup
1✔
770

771
        soup = BeautifulSoup(table_content, "html.parser")
1✔
772

773
        # Extract header
774
        header = []
1✔
775
        header_cells = soup.find("thead").find_all("th")
1✔
776
        for cell in header_cells:
1✔
777
            header.append(cell.get_text())
1✔
778

779
        # Extract rows
780
        rows = []
1✔
781
        for row in soup.find("tbody").find_all("tr"):
1✔
782
            row_data = []
1✔
783
            for cell in row.find_all("td"):
1✔
784
                row_data.append(cell.get_text())
1✔
785
            rows.append(row_data)
1✔
786

787
        # return dictionary
788

789
        return {"header": header, "rows": rows}
1✔
790

791

792
class MapTableListsToStdTableJSON(FieldOperator):
1✔
793
    """Converts lists table format to the basic one (JSON).
794

795
    JSON format:
796

797
    .. code-block:: json
798

799
        {
800
            "header": ["col1", "col2"],
801
            "rows": [["row11", "row12"], ["row21", "row22"], ["row31", "row32"]]
802
        }
803
    """
804

805
    def process_value(self, table: Any) -> Any:
1✔
806
        return self.map_tablelists_to_stdtablejson_util(table_content=table)
×
807

808
    def map_tablelists_to_stdtablejson_util(self, table_content: str) -> Dict:
1✔
809
        return {"header": table_content[0], "rows": table_content[1:]}
×
810

811

812
class ConstructTableFromRowsCols(InstanceOperator):
1✔
813
    """Maps column and row field into single table field encompassing both header and rows.
814

815
    field[0] = header string as List
816
    field[1] = rows string as List[List]
817
    field[2] = table caption string(optional)
818
    """
819

820
    fields: List[str]
1✔
821
    to_field: str
1✔
822

823
    def process(
1✔
824
        self, instance: Dict[str, Any], stream_name: Optional[str] = None
825
    ) -> Dict[str, Any]:
826
        header = dict_get(instance, self.fields[0])
×
827
        rows = dict_get(instance, self.fields[1])
×
828

829
        if len(self.fields) >= 3:
×
830
            caption = instance[self.fields[2]]
×
831
        else:
832
            caption = None
×
833

834
        import ast
×
835

836
        header_processed = ast.literal_eval(header)
×
837
        rows_processed = ast.literal_eval(rows)
×
838

839
        output_dict = {"header": header_processed, "rows": rows_processed}
×
840

841
        if caption is not None:
×
842
            output_dict["caption"] = caption
×
843

844
        instance[self.to_field] = output_dict
×
845

846
        return instance
×
847

848

849
class TransposeTable(TypeDependentAugmentor):
1✔
850
    """Transpose a table.
851

852
    .. code-block:: text
853

854
        Sample Input:
855
            {
856
                "header": ["name", "age", "sex"],
857
                "rows": [["Alice", 26, "F"], ["Raj", 34, "M"], ["Donald", 39, "M"]],
858
            }
859

860
        Sample Output:
861
            {
862
                "header": [" ", "0", "1", "2"],
863
                "rows": [["name", "Alice", "Raj", "Donald"], ["age", 26, 34, 39], ["sex", "F", "M", "M"]],
864
            }
865

866
    """
867

868
    augmented_type = Table
1✔
869

870
    def process_value(self, table: Any) -> Any:
1✔
871
        return self.transpose_table(table)
1✔
872

873
    def transpose_table(self, table: Dict) -> Dict:
1✔
874
        # Extract the header and rows from the table object
875
        header = table["header"]
1✔
876
        rows = table["rows"]
1✔
877

878
        # Transpose the table by converting rows as columns and vice versa
879
        transposed_header = [" "] + [str(i) for i in range(len(rows))]
1✔
880
        transposed_rows = [
1✔
881
            [header[i]] + [row[i] for row in rows] for i in range(len(header))
882
        ]
883

884
        return {"header": transposed_header, "rows": transposed_rows}
1✔
885

886

887
class DuplicateTableRows(TypeDependentAugmentor):
1✔
888
    """Duplicates specific rows of a table for the given number of times.
889

890
    Args:
891
        row_indices (List[int]): rows to be duplicated
892

893
        times(int): each row to be duplicated is to show that many times
894
    """
895

896
    augmented_type = Table
1✔
897

898
    row_indices: List[int] = []
1✔
899
    times: int = 1
1✔
900

901
    def process_value(self, table: Any) -> Any:
1✔
902
        # Extract the header and rows from the table
903
        header = table["header"]
1✔
904
        rows = table["rows"]
1✔
905

906
        # Duplicate only the specified rows
907
        duplicated_rows = []
1✔
908
        for i, row in enumerate(rows):
1✔
909
            if i in self.row_indices:
1✔
910
                duplicated_rows.extend(
1✔
911
                    [row] * self.times
912
                )  # Duplicate the selected rows
913
            else:
914
                duplicated_rows.append(row)  # Leave other rows unchanged
1✔
915

916
        # Return the new table with selectively duplicated rows
917
        return {"header": header, "rows": duplicated_rows}
1✔
918

919

920
class DuplicateTableColumns(TypeDependentAugmentor):
1✔
921
    """Duplicates specific columns of a table for the given number of times.
922

923
    Args:
924
        column_indices (List[int]): columns to be duplicated
925

926
        times(int): each column to be duplicated is to show that many times
927
    """
928

929
    augmented_type = Table
1✔
930

931
    column_indices: List[int] = []
1✔
932
    times: int = 1
1✔
933

934
    def process_value(self, table: Any) -> Any:
1✔
935
        # Extract the header and rows from the table
936
        header = table["header"]
1✔
937
        rows = table["rows"]
1✔
938

939
        # Duplicate the specified columns in the header
940
        duplicated_header = []
1✔
941
        for i, col in enumerate(header):
1✔
942
            if i in self.column_indices:
1✔
943
                duplicated_header.extend([col] * self.times)
1✔
944
            else:
945
                duplicated_header.append(col)
1✔
946

947
        # Duplicate the specified columns in each row
948
        duplicated_rows = []
1✔
949
        for row in rows:
1✔
950
            new_row = []
1✔
951
            for i, value in enumerate(row):
1✔
952
                if i in self.column_indices:
1✔
953
                    new_row.extend([value] * self.times)
1✔
954
                else:
955
                    new_row.append(value)
1✔
956
            duplicated_rows.append(new_row)
1✔
957

958
        # Return the new table with selectively duplicated columns
959
        return {"header": duplicated_header, "rows": duplicated_rows}
1✔
960

961

962
class InsertEmptyTableRows(TypeDependentAugmentor):
1✔
963
    """Inserts empty rows in a table randomly for the given number of times.
964

965
    Args:
966
        times(int) - how many times to insert
967
    """
968

969
    augmented_type = Table
1✔
970

971
    times: int = 0
1✔
972

973
    def process_value(self, table: Any) -> Any:
1✔
974
        # Extract the header and rows from the table
975
        header = table["header"]
1✔
976
        rows = table["rows"]
1✔
977

978
        # Insert empty rows at random positions
979
        for _ in range(self.times):
1✔
980
            empty_row = [""] * len(
1✔
981
                header
982
            )  # Create an empty row with the same number of columns
983
            insert_pos = random.randint(
1✔
984
                0, len(rows)
985
            )  # Get a random position to insert the empty row created
986
            rows.insert(insert_pos, empty_row)
1✔
987

988
        # Return the modified table
989
        return {"header": header, "rows": rows}
1✔
990

991

992
class MaskColumnsNames(TypeDependentAugmentor):
1✔
993
    """Mask the names of tables columns with dummies "Col1", "Col2" etc."""
994

995
    augmented_type = Table
1✔
996

997
    def process_value(self, table: Any) -> Any:
1✔
998
        masked_header = ["Col" + str(ind + 1) for ind in range(len(table["header"]))]
×
999

1000
        return {"header": masked_header, "rows": table["rows"]}
×
1001

1002

1003
class ShuffleColumnsNames(TypeDependentAugmentor):
1✔
1004
    """Shuffle table columns names to be displayed in random order."""
1005

1006
    augmented_type = Table
1✔
1007

1008
    def process_value(self, table: Any) -> Any:
1✔
1009
        shuffled_header = table["header"]
×
1010
        random.shuffle(shuffled_header)
×
1011

1012
        return {"header": shuffled_header, "rows": table["rows"]}
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc