File size: 5,658 Bytes
04fcf96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# Copyright 2024 FBK

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License

try:
    import pandas as pd
except ImportError:
    print("Please install the pandas package with 'pip install pandas' and try again.")
    exit(1)

import argparse

_VERSION = "1.01"

class ExplicitDefaultsHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
    def _get_help_string(self, action):
        if action.default is None or action.default is False:
            return action.help
        return super()._get_help_string(action)

# max size of pattern (seq of words) that,
# if repeated at least thresh1grams/threshNgrams times,
# risesflags the hallucination:
maxN = 5

def findHall(wrd):
    for N in range(maxN, 0, -1):
        count = 0
        for idx in range(0,len(wrd)-2*N+2): # the max idx value must be leave
                                            # room for at least one repetition
                                            # of the N_sized pattern 
            count += hallLen(idx,N,wrd)
            if ( N<3  and count+1>=parsed_args.thresh1grams ) or \
               ( N>=3 and count+1>=parsed_args.threshNgrams ):
                return [N, idx, count] 
            else:
                count = 0 # reset
                
    return [0,0,0]

def hallLen(startIdx,N,wrd):
    hallLen = 0
    startRep = startIdx + N # first index after the end of the current pattern
    while startRep < len(wrd)-N+1:
        if isHall(startIdx,startRep,N,wrd):
            hallLen+=1
            startRep+=N
        else:
            break
    return hallLen

def isHall(s1,s2,N,wrd):
    i = 0
    while i<N and wrd[s1+i] == wrd[s2+i]:
        i+=1
    return i == N
    
def main(args):
    """
    This script flags (by setting True the corresponding entry 
    of the hall_repeated_ngrams column) those sentences where a 
    pattern (n-gram, that is a sequence of n words) is repeated 
    at least a given number of times; for patterns of size 1 to 2, 
    the minimum number of times for flagging it is set by the 
    thresh1grams parameter (default value: 4), for those of size 
    3-5 by threshNgrams (2)
    """

    if (parsed_args.version): 
        print(f"Version {_VERSION} of anomalous string detector")
        exit(1)

    if not (tsv_files_specified):
        print("--tsv-InFile and --tsv-OutFile are both required")
        parser.print_usage()
        exit(1)

    if not (wrong_thresh_values):
        print("--thresh1grams and --threshNgrams must both be positive integers")
        parser.print_usage()
        exit(1)

    try:
        inDF = pd.read_csv(args.tsv_InFile, sep='\t', dtype=str, low_memory=False, na_filter=False, quoting=3)
    except IOError:
        print("Error in opening "+args.tsv_InFile+" file")

    try:
        txt = inDF[parsed_args.column]
    except KeyError:
        print("Error in reading column <"+parsed_args.column+"> in TSV file")
        exit(1)

    flag = []
    for line in txt:
        words = line.split()
        [size, idx, count] = findHall(words)
        if size>0:
            if args.quiet:
                flag.append("True")
            else:
                flag.append("True (pattern of length " + str(size) + \
                            " from index " + str(idx) + \
                            ", repeated at least " + str(count+1) + " times)")
        else:
            flag.append("False")

    inDF['hall_repeated_ngrams'] = flag
    inDF.to_csv(args.tsv_OutFile, sep="\t", index=False, quoting=3)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(formatter_class=ExplicitDefaultsHelpFormatter)

    # I/O related arguments
    parser.add_argument(
        '--tsv-InFile', '-i', type=str,
        help="The input TSV file [Mandatory]")

    parser.add_argument(
        '--tsv-OutFile', '-o', type=str,
        help="The output TSV file [Mandatory. If equal to input TSV file, the new column is added to the original file]")

    # Processing arguments:
    parser.add_argument(
        '--column', '-c', default='source',
        help="Column name of the text to process [Optional]")
    
    parser.add_argument(
        '--thresh1grams', '-u', type=int, default=4,
        help="Threshold for 1-2_word hallucinations [Optional]")

    parser.add_argument(
        '--threshNgrams', '-n', type=int, default=2,
        help="Threshold for 3-5_word hallucinations [Optional]")

    # Reporting related arguments
    parser.add_argument(
        '--quiet', '-q', default=False, action='store_true',
        help='Print only True/False, no explanation for True\'s')

    # Get version information:
    parser.add_argument(
        '--version', '-v', action='store_true', default=False,
        help="Print version of the script and exit")

    
    parsed_args = parser.parse_args()
    tsv_files_specified = \
        getattr(parsed_args, 'tsv_InFile') is not None \
        and len(parsed_args.tsv_InFile) > 0 \
        and getattr(parsed_args, 'tsv_OutFile') is not None \
        and len(parsed_args.tsv_OutFile) > 0

    wrong_thresh_values = parsed_args.thresh1grams > 0 \
                          and parsed_args.threshNgrams > 0
    
    
    main(parsed_args)