File size: 10,658 Bytes
1a89bb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340

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)