gasmichel's picture
Upload folder using huggingface_hub
1a89bb0 verified
import re
import os
from transformers import GenerationConfig, AutoModelForCausalLM, AutoTokenizer
import json
import numpy as np
import logging
import sys
from contextlib import redirect_stdout, redirect_stderr
import tqdm.auto as tqdm
# BEFORE importing vLLM
class QuoteTagger:
def tag(self, context, quote_s):
predictions = []
currentQuote = ""
in_quote = False
lastPar = None
if quote_s == "‘" or quote_s == "’" or quote_s == "'":
quote_symbol = "SINGLE_QUOTE"
elif quote_s == "“" or quote_s == "”" or quote_s == '"' or quote_s == "“":
quote_symbol = "DOUBLE_QUOTE"
else :
# default to double quote
quote_symbol = "DOUBLE_QUOTE"
for byte_id, w_char in enumerate(context):
par_id = 0
w = None
if w_char == "“" or w_char == "”" or w_char == '"':
w = "DOUBLE_QUOTE"
elif w_char == "‘" or w_char == "’" or w_char == "'":
if byte_id < len(context) - 1:
suff = context[byte_id + 1 : byte_id + 3]
if (
suff != "s "
and suff != "d "
and suff != "ll"
and suff != "ve"
and suff != "m "
):
w = "SINGLE_QUOTE"
else :
w = "SINGLE_QUOTE"
elif w_char == "\n" and context[byte_id - 1] == "\n" :
par_id += 1
if len(currentQuote) > 0:
predictions.append(currentQuote)
currentQuote = ""
in_quote = False
if w == quote_symbol:
# print(byte_id)
if in_quote :
if len(currentQuote) > 0:
currentQuote += w_char
predictions.append(currentQuote)
in_quote = False
currentQuote = ""
else:
in_quote = True
if in_quote :
currentQuote += w_char
return predictions
tagger = QuoteTagger()
def get_prompt(context, tokenizer) :
try :
quote = re.findall('Q\|>([^<]+)<\|Q', context)[0]
context = re.sub('<\|Q\|>[^<]+<\|Q\|>', "[TARGET]", context)
except :
return None
start_q = quote[0]
end_q = quote[-1]
if all([quote[1] != " ", context[:2] == f"{end_q} "]):
context = context[2:]
# Subbing all special markers
context = re.sub('\|([\d]+)\|([^\|]+)\|[\d]+\|', lambda x: x.group(2), context)
# Paragraph IDs as headers
x = context.split('\n\n')
x = [f"[{f}] " + xx for f, xx in enumerate(x)]
context = '\n\n'.join(x)
# Replace quotes by special markers
quotes = tagger.tag(context, start_q)
for idx, q in enumerate(quotes) :
if "[TARGET]" not in q :
context = context.replace(q, f"[QUOTE_{idx+1}]")
msg = [{"role" : "system", "content" : """You are an expert in linguistic. You like to read book and excel at analyzing dialogues in literature."""}]
# msg = []
prompt = """Given a small narrative passage, where each quote content is masked, your role is to extract speech verbs, adverbs, adjectives and nouns that indicate how a target quotation is being uttered. You will be given a target quotation marked with [TARGET] that occur in the passage. You need to extract speech verbs, adverbs, adjectives and nouns that follow these criteria:
- It must be either a speech-verb, an adverb, a noun or an adjective.
- It must be one word only.
- It must must be a speech descriptor of the target quotation.
- If an adverb, its must be a descriptor of one of the speech-verb describing the target quotation.
- If a verb, **ensure that it is a speech-verb and not a verb describing anything else than speech.**
Note that multiple speech-verbs can be found and that target quotations can have no associated speech-verbs.
Return a dictionary where keys are the words extracted in the final step and the values is another dictionary with keys 'id' for the paragraph id of the word, 'type' for the word type (verb, adverb, adjective, noun) and 'confidence' an integer between 0 and 10 measuring how confident you are in your prediction, 0 being not confident at all and 10 being sure you are right.
Before creating the dictionary, make sure again that all the criteria above are respected.
**Only generate this dictionary and nothing else. Return an empty dictionary if no words were found.**
Passage:
[0] Ella handed the notebook to Jay, eyes uncertain.
[1] Jay flipped through the sketches, pausing at one. [QUOTE_1] She nodded.
[2] [TARGET] whispered Ella slowly.
Target quotation: [TARGET]"""
msg.append({"role" : "user" , "content" : prompt})
answer = """```json
{
"whispered": {
"id": "2",
"type": "verb",
"confidence": 10
},
"slowly": {
"id": "2",
"type": "adverb",
"confidence": 10
}
}
```"""
msg.append({"role" : "assistant" , "content" : answer})
next_p = """Passage:
[0] She went on, half laughing
[1] [TARGET] Then we went to the park, and he said [QUOTE_1]
Target quotation: [TARGET]"""
msg.append({"role" : "user" , "content" : next_p})
answer = """```json
{
"went": {
"id": "0",
"type": "verb",
"confidence": 9
},
"laughing": {
"id": "0",
"type": "verb",
"confidence": 9
}
}
```"""
msg.append({"role" : "assistant" , "content" : answer})
next_p = """Passage:
[0] [QUOTE_1]
[1] Jake nodded and started saying, with a dark smile [TARGET]
Target quotation: [TARGET]"""
msg.append({"role" : "user" , "content" : next_p})
answer = """```json
{
"saying": {
"id": "1",
"type": "verb",
"confidence": 9
}
}
```"""
msg.append({"role" : "assistant" , "content" : answer})
next_p = """Passage:
[0] [QUOTE_1] Jake continued. [QUOTE_2]
[1] [TARGET]
[2] [QUOTE_3] he added.
Target quotation: [TARGET]"""
msg.append({"role" : "user" , "content" : next_p})
answer = """```json
{}
```"""
msg.append({"role" : "assistant" , "content" : answer})
next_p = """Passage:
[0] Rain pattered against the window as Mia whispered, [QUOTE_1]
[1] Lena staring into the dark. [TARGET], she said, weeping softly.
Target quotation: [TARGET]"""
msg.append({"role" : "user" , "content" : next_p})
answer = """```json
{
"said": {
"id": "1",
"type": "verb",
"confidence": 10
},
"weeping": {
"id": "1",
"type": "verb",
"confidence": 8
},
"softly": {
"id": "1",
"type": "adverb",
"confidence": 9
}
}
```"""
msg.append({"role" : "assistant" , "content" : answer})
next_p = "Passage:\n\n" + f"""{context}
Target quotation: [TARGET]"""
msg.append({"role" : "user" , "content" : next_p})
return tokenizer.apply_chat_template(
msg,
tokenize=False,
add_generation_prompt=True,
enable_thinking= False
)
class Tee:
def __init__(self, *streams):
self.streams = streams
def write(self, data):
for s in self.streams:
s.write(data)
def flush(self):
for s in self.streams:
s.flush()
#log_file = open("logs/progress_sve.log", "w")
#sys.stdout = Tee(sys.stdout, log_file)
#sys.stderr = Tee(sys.stderr, log_file)
if __name__ == "__main__" :
#logger = logging.getLogger()
#handler = logging.StreamHandler(sys.stdout) # Send output to stdout
#handler.setLevel(logging.INFO) # Set level for handler
#logger.addHandler(handler)
#logger.setLevel(logging.INFO) # Set level for logger
from vllm import LLM, SamplingParams
model_name = "/lustre/fsn1/projects/rech/knb/ujg36yr/models/Phi4/"
llm = LLM(model_name, max_model_len=4096)
os.makedirs("/lustre/fsn1/projects/rech/knb/ujg36yr/filtered_tts_data/model_out/", exist_ok=True)
data = json.load(open('/lustre/fsn1/projects/rech/knb/ujg36yr/filtered_tts_data/train_filtered_sv_emo.json'))
data = json.load(open('/lustre/fsn1/projects/rech/knb/ujg36yr/filtered_tts_data/phi4_out/test_t5_context.json'))
tokenizer = AutoTokenizer.from_pretrained(model_name)
sps = SamplingParams(temperature=0,top_p=1.0, stop_token_ids=[100265], max_tokens=400)
# Start with SV EMO subset
prompts = []
errors =0
maps = {}
for idx in range(len(data["sv_emo"])) :
context = data['sv_emo'][idx]['context']
p = get_prompt(context, tokenizer)
if p is not None :
maps[len(prompts)] = idx
prompts.append(p)
else :
errors +=1
print(f"Processing {len(prompts)} prompts ({errors} with errors)")
outputs = llm.generate(prompts, sps)
out = []
for idx, output in enumerate(outputs):
prompt = output.prompt
try :
generated_text = eval(output.outputs[0].text.replace("```json", "").replace("```",""))
except :
generated_text = {}
original = data["sv_emo"][maps[idx]].copy()
original["preds"] = generated_text
out.append(original)
with open('/lustre/fsn1/projects/rech/knb/ujg36yr/filtered_tts_data/model_out/phi4-out.sv_emo.json','w') as f :
json.dump(out,f)
del out, outputs, prompts
# Then SV subset
prompts = []
errors = 0
maps = {}
for idx in range(len(data["sv"])) :
context = data['sv'][idx]['context']
p = get_prompt(context, tokenizer)
if p is not None :
maps[len(prompts)] = idx
prompts.append(p)
else :
errors +=1
print(f"Processing {len(prompts)} prompts ({errors} with errors)")
outputs = llm.generate(prompts, sps)
out = []
for idx, output in enumerate(outputs):
prompt = output.prompt
try :
generated_text = eval(output.outputs[0].text.replace("```json", "").replace("```",""))
except :
generated_text = {}
original = data["sv"][maps[idx]].copy()
original["preds"] = generated_text
out.append(original)
with open('/lustre/fsn1/projects/rech/knb/ujg36yr/filtered_tts_data/model_out/phi4-out.sv.json','w') as f :
json.dump(out,f)