mosel / scripts /flagHallucinations.py
mgaido91's picture
[DEV] Add scripts for hallucination detection
04fcf96 verified
raw
history blame
5.66 kB
# 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)