Spaces:
Running
Running
File size: 9,955 Bytes
7a064ce fc3bf2a 7a064ce fc3bf2a 7a064ce fc3bf2a 7a064ce fc3bf2a 7a064ce fc3bf2a 7a064ce fc3bf2a 19bbd13 fc3bf2a 7a064ce fc3bf2a 7a064ce fc3bf2a 940fcc5 fc3bf2a e9aaf5a fc3bf2a 2ca006a 7a064ce 2ca006a fc3bf2a 2ca006a fc3bf2a 1b7fb2e fc3bf2a 1b7fb2e fc3bf2a 7a064ce fc3bf2a 7a064ce fc3bf2a e9aaf5a fc3bf2a 7a064ce fc3bf2a 7a064ce fc3bf2a 7a064ce fc3bf2a 1b7fb2e fc3bf2a 1b7fb2e fc3bf2a | 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 | import hashlib
import io
import json
import os
import re
import docx
import fitz
import pytesseract
from openai import OpenAI
from PIL import Image
from werkzeug.datastructures import FileStorage
from .logger import get_logger
logger = get_logger()
CHAT_MODEL = os.getenv("CHAT_MODEL", "gpt-5.6-luna")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
def ocr_page(page: fitz.Page, zoom: float = 2.0) -> str:
logger.info(f"Performing OCR on page {page.number}")
mat = fitz.Matrix(zoom, zoom)
pix = page.get_pixmap(matrix=mat, alpha=False) # type: ignore
img = Image.open(io.BytesIO(pix.tobytes("png")))
return pytesseract.image_to_string(img)
def blocks_text(tp: fitz.TextPage) -> str:
blocks = tp.extractBLOCKS()
blocks.sort(key=lambda b: (round(b[1], 2), round(b[0], 2)))
parts = [(b[4] or "").strip() for b in blocks if (b[4] or "").strip()]
return "\n\n".join(parts)
def normalize(s: str) -> str:
s = s.replace("\r\n", "\n").replace("\r", "\n")
s = re.sub(r"[“”]", '"', s)
s = re.sub(r"[‘’]", "'", s)
s = re.sub(r"(\w)-\n(\w)", r"\1\2", s) # de-hyphenate soft wraps
s = re.sub(r"\n{3,}", "\n\n", s) # collapse excess breaks
return s
def get_manifest_info(text: str) -> dict[str, str | None]:
try:
client = OpenAI(api_key=OPENAI_API_KEY)
prompt = (
f"""
You are an expert in legal research and analysis, specializing in technology transactions. Examine the attached technology transactions document, and then identify respective values for each of the following keys: the role(s) of the party or parties (use only the roles, e.g., licensor, licensee; do not include the names of the parties), the governing law (use standard legal abbreviations, e.g., US-CA, US-FED, US-DE, etc.), the industry (use 1-3 words, e.g., biotechnology, software, SaaS), and the effective date of the agreement. Consider the substantive meaning of words (e.g., "Page 1 of 12" is not likely to be the governing law), placement in the document, surrounding text, applicable section, and any other factors that might inform your decision. Format the date in a string "YYYY-MM-DD". If you are unable to identify a value for the governing law, use the jurisdiction, if available.
Return a response in following JSON format only:
{{
"party_roles": party_roles,
"governing_law": governing_law,
"industry": industry,
"effective_date": effective_date
}}.
Do not return anything else outside of the JSON object. If you cannot identify a value corresponding to one of the keys, respond with null for that key.
--- PAGE TEXT START ---\n
{text}\n
--- PAGE TEXT END ---
"""
)
response = client.responses.create(
model=CHAT_MODEL,
input=prompt,
text={"verbosity": "low"},
)
response = response.output_text if response else ""
logger.info(f"AI manifest raw response: {response}")
candidate = (response or [])
logger.info(f"AI manifest response: {candidate}")
expected_keys = [
"party_roles",
"governing_law",
"industry",
"effective_date",
]
data = {}
if isinstance(candidate, dict):
data = candidate
elif isinstance(candidate, str):
try:
data = json.loads(candidate)
except Exception:
logger.error("AI manifest response not valid JSON; returning defaults")
data = {}
else:
logger.error("AI manifest response unexpected type %s", type(candidate))
# Build normalized manifest dict
manifest = {k: (data.get(k) if isinstance(data, dict) else None) for k in expected_keys}
# Coerce obvious placeholder / unknown strings to None
for k, v in manifest.items():
if isinstance(v, str) and v.strip().lower() in {"unknown", "null", "n/a", "none", ""}:
manifest[k] = None
return manifest
except Exception as e:
logger.error(f"Error extracting title from text: {e}")
return {}
def extract_pdf_text(file: FileStorage):
file.stream.seek(0)
text_parts = []
logger.info("Extracting text from PDF")
with fitz.open(stream=file.stream.read(), filetype="pdf") as doc:
for page in doc:
text = page.get_text("text")
if text.strip():
text_parts.append(text)
else:
pix = page.get_pixmap()
img = Image.frombytes(mode="RGB", size=(pix.width, pix.height), data=pix.samples)
ocr_text = pytesseract.image_to_string(img)
text_parts.append(ocr_text)
text_parts.append("\n\n\f\n\n") # Page break
raw = "\n\n\f\n\n".join(text_parts).strip()
return normalize(raw)
def extract_docx_text(file: FileStorage):
file.stream.seek(0)
logger.info("Extracting text from DOCX")
doc = docx.Document(file.stream)
text = [p.text for p in doc.paragraphs]
raw = "\n".join(text)
return normalize(raw)
def extract_text(file: FileStorage) -> str:
filename = file.filename or ""
file.stream.seek(0)
_, ext = os.path.splitext(filename.lower())
if ext == ".txt":
return normalize(file.stream.read().decode('utf-8'))
if ext == ".pdf":
return extract_pdf_text(file)
elif ext == ".docx":
return extract_docx_text(file)
else:
raise ValueError("Unsupported file format")
def extract_title_type_jurisdiction(text: str) -> dict[str, str | None]:
try:
client = OpenAI(api_key=OPENAI_API_KEY)
prompt = (
f"""
You are an expert in legal research and analysis, specializing in technology transactions. Examine the attached legal document, which is a technology transactions document, and then identify the title, type of technology transactions document (e.g., IP agreement, NDA, license, MSA, etc.), and jurisdiction. Avoid using proper names of the parties in the title. Try to use the type of legal document as the title -- e.g., IP Agreement, Master Services Agreement, Terms of Service, etc. Use an accepted legal abbreviation for the jurisdiction (e.g., US-CA, US-FED, FRG, etc.). Where appropriate, use an accepted legal abbreviation for the doc_type -- e.g., "MSA" for Master Services Agreement, "EULA" for End User License Agreement, etc. If you are unable to identify the jurisdiction, use the governing law, if available. Consider the substantive meaning of words (e.g., "Page 1 of 12" is not likely to be the title), placement in the document, case of the letters, length, punctuation, justification, and any other factors that might inform your decision. If you cannot confidently identify a corresponding value for a field, respond with null for that field. Return only a JSON object, with no other characters outside the JSON object. The JSON object should have the following keys: title, doc_type, jurisdiction. For example:
{{"title": title, "doc_type": doc_type, "jurisdiction": jurisdiction}}.
--- PAGE TEXT START ---\n
{text}\n
--- PAGE TEXT END ---
"""
)
ai_model = CHAT_MODEL
response = client.chat.completions.create(
model=ai_model,
messages=[
{"role": "system", "content": "Extract the document's title, doc_type, and jurisdiction based on the following text.\n"},
{"role": "user", "content": prompt},
]
)
response_text = response.choices[0].message.content if response.choices else ""
candidate = (response_text or "").strip()
# Expected keys
keys = ["title", "doc_type", "jurisdiction"]
result: dict[str, str | None] = {k: None for k in keys}
if not candidate:
return result
parsed: dict[str, str | None] = {}
# Try direct JSON parse first
try:
parsed = json.loads(candidate)
except Exception:
# Attempt to salvage JSON substring if model added stray text
try:
import re as _re
match = _re.search(r"\{.*\}", candidate, _re.DOTALL)
if match:
parsed = json.loads(match.group(0))
else:
logger.error("AI title/doc_type/jurisdiction response not valid JSON: %s", candidate[:200])
except Exception:
logger.error("Failed to parse AI JSON for title/doc_type/jurisdiction")
if isinstance(parsed, dict):
for k in keys:
v = parsed.get(k)
if isinstance(v, str):
vs = v.strip()
if vs.lower() in {"", "null", "none", "unknown", "n/a"}:
result[k] = None
else:
result[k] = vs
elif v is None:
result[k] = None
else:
# Unexpected type -> stringify conservatively
try:
result[k] = str(v)
except Exception:
result[k] = None
return result
except Exception as e:
logger.error(f"Error extracting title from text: {e}")
return {"title": None, "doc_type": None, "jurisdiction": None}
def sha256_file(file: FileStorage) -> str:
file.stream.seek(0)
return sha256_bytes(file.stream.read())
def sha256_bytes(bytes: bytes) -> str:
return hashlib.sha256(bytes).hexdigest()
def sha256_text(text: str) -> str:
"""Compute the SHA-256 hash of a text string."""
return sha256_bytes(text.encode('utf-8'))
|