1
0
mw-lifecycle-analysis/p2/quest/python_scripts/info_labeling.py

136 lines
9.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from transformers import AutoModelForCausalLM, AutoTokenizer, OlmoForCausalLM
import torch
import csv
import pandas as pd
import re
cache_directory = "/projects/p32852/cache/"
#load in the different models
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
print(torch.cuda.get_device_name(0))
print(torch.cuda.get_device_properties(0))
#olmo = AutoModelForCausalLM.from_pretrained("allenai/OLMo-2-0325-32B", cache_dir=cache_directory).to(device)
#tokenizer = AutoTokenizer.from_pretrained("allenai/OLMo-2-0325-32B", cache_dir=cache_directory)
olmo = AutoModelForCausalLM.from_pretrained("allenai/OLMo-2-1124-13B", cache_dir=cache_directory).to(device)
tokenizer = AutoTokenizer.from_pretrained("allenai/OLMo-2-1124-13B")
#TODO: text_preprocessing per https://arxiv.org/pdf/1902.07093
priming = "For the **GIVEN COMMENT**, please categorize it into one of the defined [[CATEGORIES]]. Each [[CATEGORY]] is described in the TYPOLOGY for reference.Your task is to match the **GIVEN COMMENT** to the **[[CATEGORY]]** that most accurately describes the content of the comment. Only provide the category as your output. Do not provide any text beyond the category name."
#the typology descriptions are taken straight from https://arxiv.org/pdf/1902.07093
typology = """
TYPOLOGY:
[[EXPECTED BEHAVIOR]], in which stakeholders discuss, from the users perspective, the expected or ideal situation affected by the issue. For example, a participant commented: “My suggestion/request in the near term would be to have an option to make the vocabulary read only so that users who want to be able to leave spacy alone to do streaming data processing dont need to worry about changing memory requirements.”
[[MOTIVATION]], in which stakeholders elaborate on why the issue needs to be fixed or a feature needs to be added. For example, in support of redesigning TensorFlow's input pipeline one participant wrote: “Right now, this method starves my GPU all the time, which is a shame because most other [deep learning] frameworks manage to make this much more performantly.”
[[OBSERVED BUG BEHAVIOR]], which only appears in bug reports and focuses on describing the observed behaviour of the bug. For example, one participant commented: “I found strange behavior using the pipe() method”, then started to describe this behavior.
[[BUG REPRODUCTION]], which also only appears in bug reports and focuses on any report, request, and/or question regarding the reproduction of the bug. For example, one participant commented that a bug was reproducible: “Same problem here, working on Windows 10 with German text.”
[[INVESTIGATION AND EXPLORATION]], in which OSS stakeholders discuss their exploration of ideas about the problem that was thought to have caused the issue. For example, “This result confirms my hypothesis but also shows that the memory increase really isnt all that significant... But it still points to a potential flaw in the design of the library.”
[[SOLUTION DISCUSSION]] is framed around the solution space from the developers point of view, in which participants discuss design ideas and implementation details, as well as suggestions, constraints, challenges, and useful references around such topics. For example, “I know there are multiple ways of approaching this however I strongly recommend node-gyp for performance.”
[[CONTRIBUTION AND COMMITMENT]], in which participants call for contributors and/or voice willingness or unwillingness to contribute to resolving the issue. For example, one potential collaborator said: “I will gladly contribute in any way I can, however, this is something I will not be able to do alone. Would be best if a few other people is interested as well...”
[[TASK PROGRESS]], in which stakeholders request or report progress of tasks and sub-tasks towards the solution of the issue. For example, “I made an initial stab at it... - this is just a proof of concept that gets the version string into nodejs. Ill start working on adding the swig interfaces...”
[[TESTING]], in which participants discuss the testing procedure and results, as well as the system environment, code, data, and feedback involved in testing. For example, “Tested on 0.101 and master - the issue seems to be fixed on master not just for the example document, but for the entire corpus...”
[[FUTURE PLAN]], in which participants discuss the long-term plan related to the issue; such plans usually involve work/ideas that are not required to close the current issue. For example, “For the futures, stay tuned, as were prototyping something in this direction.”
[[POTENTIAL NEW ISSUES AND REQUESTS]], in which participants identify and discuss new bugs or needed features while investigating and addressing the current issue. For example, when discussing a bug in scikit-learn about parallel execution that causes process hanging, one participant said: “As a side point, I note there seems to be a lot more joblib parallelisation overhead in master... that wasnt there in 0.14.”
[[SOLUTION USAGE]] was usually discussed once a full or partial solution of the issue was released and stakeholders asked questions or provided suggestions about how to use the library with the new solution update. For example, “Please help me how to continue training the model [with the new release].”
[[WORKAROUNDS]] focus on discussions about temporary or alternative solutions that can help overcome the issue until the official fix or enhancement is released. For example, in a discussion regarding memory growth for streamed data, one participant expressed his temporary solution: “For now workaround with reloading / collecting nlp object works quite ok in production.”
[[ISSUE CONTENT MANAGEMENT]] focuses on redirecting the discussions and controlling the quality of the comments with respect to the issue. For example, “We might want to move this discussion to here: [link to another issue]”
[[ACTION ON ISSUE]], in which participants comment on the proper actions to perform on the issue itself. For example, “Im going to close this issue because its old and most of the information here is now out of date.”
[[SOCIAL CONVERSATION]], in which participants express emotions such as appreciation, disappointment, annoyance, regret, etc. or engage in small talk. For example, “Im so glad that this has received so much thought and attention!”
"""
#instructions="Only respond with the GIVEN COMMENT's [[CATEGORY]] classification. Do not provide any more information."
instructions="The comment's category is: "
with open("/home/nws8519/git/mw-lifecycle-analysis/p2/quest/072325_biberplus_labels.csv", mode='r', newline='') as file:
reader = csv.reader(file)
array_of_categorizations = []
index = -1
for row in reader:
index += 1
if index <= 0:
continue
text_dict = {}
#organizing the data from each citation
text_dict['id'] = row[0]
text_dict['task_title'] = row[1]
text_dict['comment_text'] = row[2]
text_dict['comment_type'] = row[12]
raw_text = text_dict['comment_text']
#print(raw_text)
# comment_text preprocessing per https://arxiv.org/pdf/1902.07093
# 1. replace code with CODE
comment_text = re.sub(r'`[^`]+`', 'CODE', raw_text) # Inline code
comment_text = re.sub(r'```[\s\S]+?```', 'CODE', comment_text) # Block code
# 2. replace quotes with QUOTE
lines = comment_text.split('\n')
lines = ['QUOTE' if line.strip().startswith('>') else line for line in lines]
comment_text = '\n'.join(lines)
# 3. replace Gerrit URLs with GERRIT URL
gerrit_url_pattern = r'https://gerrit\.wikimedia\.org/r/\d+'
comment_text = re.sub(gerrit_url_pattern, 'GERRIT_URL', comment_text)
# replace URL with URL
url_pattern = r'https?://[^\s]+'
comment_text = re.sub(url_pattern, 'URL', comment_text)
# 4. if possible, replace @ with SCREEN_NAME
comment_text = re.sub(r'(^|\s)@\w+', 'SCREEN_NAME', comment_text)
#print(comment_text)
text_dict['cleaned_comment_text'] = comment_text
#build out prompt construction; more specificity in data provided
given_data = f"**GIVEN COMMENT: \n ' Type -{text_dict['comment_type']} \n Text -{text_dict['cleaned_comment_text']}**'\n"
prompt_question="What do you think about this message? What are they saying?"
#prompt = f"{prompt_1}\n\n{example_1}\n\n{example_2}\n\n{example_3}\n\n{example_4}\n\n{given_data}\n"
prompt = f"{priming}\n{typology}\n\n{given_data}\n{instructions}"
#handoff to the model
inputs = tokenizer(prompt, return_tensors='pt', return_token_type_ids=False).to(device)
#deterministic sampling and getting the response back
response = olmo.generate(**inputs, max_new_tokens=256, do_sample=False)
response_txt = tokenizer.batch_decode(response, skip_special_tokens=True)[0]
#print("this is the response:::: ----------------------------")
#print(response_txt)
#getting the resulting codes
#codes_id = response_txt.rfind("CATEGORIES:")
#writing them to the citation_dicti
match = re.search(r"The comment's category is: \s*(.*)", response_txt)
if match:
following_text = match.group(1).strip("[]*")
else:
following_text = "NO CATEGORY"
#print(following_text)
text_dict['olmo_category'] = following_text
'''
for item in result.strip(";").split(";"):
key_value = item.strip().split('. ')
if len(key_value) == 2:
key = key_value[0]
value = key_value[1]
cite_dict[key] = value
'''
array_of_categorizations.append(text_dict)
#CSV everything
df = pd.DataFrame(array_of_categorizations)
df.to_csv('072525_olmo_messages_categorized.csv', index=False)