362 lines
9.2 KiB
Python
362 lines
9.2 KiB
Python
from pathlib import Path
|
|
import getpass
|
|
import json
|
|
import os
|
|
|
|
import pymupdf
|
|
import requests
|
|
|
|
API_URL = "https://project.nes.uni-due.de/llm2/v1/chat/completions"
|
|
MODEL = "gemma4-e4b"
|
|
|
|
SCRIPT_DIR = Path(__file__).resolve().parent
|
|
ROOT_DIR = SCRIPT_DIR
|
|
SYSTEM_PROMPT_PATH = SCRIPT_DIR / "prompt_template_ad_vllm.txt"
|
|
|
|
PAIR_IDS = [] # if empty -> all folders with AD.pdf
|
|
|
|
|
|
AD_SCHEMA = {
|
|
"type": "object",
|
|
"additionalProperties": False,
|
|
"properties": {
|
|
"company": {
|
|
"type": "object",
|
|
"additionalProperties": False,
|
|
"properties": {
|
|
"name": {"type": ["string", "null"]},
|
|
"legal_form": {"type": ["string", "null"]},
|
|
"register_court": {"type": ["string", "null"]},
|
|
"register_number": {"type": ["string", "null"]},
|
|
"city": {"type": ["string", "null"]},
|
|
"business_purpose": {"type": ["string", "null"]},
|
|
"active": {"type": "boolean"},
|
|
},
|
|
"required": [
|
|
"name",
|
|
"legal_form",
|
|
"register_court",
|
|
"register_number",
|
|
"city",
|
|
"business_purpose",
|
|
"active",
|
|
],
|
|
},
|
|
"roles": {
|
|
"type": "array",
|
|
"items": {
|
|
"type": "object",
|
|
"additionalProperties": False,
|
|
"properties": {
|
|
"name": {"type": ["string", "null"]},
|
|
"title": {"type": ["string", "null"]},
|
|
"birth_date": {"type": ["string", "null"]},
|
|
"city": {"type": ["string", "null"]},
|
|
"role": {"type": ["string", "null"]},
|
|
},
|
|
"required": [
|
|
"name",
|
|
"title",
|
|
"birth_date",
|
|
"city",
|
|
"role",
|
|
],
|
|
},
|
|
},
|
|
},
|
|
"required": [
|
|
"company",
|
|
"roles",
|
|
],
|
|
}
|
|
|
|
|
|
def get_pair_ids():
|
|
if PAIR_IDS:
|
|
return PAIR_IDS
|
|
|
|
pair_ids = []
|
|
|
|
for item in ROOT_DIR.iterdir():
|
|
if item.is_dir() and (item / "AD.pdf").exists():
|
|
pair_ids.append(item.name)
|
|
|
|
return sorted(pair_ids)
|
|
|
|
|
|
def pdf_to_text(pdf_path: Path) -> str:
|
|
doc = pymupdf.open(pdf_path)
|
|
pages = []
|
|
|
|
for page_index, page in enumerate(doc, start=1):
|
|
text = page.get_text("text")
|
|
|
|
pages.append(
|
|
f"\n\n{'=' * 40}\n"
|
|
f"PAGE {page_index} / PLAIN TEXT\n"
|
|
f"{'=' * 40}\n\n"
|
|
f"{text}"
|
|
)
|
|
|
|
doc.close()
|
|
|
|
return "\n".join(pages)
|
|
|
|
|
|
def get_api_key() -> str:
|
|
api_key = os.getenv("LLM_API_KEY")
|
|
|
|
if api_key:
|
|
return api_key
|
|
|
|
return getpass.getpass("API key: ")
|
|
|
|
|
|
def add_suffix(path: Path, suffix: str) -> Path:
|
|
if not suffix:
|
|
return path
|
|
|
|
return path.with_name(f"{path.stem}{suffix}{path.suffix}")
|
|
|
|
|
|
def get_run_suffix(paths: list[Path]) -> str:
|
|
if not any(path.exists() for path in paths):
|
|
return ""
|
|
|
|
version = 1
|
|
|
|
while True:
|
|
suffix = f"_v{version}"
|
|
|
|
if not any(add_suffix(path, suffix).exists() for path in paths):
|
|
return suffix
|
|
|
|
version += 1
|
|
|
|
|
|
def get_usage(data: dict) -> dict:
|
|
usage = data.get("usage", {})
|
|
|
|
prompt_tokens = usage.get("prompt_tokens", 0) or 0
|
|
completion_tokens = usage.get("completion_tokens", 0) or 0
|
|
total_tokens = usage.get("total_tokens", prompt_tokens + completion_tokens) or 0
|
|
|
|
return {
|
|
"prompt_tokens": prompt_tokens,
|
|
"completion_tokens": completion_tokens,
|
|
"total_tokens": total_tokens,
|
|
}
|
|
|
|
|
|
def make_payload(system_prompt: str, ad_text: str) -> dict:
|
|
return {
|
|
"model": MODEL,
|
|
"messages": [
|
|
{
|
|
"role": "system",
|
|
"content": system_prompt,
|
|
},
|
|
{
|
|
"role": "user",
|
|
"content": ad_text,
|
|
},
|
|
],
|
|
"temperature": 0,
|
|
"max_tokens": 4096,
|
|
"response_format": {
|
|
"type": "json_schema",
|
|
"json_schema": {
|
|
"name": "ad_result",
|
|
"strict": True,
|
|
"schema": AD_SCHEMA,
|
|
},
|
|
},
|
|
}
|
|
|
|
|
|
def call_api(payload: dict, api_key: str) -> dict:
|
|
response = requests.post(
|
|
API_URL,
|
|
headers={
|
|
"Content-Type": "application/json",
|
|
"Authorization": f"Bearer {api_key}",
|
|
},
|
|
json=payload,
|
|
timeout=300,
|
|
)
|
|
|
|
return response.json()
|
|
|
|
|
|
def write_json(path: Path, data: dict) -> None:
|
|
path.write_text(
|
|
json.dumps(data, ensure_ascii=False, indent=2),
|
|
encoding="utf-8",
|
|
)
|
|
|
|
|
|
def make_debug_data(
|
|
pair_id: str,
|
|
pair_dir: Path,
|
|
suffix: str,
|
|
output_json: Path,
|
|
system_prompt: str,
|
|
ad_text: str,
|
|
data: dict,
|
|
) -> dict:
|
|
choice = {}
|
|
|
|
if "choices" in data and data["choices"]:
|
|
choice = data["choices"][0]
|
|
|
|
message = choice.get("message", {})
|
|
|
|
return {
|
|
"pair_id": pair_id,
|
|
"status": "error" if "error" in data else "ok",
|
|
"suffix": suffix if suffix else None,
|
|
"model": MODEL,
|
|
"api_url": API_URL,
|
|
"files": {
|
|
"ad_pdf": str(pair_dir / "AD.pdf"),
|
|
"system_prompt": SYSTEM_PROMPT_PATH,
|
|
"output_json": str(output_json),
|
|
},
|
|
"settings": {
|
|
"temperature": 0,
|
|
"max_tokens": 4096,
|
|
"response_format": "json_schema",
|
|
"schema_name": "ad_result",
|
|
"strict_schema": True,
|
|
},
|
|
"input": {
|
|
"system_prompt": system_prompt,
|
|
"user_text": ad_text,
|
|
},
|
|
"usage": get_usage(data),
|
|
"response": {
|
|
"id": data.get("id"),
|
|
"created": data.get("created"),
|
|
"finish_reason": choice.get("finish_reason"),
|
|
"stop_reason": choice.get("stop_reason"),
|
|
"system_fingerprint": data.get("system_fingerprint"),
|
|
"content_preview": message.get("content", "")[:500],
|
|
},
|
|
"error": data.get("error"),
|
|
}
|
|
|
|
|
|
def process_pair(pair_id: str, system_prompt: str, api_key: str) -> dict:
|
|
pair_dir = ROOT_DIR / pair_id
|
|
ad_pdf = pair_dir / "AD.pdf"
|
|
|
|
output_json_base = pair_dir / "AD_llm_result_vllm.json"
|
|
debug_json_base = pair_dir / "AD_vllm_debug.json"
|
|
|
|
suffix = get_run_suffix(
|
|
[
|
|
output_json_base,
|
|
debug_json_base,
|
|
]
|
|
)
|
|
|
|
output_json = add_suffix(output_json_base, suffix)
|
|
debug_json = add_suffix(debug_json_base, suffix)
|
|
|
|
ad_text = pdf_to_text(ad_pdf)
|
|
payload = make_payload(system_prompt, ad_text)
|
|
data = call_api(payload, api_key)
|
|
|
|
debug_data = make_debug_data(
|
|
pair_id,
|
|
pair_dir,
|
|
suffix,
|
|
output_json,
|
|
system_prompt,
|
|
ad_text,
|
|
data,
|
|
)
|
|
|
|
if "error" in data:
|
|
write_json(debug_json, debug_data)
|
|
|
|
return {
|
|
"pair_id": pair_id,
|
|
"status": "error",
|
|
"suffix": suffix,
|
|
"usage": get_usage(data),
|
|
"debug_path": str(debug_json),
|
|
"error": data["error"],
|
|
}
|
|
|
|
answer = data["choices"][0]["message"]["content"].strip()
|
|
result = json.loads(answer)
|
|
|
|
write_json(output_json, result)
|
|
|
|
debug_data["result_keys"] = list(result.keys())
|
|
debug_data["roles_count"] = len(result.get("roles", []))
|
|
write_json(debug_json, debug_data)
|
|
|
|
return {
|
|
"pair_id": pair_id,
|
|
"status": "ok",
|
|
"suffix": suffix,
|
|
"usage": get_usage(data),
|
|
"output_path": str(output_json),
|
|
"debug_path": str(debug_json),
|
|
}
|
|
|
|
|
|
def main() -> None:
|
|
pair_ids = get_pair_ids()
|
|
api_key = get_api_key()
|
|
system_prompt = Path(SYSTEM_PROMPT_PATH).read_text(encoding="utf-8")
|
|
|
|
total_prompt_tokens = 0
|
|
total_completion_tokens = 0
|
|
results = []
|
|
|
|
for pair_id in pair_ids:
|
|
result = process_pair(pair_id, system_prompt, api_key)
|
|
usage = result["usage"]
|
|
|
|
total_prompt_tokens += usage["prompt_tokens"]
|
|
total_completion_tokens += usage["completion_tokens"]
|
|
|
|
results.append(result)
|
|
|
|
print("=" * 80)
|
|
print("TOTAL TOKEN USAGE")
|
|
print(f" prompt_tokens: {total_prompt_tokens}")
|
|
print(f" completion_tokens: {total_completion_tokens}")
|
|
print(f" total_tokens: {total_prompt_tokens + total_completion_tokens}")
|
|
print(f" processed_folders: {len(results)}")
|
|
|
|
print()
|
|
print("PROCESSED FOLDERS")
|
|
for index, result in enumerate(results, start=1):
|
|
usage = result["usage"]
|
|
pair_id = result["pair_id"]
|
|
status = result["status"]
|
|
suffix = result["suffix"] if result["suffix"] else "none"
|
|
|
|
print(
|
|
f" {index:02d}. {pair_id} | {status} | suffix: {suffix} | "
|
|
f"prompt: {usage['prompt_tokens']} | "
|
|
f"completion: {usage['completion_tokens']} | "
|
|
f"total: {usage['total_tokens']}"
|
|
)
|
|
|
|
errors = [result for result in results if result["status"] != "ok"]
|
|
|
|
if errors:
|
|
print()
|
|
print("ERRORS")
|
|
for result in errors:
|
|
print(f" {result['pair_id']}: {result['error']}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|