Upload 3 files
Browse files- lib%2F__init__.py +0 -0
- lib%2Fgraph_extract.py +151 -0
- lib%2Fsamples.py +46 -0
lib%2F__init__.py
ADDED
File without changes
|
lib%2Fgraph_extract.py
ADDED
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import re
|
3 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig
|
4 |
+
import torch
|
5 |
+
import warnings
|
6 |
+
import spaces
|
7 |
+
|
8 |
+
flash_attn_installed = False
|
9 |
+
# try:
|
10 |
+
# import subprocess
|
11 |
+
# print("Installing flash-attn...")
|
12 |
+
# subprocess.run(
|
13 |
+
# "pip install flash-attn --no-build-isolation",
|
14 |
+
# env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},
|
15 |
+
# shell=True,
|
16 |
+
# )
|
17 |
+
# flash_attn_installed = True
|
18 |
+
# except Exception as e:
|
19 |
+
# print(f"Error installing flash-attn: {e}")
|
20 |
+
|
21 |
+
|
22 |
+
# Suppress specific warnings
|
23 |
+
warnings.filterwarnings(
|
24 |
+
"ignore",
|
25 |
+
message="You have modified the pretrained model configuration to control generation.",
|
26 |
+
)
|
27 |
+
warnings.filterwarnings(
|
28 |
+
"ignore",
|
29 |
+
message="You are not running the flash-attention implementation, expect numerical differences.",
|
30 |
+
)
|
31 |
+
|
32 |
+
print("Initializing application...")
|
33 |
+
|
34 |
+
model = AutoModelForCausalLM.from_pretrained(
|
35 |
+
"sciphi/triplex",
|
36 |
+
trust_remote_code=True,
|
37 |
+
# attn_implementation="flash_attention_2" if flash_attn_installed else None,
|
38 |
+
torch_dtype=torch.bfloat16,
|
39 |
+
device_map="auto",
|
40 |
+
low_cpu_mem_usage=True,#advised if any device map given
|
41 |
+
).eval()
|
42 |
+
|
43 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
44 |
+
"sciphi/triplex",
|
45 |
+
trust_remote_code=True,
|
46 |
+
# attn_implementation="flash_attention_2" if flash_attn_installed else None,
|
47 |
+
torch_dtype=torch.bfloat16,
|
48 |
+
)
|
49 |
+
|
50 |
+
|
51 |
+
print("Model and tokenizer loaded successfully.")
|
52 |
+
|
53 |
+
# Set up generation config
|
54 |
+
generation_config = GenerationConfig.from_pretrained("sciphi/triplex")
|
55 |
+
generation_config.max_length = 2048
|
56 |
+
generation_config.pad_token_id = tokenizer.eos_token_id
|
57 |
+
|
58 |
+
|
59 |
+
@spaces.GPU
|
60 |
+
def triplextract(text, entity_types, predicates):
|
61 |
+
input_format = """Perform Named Entity Recognition (NER) and extract knowledge graph triplets from the text. NER identifies named entities of given entity types, and triple extraction identifies relationships between entities using specified predicates. Return the result as a JSON object with an "entities_and_triples" key containing an array of entities and triples.
|
62 |
+
|
63 |
+
**Entity Types:**
|
64 |
+
{entity_types}
|
65 |
+
|
66 |
+
**Predicates:**
|
67 |
+
{predicates}
|
68 |
+
|
69 |
+
**Text:**
|
70 |
+
{text}
|
71 |
+
"""
|
72 |
+
message = input_format.format(
|
73 |
+
entity_types = json.dumps({"entity_types": entity_types}),
|
74 |
+
predicates = json.dumps({"predicates": predicates}),
|
75 |
+
text = text)
|
76 |
+
|
77 |
+
# message = input_format.format(
|
78 |
+
# entity_types=entity_types, predicates=predicates, text=text
|
79 |
+
# )
|
80 |
+
|
81 |
+
messages = [{"role": "user", "content": message}]
|
82 |
+
|
83 |
+
print("Tokenizing input...")
|
84 |
+
input_ids = tokenizer.apply_chat_template(
|
85 |
+
messages, add_generation_prompt=True, return_tensors="pt"
|
86 |
+
).to(model.device)
|
87 |
+
|
88 |
+
attention_mask = input_ids.ne(tokenizer.pad_token_id)
|
89 |
+
|
90 |
+
print("Generating output...")
|
91 |
+
try:
|
92 |
+
with torch.no_grad():
|
93 |
+
output = model.generate(
|
94 |
+
input_ids=input_ids,
|
95 |
+
attention_mask=attention_mask,
|
96 |
+
generation_config=generation_config,
|
97 |
+
do_sample=True,
|
98 |
+
)
|
99 |
+
|
100 |
+
decoded_output = tokenizer.decode(output[0], skip_special_tokens=True)
|
101 |
+
print("Decoding output completed.")
|
102 |
+
|
103 |
+
return decoded_output
|
104 |
+
except torch.cuda.OutOfMemoryError as e:
|
105 |
+
print(f"CUDA out of memory error: {e}")
|
106 |
+
return "Error: CUDA out of memory."
|
107 |
+
except Exception as e:
|
108 |
+
print(f"Error in generation: {e}")
|
109 |
+
return f"Error in generation, please try again: {str(e)}"
|
110 |
+
|
111 |
+
def parse_triples(prediction):
|
112 |
+
entities = {}
|
113 |
+
relationships = []
|
114 |
+
|
115 |
+
try:
|
116 |
+
data = json.loads(prediction)
|
117 |
+
items = data.get("entities_and_triples", [])
|
118 |
+
except json.JSONDecodeError:
|
119 |
+
json_match = re.search(r"```json\s*(.*?)\s*```", prediction, re.DOTALL)
|
120 |
+
if json_match:
|
121 |
+
try:
|
122 |
+
data = json.loads(json_match.group(1))
|
123 |
+
items = data.get("entities_and_triples", [])
|
124 |
+
except json.JSONDecodeError:
|
125 |
+
items = re.findall(r"\[(.*?)\]", prediction)
|
126 |
+
else:
|
127 |
+
items = re.findall(r"\[(.*?)\]", prediction)
|
128 |
+
|
129 |
+
for item in items:
|
130 |
+
if isinstance(item, str):
|
131 |
+
try:
|
132 |
+
if ":" in item:
|
133 |
+
id, entity = item.split(",", 1)
|
134 |
+
id = id.strip("[]").strip()
|
135 |
+
entity_type, entity_value = entity.split(":", 1)
|
136 |
+
entities[id] = {
|
137 |
+
"type": entity_type.strip(),
|
138 |
+
"value": entity_value.strip(),
|
139 |
+
}
|
140 |
+
else:
|
141 |
+
parts = item.split()
|
142 |
+
if len(parts) >= 3:
|
143 |
+
source = parts[0].strip("[]")
|
144 |
+
relation = " ".join(parts[1:-1])
|
145 |
+
target = parts[-1].strip("[]")
|
146 |
+
relationships.append((source, relation.strip(), target))
|
147 |
+
except Exception as e:
|
148 |
+
# TODO: Handle gracefully
|
149 |
+
print(f"Error in processing: {item}: {e}")
|
150 |
+
|
151 |
+
return entities, relationships
|
lib%2Fsamples.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections import namedtuple
|
2 |
+
|
3 |
+
Snippet = namedtuple('Snippet', ['text_input', 'entity_types', 'predicates'])
|
4 |
+
|
5 |
+
snippets = {
|
6 |
+
'paris': Snippet(
|
7 |
+
text_input="""Paris is the capital of France. It has a population of two million people.
|
8 |
+
The Eiffel Tower, located in Paris, is a famous landmark with a height of 324 meters.
|
9 |
+
Paris is known for its romantic atmosphere.""",
|
10 |
+
entity_types="LOCATION, POPULATION, STYLE",
|
11 |
+
predicates="HAS, IS"
|
12 |
+
),
|
13 |
+
|
14 |
+
'dickens': Snippet(
|
15 |
+
text_input="""It was the best of times, it was the worst of times, it was the age of wisdom,
|
16 |
+
it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity,
|
17 |
+
it was the season of Light, it was the season of Darkness, it was the spring of hope,
|
18 |
+
it was the winter of despair, we had everything before us, we had nothing before us,
|
19 |
+
we were all going direct to Heaven, we were all going direct the other way – in short,
|
20 |
+
the period was so far like the present period, that some of its noisiest authorities
|
21 |
+
insisted on its being received, for good or for evil, in the superlative degree of comparison only.""",
|
22 |
+
entity_types="EMOTION, EVENT, OUTCOME, PLACE",
|
23 |
+
predicates="WAS, HAD, WERE, IS"
|
24 |
+
),
|
25 |
+
|
26 |
+
'tech_company': Snippet(
|
27 |
+
text_input="""Apple Inc. was founded by Steve Jobs, Steve Wozniak, and Ronald Wayne in 1976.
|
28 |
+
Headquartered in Cupertino, California, Apple designs and produces consumer electronics,
|
29 |
+
software, and online services. The company's flagship products include the iPhone smartphone,
|
30 |
+
iPad tablet, and Mac personal computer. As of 2023, Apple has over 150000 employees worldwide
|
31 |
+
and generates annual revenue exceeding $350 billion.""",
|
32 |
+
entity_types="COMPANY, PERSON, PRODUCT, LOCATION, DATE, EVENT",
|
33 |
+
predicates="FOUNDED, PRODUCES, HAS, IN, EMPLOYEES, "
|
34 |
+
),
|
35 |
+
|
36 |
+
'climate_change': Snippet(
|
37 |
+
text_input="""Global warming is causing significant changes to Earth's climate. The average global
|
38 |
+
temperature has increased by approximately 1C since the pre-industrial era. This warming is
|
39 |
+
primarily caused by human activities, particularly the emission of greenhouse gases like carbon dioxide.
|
40 |
+
The Paris Agreement, signed in 2015, aims to limit global temperature increase to well below 2°C above
|
41 |
+
pre-industrial levels. To achieve this goal, many countries are implementing policies to reduce carbon
|
42 |
+
emissions and transition to renewable energy sources.""",
|
43 |
+
entity_types="PHENOMENON, PLANET, TEMPERATURE, CAUSE, CHEMICAL, AGREEMENT, DATE, GOAL, POLICY",
|
44 |
+
predicates="CAUSES, INCREASED_BY, CAUSED_BY, SIGNED_IN, AIMS_TO, IMPLEMENTING"
|
45 |
+
)
|
46 |
+
}
|