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

IBM / unitxt / 12697164720

09 Jan 2025 07:30PM UTC coverage: 80.018% (-0.2%) from 80.203%
12697164720

push

github

web-flow
Add example for evaluating tables as images using Unitxt APIs (#1495)

Signed-off-by: elronbandel <elronbandel@gmail.com>

1377 of 1710 branches covered (80.53%)

Branch coverage included in aggregate %.

8678 of 10856 relevant lines covered (79.94%)

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

149
        serialized_row_str += " | ".join(row_cell_values)
1✔
150

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

153

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

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

160
    .. code-block:: text
161

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

168
    """
169

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

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

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

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

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

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

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

201

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

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

208
    .. code-block:: python
209

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

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

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

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

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

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

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

246

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

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

253
    .. code-block:: json
254

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

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

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

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

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

279

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

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

286
    .. code-block:: html
287

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

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

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

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

314
        return serialized_tbl_str.strip()
1✔
315

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

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

335

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

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

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

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

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

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

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

361

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

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

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

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

376
        import io
×
377

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

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

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

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

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

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

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

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

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

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

422

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

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

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

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

437
    return None
1✔
438

439

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

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

448
    """
449

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

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

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

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

465
        return instance
1✔
466

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

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

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

484

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

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

492
    rows_to_keep: int = 10
1✔
493

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

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

501
        num_rows = len(rows)
1✔
502

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

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

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

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

518
        return table_content
1✔
519

520

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

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

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

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

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

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

550

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

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

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

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

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

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

580

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

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

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

590
    """
591

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

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

600

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

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

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

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

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

619

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

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

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

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

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

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

642
        return instance
1✔
643

644

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

648
    .. code-block:: text
649

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

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

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

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

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

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

677
        return table_content
1✔
678

679

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

683
    .. code-block:: text
684

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

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

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

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

705

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

709
    .. code-block:: text
710

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

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

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

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

731

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

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

745

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

750

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

754
    JSON format:
755

756
    .. code-block:: json
757

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

764
    _requirements_list = ["bs4"]
1✔
765

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

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

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

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

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

788
        # return dictionary
789

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

792

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

796
    JSON format:
797

798
    .. code-block:: json
799

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

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

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

812

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

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

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

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

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

835
        import ast
×
836

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

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

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

845
        instance[self.to_field] = output_dict
×
846

847
        return instance
×
848

849

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

853
    .. code-block:: text
854

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

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

867
    """
868

869
    augmented_type = Table
1✔
870

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

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

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

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

887

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

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

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

897
    augmented_type = Table
1✔
898

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

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

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

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

920

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

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

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

930
    augmented_type = Table
1✔
931

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

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

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

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

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

962

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

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

970
    augmented_type = Table
1✔
971

972
    times: int = 0
1✔
973

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

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

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

992

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

996
    augmented_type = Table
1✔
997

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

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

1003

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

1007
    augmented_type = Table
1✔
1008

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

1013
        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

© 2025 Coveralls, Inc