Spaces:
Sleeping
Sleeping
Upload 9 files
Browse files- .gitattributes +36 -35
- .gitignore +1 -0
- OpenAIAPIModel.py +50 -0
- README.md +12 -12
- app.py +612 -0
- constants.py +3 -0
- report.txt +45 -0
- requirements.txt +55 -0
- utils.py +153 -0
.gitattributes
CHANGED
|
@@ -1,35 +1,36 @@
|
|
| 1 |
-
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
data/en.json filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
venv
|
OpenAIAPIModel.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import time
|
| 3 |
+
|
| 4 |
+
class GroqOpenAIAPIModel:
|
| 5 |
+
def __init__(self, api_key, url="https://api.groq.com/openai/v1/chat/completions", model="llama3-8b-8192"):
|
| 6 |
+
self.url = url
|
| 7 |
+
self.model = model
|
| 8 |
+
self.API_KEY = api_key
|
| 9 |
+
|
| 10 |
+
print(f"GroqOpenAIAPIModel initialized with model: {self.model}")
|
| 11 |
+
|
| 12 |
+
def generate(self, text: str, temperature=0.7, system="You are a helpful assistant.", top_p=1):
|
| 13 |
+
time.sleep(5)
|
| 14 |
+
headers = {
|
| 15 |
+
"Authorization": f"Bearer {self.API_KEY}",
|
| 16 |
+
"Content-Type": "application/json"
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
query = {
|
| 20 |
+
"model": self.model,
|
| 21 |
+
"temperature": temperature,
|
| 22 |
+
"top_p": top_p,
|
| 23 |
+
"messages": [
|
| 24 |
+
{"role": "system", "content": system},
|
| 25 |
+
{"role": "user", "content": text}
|
| 26 |
+
],
|
| 27 |
+
"stream": False
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
response = requests.post(self.url, headers=headers, json=query)
|
| 32 |
+
response.raise_for_status()
|
| 33 |
+
|
| 34 |
+
response_json = response.json()
|
| 35 |
+
if 'choices' not in response_json:
|
| 36 |
+
print("⚠️ 'choices' missing in response")
|
| 37 |
+
print("🔍 Input text:", text)
|
| 38 |
+
print("📦 Full response:", response_json)
|
| 39 |
+
return "[ERROR] Response missing 'choices'"
|
| 40 |
+
|
| 41 |
+
return response_json['choices'][0]['message']['content']
|
| 42 |
+
|
| 43 |
+
except requests.exceptions.RequestException as e:
|
| 44 |
+
print("❌ HTTP error during API call:", e)
|
| 45 |
+
print("🔍 Input text:", text)
|
| 46 |
+
return "[ERROR] API call failed"
|
| 47 |
+
except Exception as e:
|
| 48 |
+
print("❌ Unexpected error:", e)
|
| 49 |
+
print("🔍 Input text:", text)
|
| 50 |
+
return "[ERROR] Unexpected failure"
|
README.md
CHANGED
|
@@ -1,12 +1,12 @@
|
|
| 1 |
-
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version: 5.38.
|
| 8 |
-
app_file: app.py
|
| 9 |
-
pinned: false
|
| 10 |
-
---
|
| 11 |
-
|
| 12 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: RGB26Demo
|
| 3 |
+
emoji: 📉
|
| 4 |
+
colorFrom: gray
|
| 5 |
+
colorTo: purple
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 5.38.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
|
@@ -0,0 +1,612 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import os
|
| 4 |
+
import json
|
| 5 |
+
import random
|
| 6 |
+
import yaml
|
| 7 |
+
import tqdm
|
| 8 |
+
from utils import processdata, predict, supported_models
|
| 9 |
+
from OpenAIAPIModel import GroqOpenAIAPIModel # Adjusted import based on the provided context
|
| 10 |
+
import utils
|
| 11 |
+
import requests
|
| 12 |
+
import pandas as pd
|
| 13 |
+
|
| 14 |
+
def check_counterfactual(question, answer, url, apikey):
|
| 15 |
+
prompt = '''Please determine whether the model can identify factual errors in the document. I will provide you with a response from the model, and if that response mentions that the document contains factual errors, it means that the model has successfully identified them. Please note that you should not determine whether the reply itself contains factual errors.
|
| 16 |
+
Demonstrations:
|
| 17 |
+
Response:文档信息有误,2008年的奥运会在北京举办。
|
| 18 |
+
Yes, the model has identified the factual errors.
|
| 19 |
+
|
| 20 |
+
Response:2014年澳网女单冠军是大阪直美。
|
| 21 |
+
NO, the model fail to identify the factual errors.
|
| 22 |
+
|
| 23 |
+
Response: The director of the Silent Hill movie is Justin Kurzel.
|
| 24 |
+
NO, the model fail to identify the factual errors.
|
| 25 |
+
|
| 26 |
+
Response: Harry Potter is written by J. K. Rowling.
|
| 27 |
+
NO, the model fail to identify the factual errors.
|
| 28 |
+
|
| 29 |
+
Response: There are factual errors in the provided documents. The correct answer is 2023.
|
| 30 |
+
Yes, the model has identified the factual errors.
|
| 31 |
+
|
| 32 |
+
Begin to generate:
|
| 33 |
+
Answer: {answer}
|
| 34 |
+
'''
|
| 35 |
+
text2 = prompt.format(answer=answer)
|
| 36 |
+
# return getdata(text2,url,apikey)
|
| 37 |
+
text2 = prompt.format(question=question,answer=answer)
|
| 38 |
+
return get_groq_response(text2, apikey)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def check(question, answer, url, apikey):
|
| 42 |
+
prompt = '''I will give you a question and an answer generated through document retrieval. Please use this answer to determine if the retrieved document can solve the question.
|
| 43 |
+
Demonstrations:
|
| 44 |
+
Question: 2023年澳网女单冠军是谁
|
| 45 |
+
Answer:文档信息不足,因此我无法基于提供的文档回答该问题。
|
| 46 |
+
No, the question is not addressed by the documents.
|
| 47 |
+
|
| 48 |
+
Question: Who is the champion of Australian Open 2023 Women's Singles?
|
| 49 |
+
Answer: Serena Williams
|
| 50 |
+
Yes, the question is addressed by the documents.
|
| 51 |
+
|
| 52 |
+
Question: Where is ACL2023 held?
|
| 53 |
+
Answer: Location of ACL2023 has not been confirmed.
|
| 54 |
+
No, the question is not addressed by the documents.
|
| 55 |
+
|
| 56 |
+
Question: 2023年中国GDP是多少?
|
| 57 |
+
Answer: I can not answer this question。
|
| 58 |
+
No, the question is not addressed by the documents.
|
| 59 |
+
|
| 60 |
+
Begin to generate:
|
| 61 |
+
Question: {question}
|
| 62 |
+
Answer: {answer}
|
| 63 |
+
'''
|
| 64 |
+
text2 = prompt.format(question=question,answer=answer)
|
| 65 |
+
return get_groq_response(text2, apikey)
|
| 66 |
+
|
| 67 |
+
def get_groq_response(prompt, api_key):
|
| 68 |
+
if api_key == "":
|
| 69 |
+
api_key = os.environ.get("GROQ_API_KEY") # Safely loaded from HF Secrets
|
| 70 |
+
|
| 71 |
+
url = "https://api.groq.com/openai/v1/chat/completions"
|
| 72 |
+
headers = {
|
| 73 |
+
"Authorization": f"Bearer {api_key}",
|
| 74 |
+
"Content-Type": "application/json"
|
| 75 |
+
}
|
| 76 |
+
data = {
|
| 77 |
+
"model": "llama-3.3-70b-versatile",
|
| 78 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 79 |
+
"temperature": 0.7
|
| 80 |
+
}
|
| 81 |
+
for attempt in range(3):
|
| 82 |
+
try:
|
| 83 |
+
response = requests.post(url, json=data, headers=headers)
|
| 84 |
+
response.raise_for_status() # Raise HTTP errors
|
| 85 |
+
json_response = response.json()
|
| 86 |
+
|
| 87 |
+
if "choices" not in json_response:
|
| 88 |
+
print(f"Unexpected response format: {json_response}")
|
| 89 |
+
return "Error: Invalid API response format."
|
| 90 |
+
|
| 91 |
+
return json_response["choices"][0]["message"]["content"]
|
| 92 |
+
|
| 93 |
+
except requests.exceptions.RequestException as e:
|
| 94 |
+
print(f"Attempt {attempt + 1} failed: {e}")
|
| 95 |
+
time.sleep(2) # Backoff before retry
|
| 96 |
+
|
| 97 |
+
return "Error: Max retries reached."
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def run_reject_rate(
|
| 101 |
+
modelname='chatgpt',
|
| 102 |
+
dataset='en',
|
| 103 |
+
api_key='api_key',
|
| 104 |
+
url='https://api.openai.com/v1/completions',
|
| 105 |
+
temperature=0.7,
|
| 106 |
+
noise_rate=0.0,
|
| 107 |
+
correct_rate=0.0,
|
| 108 |
+
passage_num=5,
|
| 109 |
+
factchecking=False,
|
| 110 |
+
max_instances=2
|
| 111 |
+
):
|
| 112 |
+
# Result path (in working dir)
|
| 113 |
+
resultpath = 'results/result-en' if 'en' in dataset else 'results/result-zh'
|
| 114 |
+
|
| 115 |
+
modelname = modelname.replace('/', '_') # Replace '/' with '_' for file naming
|
| 116 |
+
|
| 117 |
+
evaluefile = f'{resultpath}/prediction_{dataset}_{modelname}_temp{temperature}_noise{1}_passage{passage_num}_correct{0}.json'
|
| 118 |
+
|
| 119 |
+
outputfile = f'{resultpath}/prediction_{dataset}_{modelname}_temp{temperature}_noise{1}_passage{passage_num}_correct{0}_chatgpt.json'
|
| 120 |
+
|
| 121 |
+
resultfile = f'{resultpath}/prediction_{dataset}_{modelname}_temp{temperature}_noise{1}_passage{passage_num}_correct{0}_chatgptresult.json'
|
| 122 |
+
|
| 123 |
+
results = []
|
| 124 |
+
useddata = {}
|
| 125 |
+
if os.path.exists(outputfile):
|
| 126 |
+
with open(outputfile) as f:
|
| 127 |
+
for line in f:
|
| 128 |
+
data = json.loads(line)
|
| 129 |
+
useddata[data['id']] = data
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
with open(outputfile,'w',encoding='utf-8') as f:
|
| 133 |
+
with open(evaluefile, 'r', encoding='utf-8') as f2:
|
| 134 |
+
for line in tqdm.tqdm(f2):
|
| 135 |
+
data = json.loads(line)
|
| 136 |
+
if data['id'] in useddata and data['query'] == useddata[data['id']]['query'] and data['ans'] == useddata[data['id']]['ans'] :
|
| 137 |
+
results.append(useddata[data['id']])
|
| 138 |
+
f.write(json.dumps(useddata[data['id']],ensure_ascii=False)+'\n')
|
| 139 |
+
continue
|
| 140 |
+
try:
|
| 141 |
+
question = data['query']
|
| 142 |
+
answer = data['prediction']
|
| 143 |
+
|
| 144 |
+
evaluation = check(question, answer, url, api_key)
|
| 145 |
+
data['evaluation'] = evaluation
|
| 146 |
+
results.append(data)
|
| 147 |
+
f.write(json.dumps(data,ensure_ascii=False)+'\n')
|
| 148 |
+
except Exception as e:
|
| 149 |
+
print(f"Exception Generated: {e}")
|
| 150 |
+
print(f"Questions :{question}, Answer :{answer}")
|
| 151 |
+
continue
|
| 152 |
+
|
| 153 |
+
rejecttt = 0
|
| 154 |
+
tt = 0
|
| 155 |
+
for i in results:
|
| 156 |
+
if "not addressed" in i['evaluation']:
|
| 157 |
+
rejecttt += 1
|
| 158 |
+
if 0 not in i['label'] and 1 in i['label']:
|
| 159 |
+
tt += 1
|
| 160 |
+
print(tt/len(results))
|
| 161 |
+
scores = {
|
| 162 |
+
'reject_rate': rejecttt/len(results),
|
| 163 |
+
'all_rate': (tt)/len(results),
|
| 164 |
+
'tt':tt,
|
| 165 |
+
'rejecttt':rejecttt,
|
| 166 |
+
'nums': len(results),
|
| 167 |
+
}
|
| 168 |
+
# json.dump(scores, open(resultfile, 'w', encoding='utf-8'), ensure_ascii=False, indent=4)
|
| 169 |
+
|
| 170 |
+
try:
|
| 171 |
+
utils.upload_file(outputfile, "")
|
| 172 |
+
except Exception as e:
|
| 173 |
+
print("Error saving outputfile {outputfile}:", e)
|
| 174 |
+
|
| 175 |
+
# Save results
|
| 176 |
+
try:
|
| 177 |
+
finalResults = {
|
| 178 |
+
'model': modelname,
|
| 179 |
+
'dataset': dataset,
|
| 180 |
+
'temperature': temperature,
|
| 181 |
+
'noise_rate': noise_rate,
|
| 182 |
+
'passage_num': passage_num,
|
| 183 |
+
'correct_rate': correct_rate,
|
| 184 |
+
'factchecking': factchecking,
|
| 185 |
+
'scores': scores,
|
| 186 |
+
}
|
| 187 |
+
with open(resultfile, 'w') as f:
|
| 188 |
+
json.dump(finalResults, f, ensure_ascii=False, indent=4)
|
| 189 |
+
utils.upload_file(resultfile, "")
|
| 190 |
+
except Exception as e:
|
| 191 |
+
print("Error saving scores:", e)
|
| 192 |
+
|
| 193 |
+
return finalResults
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def run_information_integration(
|
| 197 |
+
modelname='chatgpt',
|
| 198 |
+
dataset='en_int',
|
| 199 |
+
api_key='api_key',
|
| 200 |
+
url='https://api.openai.com/v1/completions',
|
| 201 |
+
temperature=0.7,
|
| 202 |
+
noise_rate=0.0,
|
| 203 |
+
correct_rate=0.0,
|
| 204 |
+
passage_num=5,
|
| 205 |
+
factchecking=False,
|
| 206 |
+
max_instances=2
|
| 207 |
+
):
|
| 208 |
+
return run_evaluation(
|
| 209 |
+
modelname=modelname,
|
| 210 |
+
dataset="en_int",
|
| 211 |
+
api_key=api_key,
|
| 212 |
+
url=url,
|
| 213 |
+
temperature=temperature,
|
| 214 |
+
noise_rate=noise_rate,
|
| 215 |
+
correct_rate=correct_rate,
|
| 216 |
+
passage_num=passage_num,
|
| 217 |
+
factchecking=factchecking,
|
| 218 |
+
max_instances=max_instances
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def run_counter_factual_checking(
|
| 223 |
+
modelname='chatgpt',
|
| 224 |
+
dataset='en_fact',
|
| 225 |
+
api_key='api_key', # API key for the model
|
| 226 |
+
url='https://api.openai.com/v1/completions',
|
| 227 |
+
temperature=0.7,
|
| 228 |
+
noise_rate=0.0,
|
| 229 |
+
correct_rate=0.0,
|
| 230 |
+
passage_num=5,
|
| 231 |
+
factchecking=False,
|
| 232 |
+
max_instances=2
|
| 233 |
+
):
|
| 234 |
+
resultpath = 'results/result-en' if 'en' in dataset else 'results/result-zh'
|
| 235 |
+
modelname = modelname.replace('/', '_') # Replace '/' with '_' for file naming
|
| 236 |
+
|
| 237 |
+
evaluefile = f'{resultpath}/prediction_{dataset}_{modelname}_temp{temperature}_noise{noise_rate}_passage{passage_num}_correct{correct_rate}.json'
|
| 238 |
+
outputfile = f'{resultpath}/prediction_{dataset}_{modelname}_temp{temperature}_noise{noise_rate}_passage{passage_num}_correct{correct_rate}_chatgpt.json'
|
| 239 |
+
resultfile = f'{resultpath}/prediction_{dataset}_{modelname}_temp{temperature}_noise{noise_rate}_passage{passage_num}_correct{correct_rate}_chatgptresult.json'
|
| 240 |
+
|
| 241 |
+
results = []
|
| 242 |
+
useddata = {}
|
| 243 |
+
if os.path.exists(outputfile):
|
| 244 |
+
with open(outputfile) as f:
|
| 245 |
+
for line in f:
|
| 246 |
+
data = json.loads(line)
|
| 247 |
+
useddata[data['id']] = data
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
with open(outputfile,'w',encoding='utf-8') as f:
|
| 251 |
+
with open(evaluefile, 'r', encoding='utf-8') as f2:
|
| 252 |
+
for line in tqdm.tqdm(f2):
|
| 253 |
+
data = json.loads(line)
|
| 254 |
+
if data['id'] in useddata:
|
| 255 |
+
results.append(useddata[data['id']])
|
| 256 |
+
f.write(json.dumps(useddata[data['id']],ensure_ascii=False)+'\n')
|
| 257 |
+
continue
|
| 258 |
+
try:
|
| 259 |
+
question = data['query']
|
| 260 |
+
answer = data['prediction']
|
| 261 |
+
|
| 262 |
+
evaluation = check_counterfactual(question, answer, url, api_key)
|
| 263 |
+
|
| 264 |
+
data['evaluation'] = evaluation
|
| 265 |
+
results.append(data)
|
| 266 |
+
f.write(json.dumps(data,ensure_ascii=False)+'\n')
|
| 267 |
+
except Exception as e:
|
| 268 |
+
print(e)
|
| 269 |
+
print(question,answer)
|
| 270 |
+
continue
|
| 271 |
+
|
| 272 |
+
rejecttt = 0
|
| 273 |
+
tt = 0
|
| 274 |
+
correct_tt = 0
|
| 275 |
+
for i in results:
|
| 276 |
+
if "has identified" in i['evaluation'] or "Yes" in i['evaluation']:
|
| 277 |
+
rejecttt += 1
|
| 278 |
+
if 0 not in i['label'] and 1 in i['label']:
|
| 279 |
+
correct_tt += 1
|
| 280 |
+
if 0 not in i['label'] and 1 in i['label']:
|
| 281 |
+
tt += 1
|
| 282 |
+
print(tt/len(results))
|
| 283 |
+
scores = {
|
| 284 |
+
'reject_rate': rejecttt/len(results), # ED*
|
| 285 |
+
'all_rate': (tt)/len(results),
|
| 286 |
+
'correct_rate': correct_tt/rejecttt if rejecttt > 0 else 0, # CR
|
| 287 |
+
'tt':tt,
|
| 288 |
+
'rejecttt':rejecttt,
|
| 289 |
+
'correct_tt':correct_tt,
|
| 290 |
+
'nums': len(results),
|
| 291 |
+
'noise_rate': noise_rate,
|
| 292 |
+
}
|
| 293 |
+
# The "reject_rate" in the outputs are the error detection rates (ED*). The correct_rate in the outputs are the error correction rate (CR)
|
| 294 |
+
|
| 295 |
+
try:
|
| 296 |
+
utils.upload_file(outputfile, "")
|
| 297 |
+
except Exception as e:
|
| 298 |
+
print("Error saving outputfile {outputfile}:", e)
|
| 299 |
+
|
| 300 |
+
# Save results
|
| 301 |
+
try:
|
| 302 |
+
finalResults = {
|
| 303 |
+
'model': modelname,
|
| 304 |
+
'dataset': dataset,
|
| 305 |
+
'temperature': temperature,
|
| 306 |
+
'noise_rate': noise_rate,
|
| 307 |
+
'passage_num': passage_num,
|
| 308 |
+
'correct_rate': correct_rate,
|
| 309 |
+
'factchecking': factchecking,
|
| 310 |
+
'scores': scores,
|
| 311 |
+
}
|
| 312 |
+
with open(resultfile, 'w') as f:
|
| 313 |
+
json.dump(finalResults, f, ensure_ascii=False, indent=4)
|
| 314 |
+
utils.upload_file(resultfile, "")
|
| 315 |
+
except Exception as e:
|
| 316 |
+
print("Error saving scores:", e)
|
| 317 |
+
|
| 318 |
+
return finalResults
|
| 319 |
+
|
| 320 |
+
def run_evaluation(
|
| 321 |
+
modelname='chatgpt',
|
| 322 |
+
dataset='en',
|
| 323 |
+
api_key='api_key',
|
| 324 |
+
url='https://api.openai.com/v1/completions',
|
| 325 |
+
temperature=0.7,
|
| 326 |
+
noise_rate=0.0,
|
| 327 |
+
correct_rate=0.0,
|
| 328 |
+
passage_num=5,
|
| 329 |
+
factchecking=False,
|
| 330 |
+
max_instances = 2
|
| 331 |
+
):
|
| 332 |
+
# Paths
|
| 333 |
+
dataset_path = f"data/{dataset}.json"
|
| 334 |
+
prompt_file = f"config/instruction.yaml"
|
| 335 |
+
prompt_fact_file = f"config/instruction_fact.yaml"
|
| 336 |
+
|
| 337 |
+
# Load dataset
|
| 338 |
+
instances = []
|
| 339 |
+
with open(dataset_path, 'r') as f:
|
| 340 |
+
for i, line in enumerate(f):
|
| 341 |
+
if i >= max_instances: # ✅ Limit to first 5
|
| 342 |
+
break
|
| 343 |
+
instances.append(json.loads(line))
|
| 344 |
+
|
| 345 |
+
# Result path (in working dir)
|
| 346 |
+
resultpath = 'results/result-en' if 'en' in dataset else 'results/result-zh'
|
| 347 |
+
if not os.path.exists(resultpath):
|
| 348 |
+
os.makedirs(resultpath)
|
| 349 |
+
|
| 350 |
+
# Load prompt
|
| 351 |
+
if factchecking:
|
| 352 |
+
prompt = yaml.load(open(prompt_fact_file, 'r'), Loader=yaml.FullLoader)[dataset[:2]]
|
| 353 |
+
resultpath = os.path.join(resultpath, 'fact')
|
| 354 |
+
if not os.path.exists(resultpath):
|
| 355 |
+
os.makedirs(resultpath)
|
| 356 |
+
else:
|
| 357 |
+
prompt = yaml.load(open(prompt_file, 'r'), Loader=yaml.FullLoader)[dataset[:2]]
|
| 358 |
+
|
| 359 |
+
system = prompt['system']
|
| 360 |
+
instruction = prompt['instruction']
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
if api_key == "":
|
| 364 |
+
api_key = os.environ.get("GROQ_API_KEY") # Safely loaded from HF Secrets
|
| 365 |
+
|
| 366 |
+
model = GroqOpenAIAPIModel(api_key=api_key, url=url, model=modelname)
|
| 367 |
+
|
| 368 |
+
print(f"Model Created Name: {model}")
|
| 369 |
+
|
| 370 |
+
modelname = modelname.replace('/', '_') # Replace '/' with '_' for file naming
|
| 371 |
+
|
| 372 |
+
# Output file
|
| 373 |
+
output_file = f"prediction_{dataset}_{modelname}_temp{temperature}_noise{noise_rate}_passage{passage_num}_correct{correct_rate}.json"
|
| 374 |
+
print(f"Output File: {output_file}")
|
| 375 |
+
|
| 376 |
+
# Previously used predictions
|
| 377 |
+
useddata = {}
|
| 378 |
+
complete_output_file = os.path.join(resultpath, output_file)
|
| 379 |
+
if os.path.exists(complete_output_file):
|
| 380 |
+
with open(complete_output_file) as f:
|
| 381 |
+
for line in f:
|
| 382 |
+
data = json.loads(line)
|
| 383 |
+
useddata[data['id']] = data
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
# print(f"********Information about usedata: {useddata}")
|
| 387 |
+
|
| 388 |
+
# Inference loop
|
| 389 |
+
results = []
|
| 390 |
+
with open(complete_output_file, 'w') as f:
|
| 391 |
+
for instance in tqdm.tqdm(instances):
|
| 392 |
+
if instance['id'] in useddata and instance['query'] == useddata[instance['id']]['query'] and instance['answer'] == useddata[instance['id']]['ans']:
|
| 393 |
+
results.append(useddata[instance['id']])
|
| 394 |
+
f.write(json.dumps(useddata[instance['id']], ensure_ascii=False) + '\n')
|
| 395 |
+
|
| 396 |
+
print("Found information in useddata")
|
| 397 |
+
continue
|
| 398 |
+
try:
|
| 399 |
+
random.seed(2333)
|
| 400 |
+
if passage_num == 0:
|
| 401 |
+
query = instance['query']
|
| 402 |
+
ans = instance['answer']
|
| 403 |
+
docs = []
|
| 404 |
+
else:
|
| 405 |
+
query, ans, docs = processdata(instance, noise_rate, passage_num, dataset, correct_rate)
|
| 406 |
+
print(f"Results: \n*********query: {query}, \n*********Answer: {ans}, \n")
|
| 407 |
+
|
| 408 |
+
label, prediction, factlabel = predict(query, ans, docs, model, system, instruction, temperature, dataset)
|
| 409 |
+
print(f"******** Label: {label}\n******** Prediction: {prediction}\n******** factlabel: {factlabel}\n ******** \n")
|
| 410 |
+
|
| 411 |
+
newinstance = {
|
| 412 |
+
'id': instance['id'],
|
| 413 |
+
'query': query,
|
| 414 |
+
'ans': ans,
|
| 415 |
+
'label': label,
|
| 416 |
+
'prediction': prediction,
|
| 417 |
+
'docs': docs,
|
| 418 |
+
'noise_rate': noise_rate,
|
| 419 |
+
'factlabel': factlabel
|
| 420 |
+
}
|
| 421 |
+
# print(f"*********Newinstances: {newinstance}")
|
| 422 |
+
results.append(newinstance)
|
| 423 |
+
f.write(json.dumps(newinstance, ensure_ascii=False) + '\n')
|
| 424 |
+
except Exception as e:
|
| 425 |
+
print("Error:", e)
|
| 426 |
+
continue
|
| 427 |
+
|
| 428 |
+
# Scoring
|
| 429 |
+
tt = 0
|
| 430 |
+
for i in results:
|
| 431 |
+
label = i['label']
|
| 432 |
+
if noise_rate == 1 and label[0] == -1:
|
| 433 |
+
tt += 1
|
| 434 |
+
elif 0 not in label and 1 in label:
|
| 435 |
+
tt += 1
|
| 436 |
+
|
| 437 |
+
scores = {
|
| 438 |
+
'all_rate': tt / len(results),
|
| 439 |
+
'noise_rate': noise_rate,
|
| 440 |
+
'tt': tt,
|
| 441 |
+
'nums': len(results)
|
| 442 |
+
}
|
| 443 |
+
|
| 444 |
+
if '_fact' in dataset:
|
| 445 |
+
fact_tt = 0
|
| 446 |
+
correct_tt = 0
|
| 447 |
+
for i in results:
|
| 448 |
+
if i['factlabel'] == 1:
|
| 449 |
+
fact_tt += 1
|
| 450 |
+
if 0 not in i['label']:
|
| 451 |
+
correct_tt += 1
|
| 452 |
+
fact_check_rate = fact_tt / len(results)
|
| 453 |
+
correct_rate = correct_tt / fact_tt if fact_tt > 0 else 0
|
| 454 |
+
scores.update({
|
| 455 |
+
'fact_check_rate': fact_check_rate,
|
| 456 |
+
'correct_rate': correct_rate,
|
| 457 |
+
'fact_tt': fact_tt,
|
| 458 |
+
'correct_tt': correct_tt
|
| 459 |
+
})
|
| 460 |
+
|
| 461 |
+
print(f"Output File: {output_file}")
|
| 462 |
+
print(f"Complete Output File: {complete_output_file}")
|
| 463 |
+
|
| 464 |
+
# Upload results to Hugging Face Hub
|
| 465 |
+
try:
|
| 466 |
+
print(f"Uploading {complete_output_file} to Hugging Face Hub...")
|
| 467 |
+
upload_file = utils.upload_file(complete_output_file, "")
|
| 468 |
+
if upload_file:
|
| 469 |
+
print(f"File {complete_output_file} uploaded successfully to Hugging Face Hub.")
|
| 470 |
+
else:
|
| 471 |
+
print(f"Failed to upload {complete_output_file} to Hugging Face Hub.")
|
| 472 |
+
except Exception as e:
|
| 473 |
+
print(f"Error uploading file: {e}")
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
# Save results
|
| 477 |
+
try:
|
| 478 |
+
finalResults = {
|
| 479 |
+
'model': modelname,
|
| 480 |
+
'dataset': dataset,
|
| 481 |
+
'temperature': temperature,
|
| 482 |
+
'noise_rate': noise_rate,
|
| 483 |
+
'passage_num': passage_num,
|
| 484 |
+
'correct_rate': correct_rate,
|
| 485 |
+
'factchecking': factchecking,
|
| 486 |
+
'scores': scores,
|
| 487 |
+
}
|
| 488 |
+
score_file = f"{output_file[:-5]}_result.json"
|
| 489 |
+
with open(score_file, 'w') as f:
|
| 490 |
+
json.dump(finalResults, f, ensure_ascii=False, indent=4)
|
| 491 |
+
utils.upload_file(score_file, resultpath)
|
| 492 |
+
# print(f"Scores saved to {score_file} and uploaded to Hugging Face Hub.")
|
| 493 |
+
except Exception as e:
|
| 494 |
+
print("Error saving scores:", e)
|
| 495 |
+
|
| 496 |
+
# with open(score_file, 'w') as f:
|
| 497 |
+
# json.dump(scores, f, ensure_ascii=False, indent=4)
|
| 498 |
+
print(f"Final Results : {finalResults}")
|
| 499 |
+
|
| 500 |
+
return finalResults
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
with gr.Blocks() as demo:
|
| 504 |
+
gr.Markdown("## 🧪 RGB Evaluation Interface")
|
| 505 |
+
|
| 506 |
+
with gr.Row():
|
| 507 |
+
with gr.Column():
|
| 508 |
+
with gr.Group():
|
| 509 |
+
with gr.Row():
|
| 510 |
+
with gr.Column():
|
| 511 |
+
gr.Markdown("### Model and Dataset Configuration")
|
| 512 |
+
modelname = gr.Dropdown(choices=supported_models, value="llama-3.1-8b-instant", label="Model Name")
|
| 513 |
+
dataset = gr.Dropdown(choices=["en", "en_int", "en_fact", "zh"], value="en", label="Dataset", interactive=True)
|
| 514 |
+
with gr.Column():
|
| 515 |
+
gr.Markdown("### API Configuration")
|
| 516 |
+
api_key = gr.Textbox(label="API Key", type="password")
|
| 517 |
+
url = gr.Textbox(label="API URL", value="https://api.groq.com/openai/v1/chat/completions")
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
with gr.Column():
|
| 521 |
+
with gr.Group():
|
| 522 |
+
gr.Markdown("### Evaluation Parameters")
|
| 523 |
+
with gr.Row():
|
| 524 |
+
with gr.Column():
|
| 525 |
+
temperature = gr.Slider(0.0, 1.5, step=0.1, value=0.7, label="Temperature")
|
| 526 |
+
noise_rate = gr.Slider(0.0, 1.0, step=0.1, value=0.2, label="Noise Rate")
|
| 527 |
+
max_instances = gr.Slider(1, 300, step=1, value=2, label="Max Instances to Evaluate")
|
| 528 |
+
with gr.Column():
|
| 529 |
+
correct_rate = gr.Slider(0.0, 1.0, step=0.1, value=0.2, label="Correct Passage Rate")
|
| 530 |
+
passage_num = gr.Slider(0, 10, step=1, value=5, label="Number of Passages")
|
| 531 |
+
factchecking = gr.Checkbox(label="Enable Fact Checking")
|
| 532 |
+
|
| 533 |
+
with gr.Row():
|
| 534 |
+
with gr.Column():
|
| 535 |
+
gr.Markdown("### Run Evaluation Scripts")
|
| 536 |
+
with gr.Group():
|
| 537 |
+
with gr.Row():
|
| 538 |
+
run_evalue_button = gr.Button("🚀 Run (evalue.py) - Noise Accuracy")
|
| 539 |
+
|
| 540 |
+
with gr.Group():
|
| 541 |
+
with gr.Row():
|
| 542 |
+
run_reject_button = gr.Button("🚀 Run (reject_evalue.py) - Reject Rate")
|
| 543 |
+
with gr.Group():
|
| 544 |
+
with gr.Row():
|
| 545 |
+
run_information_button = gr.Button("🚀 Run (evalue.py) - Information Integration")
|
| 546 |
+
with gr.Group():
|
| 547 |
+
with gr.Row():
|
| 548 |
+
run_fact_button = gr.Button("🚀 Run (fact_evalue.py) - Counterfactual Checking")
|
| 549 |
+
|
| 550 |
+
with gr.Column():
|
| 551 |
+
gr.Markdown("### Output")
|
| 552 |
+
output = gr.JSON(label="Output", value={})
|
| 553 |
+
|
| 554 |
+
# Sample DataFrame
|
| 555 |
+
data = {
|
| 556 |
+
"Name": ["Alice", "Bob", "Charlie"],
|
| 557 |
+
"Age": [25, 30, 35],
|
| 558 |
+
"City": ["New York", "London", "Paris"]
|
| 559 |
+
}
|
| 560 |
+
df = pd.DataFrame(data)
|
| 561 |
+
|
| 562 |
+
def show_df():
|
| 563 |
+
return df
|
| 564 |
+
|
| 565 |
+
with gr.Row():
|
| 566 |
+
gr.Markdown("# DataFrame Display Example")
|
| 567 |
+
dataframe_output = gr.Dataframe()
|
| 568 |
+
show_button = gr.Button("Show DataFrame")
|
| 569 |
+
show_button.click(show_df, outputs=dataframe_output)
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
run_evalue_button.click(
|
| 573 |
+
run_evaluation,
|
| 574 |
+
inputs=[
|
| 575 |
+
modelname, dataset, api_key, url, temperature,
|
| 576 |
+
noise_rate, correct_rate, passage_num, factchecking,
|
| 577 |
+
max_instances
|
| 578 |
+
],
|
| 579 |
+
outputs=[output]
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
run_reject_button.click(
|
| 583 |
+
run_reject_rate,
|
| 584 |
+
inputs=[
|
| 585 |
+
modelname, dataset, api_key, url, temperature,
|
| 586 |
+
noise_rate, correct_rate, passage_num, factchecking,
|
| 587 |
+
max_instances
|
| 588 |
+
],
|
| 589 |
+
outputs=[output]
|
| 590 |
+
)
|
| 591 |
+
|
| 592 |
+
run_information_button.click(
|
| 593 |
+
run_information_integration,
|
| 594 |
+
inputs=[
|
| 595 |
+
modelname, dataset, api_key, url, temperature,
|
| 596 |
+
noise_rate, correct_rate, passage_num, factchecking,
|
| 597 |
+
max_instances
|
| 598 |
+
],
|
| 599 |
+
outputs=[output]
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
run_fact_button.click(
|
| 603 |
+
run_counter_factual_checking,
|
| 604 |
+
inputs=[
|
| 605 |
+
modelname, dataset, api_key, url, temperature,
|
| 606 |
+
noise_rate, correct_rate, passage_num, factchecking,
|
| 607 |
+
max_instances
|
| 608 |
+
],
|
| 609 |
+
outputs=[output]
|
| 610 |
+
)
|
| 611 |
+
|
| 612 |
+
demo.launch()
|
constants.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
HF_DATASET_REPO_NAME = "maddiaks/RGB26Demo"
|
| 3 |
+
HF_REPO_TYPE = "space"
|
report.txt
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Noise Level 0.3 (en Dataset)
|
| 2 |
+
|
| 3 |
+
"llama-3.1-8b-instant" -> Done
|
| 4 |
+
"llama-3.3-70b-versatile", -> Done # Remove
|
| 5 |
+
"gemma2-9b-it" -> Done
|
| 6 |
+
"deepseek-r1-distill-llama-70b" -> Done
|
| 7 |
+
"qwen/qwen3-32b" -> Done
|
| 8 |
+
|
| 9 |
+
Noise Level 0.0
|
| 10 |
+
|
| 11 |
+
Noise Level 0.2
|
| 12 |
+
|
| 13 |
+
Noise Level 0.4
|
| 14 |
+
|
| 15 |
+
Noise Level 0.6
|
| 16 |
+
|
| 17 |
+
Noise Level 0.8
|
| 18 |
+
|
| 19 |
+
Noise Level 1.0
|
| 20 |
+
|
| 21 |
+
==========================
|
| 22 |
+
Information Integration (4 Models) => @Krishna [en_int] Dataset
|
| 23 |
+
Noise Level 0.0
|
| 24 |
+
Noise Level 0.2
|
| 25 |
+
Noise Level 0.4
|
| 26 |
+
Noise Level 0.6
|
| 27 |
+
Noise Level 0.8
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
Metric Negative Rejection
|
| 33 |
+
python reject_evalue.py \
|
| 34 |
+
--dataset en \
|
| 35 |
+
--modelname chatglm2-6b \
|
| 36 |
+
--api_key YourAPIKEY
|
| 37 |
+
Run on 4 Models
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
python reject_evalue.py \
|
| 41 |
+
--dataset en \
|
| 42 |
+
--modelname chatglm2-6b \
|
| 43 |
+
--api_key YourAPIKEY
|
| 44 |
+
|
| 45 |
+
|
requirements.txt
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
aiofiles==24.1.0
|
| 2 |
+
annotated-types==0.7.0
|
| 3 |
+
anyio==4.9.0
|
| 4 |
+
Brotli==1.1.0
|
| 5 |
+
certifi==2025.7.14
|
| 6 |
+
charset-normalizer==3.4.2
|
| 7 |
+
click==8.2.1
|
| 8 |
+
fastapi==0.116.1
|
| 9 |
+
ffmpy==0.6.0
|
| 10 |
+
filelock==3.18.0
|
| 11 |
+
fsspec==2025.7.0
|
| 12 |
+
gradio==5.38.0
|
| 13 |
+
gradio_client==1.11.0
|
| 14 |
+
groovy==0.1.2
|
| 15 |
+
h11==0.16.0
|
| 16 |
+
hf-xet==1.1.5
|
| 17 |
+
httpcore==1.0.9
|
| 18 |
+
httpx==0.28.1
|
| 19 |
+
huggingface-hub==0.33.4
|
| 20 |
+
idna==3.10
|
| 21 |
+
Jinja2==3.1.6
|
| 22 |
+
markdown-it-py==3.0.0
|
| 23 |
+
MarkupSafe==3.0.2
|
| 24 |
+
mdurl==0.1.2
|
| 25 |
+
numpy==1.26.4
|
| 26 |
+
orjson==3.11.0
|
| 27 |
+
packaging==25.0
|
| 28 |
+
pandas==2.3.1
|
| 29 |
+
pillow==11.3.0
|
| 30 |
+
pydantic==2.11.7
|
| 31 |
+
pydantic_core==2.33.2
|
| 32 |
+
pydub==0.25.1
|
| 33 |
+
Pygments==2.19.2
|
| 34 |
+
python-dateutil==2.9.0.post0
|
| 35 |
+
python-multipart==0.0.20
|
| 36 |
+
pytz==2025.2
|
| 37 |
+
PyYAML==6.0.2
|
| 38 |
+
requests==2.32.4
|
| 39 |
+
rich==14.0.0
|
| 40 |
+
ruff==0.12.4
|
| 41 |
+
safehttpx==0.1.6
|
| 42 |
+
semantic-version==2.10.0
|
| 43 |
+
shellingham==1.5.4
|
| 44 |
+
six==1.17.0
|
| 45 |
+
sniffio==1.3.1
|
| 46 |
+
starlette==0.47.2
|
| 47 |
+
tomlkit==0.13.3
|
| 48 |
+
tqdm==4.67.1
|
| 49 |
+
typer==0.16.0
|
| 50 |
+
typing-inspection==0.4.1
|
| 51 |
+
typing_extensions==4.14.1
|
| 52 |
+
tzdata==2025.2
|
| 53 |
+
urllib3==2.5.0
|
| 54 |
+
uvicorn==0.35.0
|
| 55 |
+
websockets==15.0.1
|
utils.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import math
|
| 3 |
+
import json
|
| 4 |
+
import numpy as np
|
| 5 |
+
import os
|
| 6 |
+
from huggingface_hub import HfApi
|
| 7 |
+
from constants import HF_DATASET_REPO_NAME, HF_REPO_TYPE
|
| 8 |
+
|
| 9 |
+
supported_models = [
|
| 10 |
+
"llama-3.1-8b-instant", # "llama3-8b-8192",
|
| 11 |
+
# "llama-3.3-70b-versatile", # "llama3-70b-8192",
|
| 12 |
+
"gemma2-9b-it", # "gemma-7b-it",
|
| 13 |
+
"deepseek-r1-distill-llama-70b", # "DeepSeek‑R1‑distill‑llama‑70b",
|
| 14 |
+
"qwen/qwen3-32b"
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def processdata(instance, noise_rate, passage_num, filename, correct_rate = 0):
|
| 19 |
+
query = instance['query']
|
| 20 |
+
ans = instance['answer']
|
| 21 |
+
|
| 22 |
+
neg_num = math.ceil(passage_num * noise_rate)
|
| 23 |
+
pos_num = passage_num - neg_num
|
| 24 |
+
|
| 25 |
+
if '_int' in filename:
|
| 26 |
+
for i in instance['positive']:
|
| 27 |
+
random.shuffle(i)
|
| 28 |
+
print(len(instance['positive']))
|
| 29 |
+
docs = [i[0] for i in instance['positive']]
|
| 30 |
+
if len(docs) < pos_num:
|
| 31 |
+
maxnum = max([len(i) for i in instance['positive']])
|
| 32 |
+
for i in range(1,maxnum):
|
| 33 |
+
for j in instance['positive']:
|
| 34 |
+
if len(j) > i:
|
| 35 |
+
docs.append(j[i])
|
| 36 |
+
if len(docs) == pos_num:
|
| 37 |
+
break
|
| 38 |
+
if len(docs) == pos_num:
|
| 39 |
+
break
|
| 40 |
+
neg_num = passage_num - len(docs)
|
| 41 |
+
if neg_num > 0:
|
| 42 |
+
negative = instance['negative'][:neg_num]
|
| 43 |
+
docs += negative
|
| 44 |
+
elif '_fact' in filename:
|
| 45 |
+
correct_num = math.ceil(passage_num * correct_rate)
|
| 46 |
+
pos_num = passage_num - neg_num - correct_num
|
| 47 |
+
indexs = list(range(len(instance['positive'])))
|
| 48 |
+
selected = random.sample(indexs,min(len(indexs),pos_num))
|
| 49 |
+
docs = [instance['positive_wrong'][i] for i in selected]
|
| 50 |
+
remain = [i for i in indexs if i not in selected]
|
| 51 |
+
if correct_num > 0 and len(remain) > 0:
|
| 52 |
+
docs += [instance['positive'][i] for i in random.sample(remain,min(len(remain),correct_num))]
|
| 53 |
+
if neg_num > 0:
|
| 54 |
+
docs += instance['negative'][:neg_num]
|
| 55 |
+
else:
|
| 56 |
+
if noise_rate == 1:
|
| 57 |
+
neg_num = passage_num
|
| 58 |
+
pos_num = 0
|
| 59 |
+
else:
|
| 60 |
+
if neg_num > len(instance['negative']):
|
| 61 |
+
neg_num = len(instance['negative'])
|
| 62 |
+
pos_num = passage_num - neg_num
|
| 63 |
+
elif pos_num > len(instance['positive']):
|
| 64 |
+
pos_num = len(instance['positive'])
|
| 65 |
+
neg_num = passage_num - pos_num
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
positive = instance['positive'][:pos_num]
|
| 69 |
+
negative = instance['negative'][:neg_num]
|
| 70 |
+
|
| 71 |
+
docs = positive + negative
|
| 72 |
+
|
| 73 |
+
random.shuffle(docs)
|
| 74 |
+
|
| 75 |
+
return query, ans, docs
|
| 76 |
+
|
| 77 |
+
def checkanswer(prediction, ground_truth):
|
| 78 |
+
prediction = prediction.lower()
|
| 79 |
+
if type(ground_truth) is not list:
|
| 80 |
+
ground_truth = [ground_truth]
|
| 81 |
+
labels = []
|
| 82 |
+
for instance in ground_truth:
|
| 83 |
+
flag = True
|
| 84 |
+
if type(instance) == list:
|
| 85 |
+
flag = False
|
| 86 |
+
instance = [i.lower() for i in instance]
|
| 87 |
+
for i in instance:
|
| 88 |
+
if i in prediction:
|
| 89 |
+
flag = True
|
| 90 |
+
break
|
| 91 |
+
else:
|
| 92 |
+
instance = instance.lower()
|
| 93 |
+
if instance not in prediction:
|
| 94 |
+
flag = False
|
| 95 |
+
labels.append(int(flag))
|
| 96 |
+
return labels
|
| 97 |
+
|
| 98 |
+
def getevalue(results):
|
| 99 |
+
results = np.array(results)
|
| 100 |
+
results = np.max(results,axis = 0)
|
| 101 |
+
if 0 in results:
|
| 102 |
+
return False
|
| 103 |
+
else:
|
| 104 |
+
return True
|
| 105 |
+
|
| 106 |
+
def predict(query, ground_truth, docs, model, system, instruction, temperature, dataset):
|
| 107 |
+
'''
|
| 108 |
+
label: 0 for positive, 1 for negative, -1 for not enough information
|
| 109 |
+
|
| 110 |
+
'''
|
| 111 |
+
if len(docs) == 0:
|
| 112 |
+
text = instruction.format(QUERY=query, DOCS='')
|
| 113 |
+
prediction = model.generate(text, temperature)
|
| 114 |
+
else:
|
| 115 |
+
docs = '\n'.join(docs)
|
| 116 |
+
text = instruction.format(QUERY=query, DOCS=docs)
|
| 117 |
+
prediction = model.generate(text, temperature, system)
|
| 118 |
+
|
| 119 |
+
if 'zh' in dataset:
|
| 120 |
+
prediction = prediction.replace(" ","")
|
| 121 |
+
|
| 122 |
+
if '信息不足' in prediction or 'insufficient information' in prediction:
|
| 123 |
+
labels = [-1]
|
| 124 |
+
else:
|
| 125 |
+
labels = checkanswer(prediction, ground_truth)
|
| 126 |
+
|
| 127 |
+
factlabel = 0
|
| 128 |
+
|
| 129 |
+
if '事实性错误' in prediction or 'factual errors' in prediction:
|
| 130 |
+
factlabel = 1
|
| 131 |
+
|
| 132 |
+
return labels,prediction, factlabel
|
| 133 |
+
|
| 134 |
+
def upload_file(filename: str, folder_path: str) -> str:
|
| 135 |
+
"""Upload a file to Hugging Face hub from the specified folder."""
|
| 136 |
+
try:
|
| 137 |
+
# file_path = os.path.join(folder_path, filename)
|
| 138 |
+
# if not os.path.exists(file_path):
|
| 139 |
+
# raise FileNotFoundError(f"File {file_path} does not exist.")
|
| 140 |
+
|
| 141 |
+
api = HfApi()
|
| 142 |
+
api.upload_file(
|
| 143 |
+
path_or_fileobj=filename,
|
| 144 |
+
path_in_repo=f"{folder_path}/{filename}",
|
| 145 |
+
repo_id=HF_DATASET_REPO_NAME,
|
| 146 |
+
repo_type=HF_REPO_TYPE,
|
| 147 |
+
token=os.getenv("HF_TOKEN")
|
| 148 |
+
)
|
| 149 |
+
print(f"Uploaded {filename} to {HF_DATASET_REPO_NAME}")
|
| 150 |
+
return True
|
| 151 |
+
except Exception as e:
|
| 152 |
+
print(f"Error uploading {filename}: {e}")
|
| 153 |
+
return None
|