import json import re from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig import torch import warnings import spaces flash_attn_installed = False try: import subprocess print("Installing flash-attn...") subprocess.run( "pip install flash-attn --no-build-isolation", env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"}, shell=True, ) flash_attn_installed = True except Exception as e: print(f"Error installing flash-attn: {e}") # Suppress specific warnings warnings.filterwarnings( "ignore", message="You have modified the pretrained model configuration to control generation.", ) warnings.filterwarnings( "ignore", message="You are not running the flash-attention implementation, expect numerical differences.", ) print("Initializing application...") model = AutoModelForCausalLM.from_pretrained( "sciphi/triplex", trust_remote_code=True, attn_implementation="flash_attention_2" if flash_attn_installed else None, torch_dtype=torch.bfloat16, device_map="auto", low_cpu_mem_usage=True,#advised if any device map given ).eval() tokenizer = AutoTokenizer.from_pretrained( "sciphi/triplex", trust_remote_code=True, attn_implementation="flash_attention_2" if flash_attn_installed else None, torch_dtype=torch.bfloat16, ) print("Model and tokenizer loaded successfully.") # Set up generation config generation_config = GenerationConfig.from_pretrained("sciphi/triplex") generation_config.max_length = 2048 generation_config.pad_token_id = tokenizer.eos_token_id @spaces.GPU def triplextract(text, entity_types, predicates): 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. **Entity Types:** {entity_types} **Predicates:** {predicates} **Text:** {text} """ message = input_format.format( entity_types = json.dumps({"entity_types": entity_types}), predicates = json.dumps({"predicates": predicates}), text = text) # message = input_format.format( # entity_types=entity_types, predicates=predicates, text=text # ) messages = [{"role": "user", "content": message}] print("Tokenizing input...") input_ids = tokenizer.apply_chat_template( messages, add_generation_prompt=True, return_tensors="pt" ).to(model.device) attention_mask = input_ids.ne(tokenizer.pad_token_id) print("Generating output...") try: with torch.no_grad(): output = model.generate( input_ids=input_ids, attention_mask=attention_mask, generation_config=generation_config, do_sample=True, ) decoded_output = tokenizer.decode(output[0], skip_special_tokens=True) print("Decoding output completed.") return decoded_output except torch.cuda.OutOfMemoryError as e: print(f"CUDA out of memory error: {e}") return "Error: CUDA out of memory." except Exception as e: print(f"Error in generation: {e}") return f"Error in generation, please try again: {str(e)}" def parse_triples(prediction): entities = {} relationships = [] try: data = json.loads(prediction) items = data.get("entities_and_triples", []) except json.JSONDecodeError: json_match = re.search(r"```json\s*(.*?)\s*```", prediction, re.DOTALL) if json_match: try: data = json.loads(json_match.group(1)) items = data.get("entities_and_triples", []) except json.JSONDecodeError: items = re.findall(r"\[(.*?)\]", prediction) else: items = re.findall(r"\[(.*?)\]", prediction) for item in items: if isinstance(item, str): try: if ":" in item: id, entity = item.split(",", 1) id = id.strip("[]").strip() entity_type, entity_value = entity.split(":", 1) entities[id] = { "type": entity_type.strip(), "value": entity_value.strip(), } else: parts = item.split() if len(parts) >= 3: source = parts[0].strip("[]") relation = " ".join(parts[1:-1]) target = parts[-1].strip("[]") relationships.append((source, relation.strip(), target)) except Exception as e: # TODO: Handle gracefully print(f"Error in processing: {item}: {e}") return entities, relationships