Spaces:
Running
Running
Upload 9 files
Browse files- src/aibom_generator/__init__.py +8 -0
- src/aibom_generator/api.py +157 -0
- src/aibom_generator/cli.py +193 -0
- src/aibom_generator/generator.py +388 -0
- src/aibom_generator/inference.py +359 -0
- src/aibom_generator/inference_model.py +532 -0
- src/aibom_generator/integration.py +134 -0
- src/aibom_generator/utils.py +222 -0
- src/aibom_generator/worker.py +103 -0
src/aibom_generator/__init__.py
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
AIBOM Generator for Hugging Face Models.
|
3 |
+
|
4 |
+
This package provides tools to generate AI Bills of Materials (AIBOMs) in CycloneDX format
|
5 |
+
for machine learning models hosted on the Hugging Face Hub.
|
6 |
+
"""
|
7 |
+
|
8 |
+
__version__ = "0.1.0"
|
src/aibom_generator/api.py
ADDED
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
FastAPI server for the AIBOM Generator.
|
3 |
+
"""
|
4 |
+
|
5 |
+
import logging
|
6 |
+
import os
|
7 |
+
from typing import Dict, List, Optional, Any, Union
|
8 |
+
|
9 |
+
from fastapi import FastAPI, HTTPException, BackgroundTasks
|
10 |
+
from fastapi.middleware.cors import CORSMiddleware
|
11 |
+
from pydantic import BaseModel
|
12 |
+
|
13 |
+
from aibom_generator.generator import AIBOMGenerator
|
14 |
+
from aibom_generator.utils import setup_logging, calculate_completeness_score
|
15 |
+
|
16 |
+
# Set up logging
|
17 |
+
setup_logging()
|
18 |
+
logger = logging.getLogger(__name__)
|
19 |
+
|
20 |
+
# Create FastAPI app
|
21 |
+
app = FastAPI(
|
22 |
+
title="AIBOM Generator API",
|
23 |
+
description="API for generating AI Bills of Materials (AIBOMs) in CycloneDX format for Hugging Face models.",
|
24 |
+
version="0.1.0",
|
25 |
+
)
|
26 |
+
|
27 |
+
# Add CORS middleware
|
28 |
+
app.add_middleware(
|
29 |
+
CORSMiddleware,
|
30 |
+
allow_origins=["*"],
|
31 |
+
allow_credentials=True,
|
32 |
+
allow_methods=["*"],
|
33 |
+
allow_headers=["*"],
|
34 |
+
)
|
35 |
+
|
36 |
+
# Create generator instance
|
37 |
+
generator = AIBOMGenerator(
|
38 |
+
hf_token=os.environ.get("HF_TOKEN"),
|
39 |
+
inference_model_url=os.environ.get("AIBOM_INFERENCE_URL"),
|
40 |
+
use_inference=os.environ.get("AIBOM_USE_INFERENCE", "true").lower() == "true",
|
41 |
+
cache_dir=os.environ.get("AIBOM_CACHE_DIR"),
|
42 |
+
)
|
43 |
+
|
44 |
+
|
45 |
+
# Define request and response models
|
46 |
+
class GenerateRequest(BaseModel):
|
47 |
+
model_id: str
|
48 |
+
include_inference: Optional[bool] = None
|
49 |
+
completeness_threshold: Optional[int] = 0
|
50 |
+
|
51 |
+
|
52 |
+
class GenerateResponse(BaseModel):
|
53 |
+
aibom: Dict[str, Any]
|
54 |
+
completeness_score: int
|
55 |
+
model_id: str
|
56 |
+
|
57 |
+
|
58 |
+
class StatusResponse(BaseModel):
|
59 |
+
status: str
|
60 |
+
version: str
|
61 |
+
|
62 |
+
|
63 |
+
# Define API endpoints
|
64 |
+
@app.get("/", response_model=StatusResponse)
|
65 |
+
async def root():
|
66 |
+
"""Get API status."""
|
67 |
+
return {
|
68 |
+
"status": "ok",
|
69 |
+
"version": "0.1.0",
|
70 |
+
}
|
71 |
+
|
72 |
+
|
73 |
+
@app.post("/generate", response_model=GenerateResponse)
|
74 |
+
async def generate_aibom(request: GenerateRequest):
|
75 |
+
"""Generate an AIBOM for a Hugging Face model."""
|
76 |
+
try:
|
77 |
+
# Generate the AIBOM
|
78 |
+
aibom = generator.generate_aibom(
|
79 |
+
model_id=request.model_id,
|
80 |
+
include_inference=request.include_inference,
|
81 |
+
)
|
82 |
+
|
83 |
+
# Calculate completeness score
|
84 |
+
completeness_score = calculate_completeness_score(aibom)
|
85 |
+
|
86 |
+
# Check if it meets the threshold
|
87 |
+
if completeness_score < request.completeness_threshold:
|
88 |
+
raise HTTPException(
|
89 |
+
status_code=400,
|
90 |
+
detail=f"AIBOM completeness score ({completeness_score}) is below threshold ({request.completeness_threshold})",
|
91 |
+
)
|
92 |
+
|
93 |
+
return {
|
94 |
+
"aibom": aibom,
|
95 |
+
"completeness_score": completeness_score,
|
96 |
+
"model_id": request.model_id,
|
97 |
+
}
|
98 |
+
except Exception as e:
|
99 |
+
logger.error(f"Error generating AIBOM: {e}")
|
100 |
+
raise HTTPException(
|
101 |
+
status_code=500,
|
102 |
+
detail=f"Error generating AIBOM: {str(e)}",
|
103 |
+
)
|
104 |
+
|
105 |
+
|
106 |
+
@app.post("/generate/async")
|
107 |
+
async def generate_aibom_async(
|
108 |
+
request: GenerateRequest,
|
109 |
+
background_tasks: BackgroundTasks,
|
110 |
+
):
|
111 |
+
"""Generate an AIBOM asynchronously for a Hugging Face model."""
|
112 |
+
# Add to background tasks
|
113 |
+
background_tasks.add_task(
|
114 |
+
_generate_aibom_background,
|
115 |
+
request.model_id,
|
116 |
+
request.include_inference,
|
117 |
+
request.completeness_threshold,
|
118 |
+
)
|
119 |
+
|
120 |
+
return {
|
121 |
+
"status": "accepted",
|
122 |
+
"message": f"AIBOM generation for {request.model_id} started in the background",
|
123 |
+
}
|
124 |
+
|
125 |
+
|
126 |
+
async def _generate_aibom_background(
|
127 |
+
model_id: str,
|
128 |
+
include_inference: Optional[bool] = None,
|
129 |
+
completeness_threshold: Optional[int] = 0,
|
130 |
+
):
|
131 |
+
"""Generate an AIBOM in the background."""
|
132 |
+
try:
|
133 |
+
# Generate the AIBOM
|
134 |
+
aibom = generator.generate_aibom(
|
135 |
+
model_id=model_id,
|
136 |
+
include_inference=include_inference,
|
137 |
+
)
|
138 |
+
|
139 |
+
# Calculate completeness score
|
140 |
+
completeness_score = calculate_completeness_score(aibom)
|
141 |
+
|
142 |
+
# TODO: Store the result or notify the user
|
143 |
+
logger.info(f"Background AIBOM generation completed for {model_id}")
|
144 |
+
logger.info(f"Completeness score: {completeness_score}")
|
145 |
+
except Exception as e:
|
146 |
+
logger.error(f"Error in background AIBOM generation for {model_id}: {e}")
|
147 |
+
|
148 |
+
|
149 |
+
@app.get("/health")
|
150 |
+
async def health():
|
151 |
+
"""Health check endpoint."""
|
152 |
+
return {"status": "healthy"}
|
153 |
+
|
154 |
+
|
155 |
+
if __name__ == "__main__":
|
156 |
+
import uvicorn
|
157 |
+
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 5000)))
|
src/aibom_generator/cli.py
ADDED
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
CLI interface for the AIBOM Generator.
|
3 |
+
"""
|
4 |
+
|
5 |
+
import argparse
|
6 |
+
import json
|
7 |
+
import os
|
8 |
+
import sys
|
9 |
+
from typing import Optional
|
10 |
+
|
11 |
+
from aibom_generator.generator import AIBOMGenerator
|
12 |
+
|
13 |
+
|
14 |
+
def parse_args():
|
15 |
+
"""Parse command line arguments."""
|
16 |
+
parser = argparse.ArgumentParser(
|
17 |
+
description="Generate AI Bills of Materials (AIBOMs) in CycloneDX format for Hugging Face models."
|
18 |
+
)
|
19 |
+
|
20 |
+
parser.add_argument(
|
21 |
+
"model_id",
|
22 |
+
help="Hugging Face model ID (e.g., 'google/bert-base-uncased')"
|
23 |
+
)
|
24 |
+
|
25 |
+
parser.add_argument(
|
26 |
+
"-o", "--output",
|
27 |
+
help="Output file path (default: <model_id>.aibom.json)",
|
28 |
+
default=None
|
29 |
+
)
|
30 |
+
|
31 |
+
parser.add_argument(
|
32 |
+
"--token",
|
33 |
+
help="Hugging Face API token for accessing private models",
|
34 |
+
default=os.environ.get("HF_TOKEN")
|
35 |
+
)
|
36 |
+
|
37 |
+
parser.add_argument(
|
38 |
+
"--inference-url",
|
39 |
+
help="URL of the inference model service for metadata extraction",
|
40 |
+
default=os.environ.get("AIBOM_INFERENCE_URL")
|
41 |
+
)
|
42 |
+
|
43 |
+
parser.add_argument(
|
44 |
+
"--no-inference",
|
45 |
+
help="Disable inference model for metadata extraction",
|
46 |
+
action="store_true"
|
47 |
+
)
|
48 |
+
|
49 |
+
parser.add_argument(
|
50 |
+
"--cache-dir",
|
51 |
+
help="Directory to cache API responses and model cards",
|
52 |
+
default=os.environ.get("AIBOM_CACHE_DIR", ".aibom_cache")
|
53 |
+
)
|
54 |
+
|
55 |
+
parser.add_argument(
|
56 |
+
"--completeness-threshold",
|
57 |
+
help="Minimum completeness score (0-100) required for the AIBOM",
|
58 |
+
type=int,
|
59 |
+
default=0
|
60 |
+
)
|
61 |
+
|
62 |
+
parser.add_argument(
|
63 |
+
"--format",
|
64 |
+
help="Output format (json or yaml)",
|
65 |
+
choices=["json", "yaml"],
|
66 |
+
default="json"
|
67 |
+
)
|
68 |
+
|
69 |
+
parser.add_argument(
|
70 |
+
"--pretty",
|
71 |
+
help="Pretty-print the output",
|
72 |
+
action="store_true"
|
73 |
+
)
|
74 |
+
|
75 |
+
return parser.parse_args()
|
76 |
+
|
77 |
+
|
78 |
+
def main():
|
79 |
+
"""Main entry point for the CLI."""
|
80 |
+
args = parse_args()
|
81 |
+
|
82 |
+
# Determine output file if not specified
|
83 |
+
if not args.output:
|
84 |
+
model_name = args.model_id.replace("/", "_")
|
85 |
+
args.output = f"{model_name}.aibom.json"
|
86 |
+
|
87 |
+
# Create the generator
|
88 |
+
generator = AIBOMGenerator(
|
89 |
+
hf_token=args.token,
|
90 |
+
inference_model_url=args.inference_url,
|
91 |
+
use_inference=not args.no_inference,
|
92 |
+
cache_dir=args.cache_dir
|
93 |
+
)
|
94 |
+
|
95 |
+
try:
|
96 |
+
# Generate the AIBOM
|
97 |
+
aibom = generator.generate_aibom(
|
98 |
+
model_id=args.model_id,
|
99 |
+
output_file=None # We'll handle saving ourselves
|
100 |
+
)
|
101 |
+
|
102 |
+
# Calculate completeness score (placeholder for now)
|
103 |
+
completeness_score = calculate_completeness_score(aibom)
|
104 |
+
|
105 |
+
# Check if it meets the threshold
|
106 |
+
if completeness_score < args.completeness_threshold:
|
107 |
+
print(f"Warning: AIBOM completeness score ({completeness_score}) is below threshold ({args.completeness_threshold})")
|
108 |
+
|
109 |
+
# Save the output
|
110 |
+
save_output(aibom, args.output, args.format, args.pretty)
|
111 |
+
|
112 |
+
print(f"AIBOM generated successfully: {args.output}")
|
113 |
+
print(f"Completeness score: {completeness_score}/100")
|
114 |
+
|
115 |
+
return 0
|
116 |
+
|
117 |
+
except Exception as e:
|
118 |
+
print(f"Error generating AIBOM: {e}", file=sys.stderr)
|
119 |
+
return 1
|
120 |
+
|
121 |
+
|
122 |
+
def calculate_completeness_score(aibom):
|
123 |
+
"""
|
124 |
+
Calculate a completeness score for the AIBOM.
|
125 |
+
|
126 |
+
This is a placeholder implementation that will be replaced with a more
|
127 |
+
sophisticated scoring algorithm based on the field mapping framework.
|
128 |
+
"""
|
129 |
+
# TODO: Implement proper completeness scoring
|
130 |
+
score = 0
|
131 |
+
|
132 |
+
# Check required fields
|
133 |
+
if all(field in aibom for field in ["bomFormat", "specVersion", "serialNumber", "version"]):
|
134 |
+
score += 20
|
135 |
+
|
136 |
+
# Check metadata
|
137 |
+
if "metadata" in aibom:
|
138 |
+
metadata = aibom["metadata"]
|
139 |
+
if "timestamp" in metadata:
|
140 |
+
score += 5
|
141 |
+
if "tools" in metadata and metadata["tools"]:
|
142 |
+
score += 5
|
143 |
+
if "authors" in metadata and metadata["authors"]:
|
144 |
+
score += 5
|
145 |
+
if "component" in metadata:
|
146 |
+
score += 5
|
147 |
+
|
148 |
+
# Check components
|
149 |
+
if "components" in aibom and aibom["components"]:
|
150 |
+
component = aibom["components"][0]
|
151 |
+
if "type" in component and component["type"] == "machine-learning-model":
|
152 |
+
score += 10
|
153 |
+
if "name" in component:
|
154 |
+
score += 5
|
155 |
+
if "bom-ref" in component:
|
156 |
+
score += 5
|
157 |
+
if "licenses" in component:
|
158 |
+
score += 5
|
159 |
+
if "externalReferences" in component:
|
160 |
+
score += 5
|
161 |
+
if "modelCard" in component:
|
162 |
+
model_card = component["modelCard"]
|
163 |
+
if "modelParameters" in model_card:
|
164 |
+
score += 10
|
165 |
+
if "quantitativeAnalysis" in model_card:
|
166 |
+
score += 10
|
167 |
+
if "considerations" in model_card:
|
168 |
+
score += 10
|
169 |
+
|
170 |
+
return score
|
171 |
+
|
172 |
+
|
173 |
+
def save_output(aibom, output_file, format_type, pretty):
|
174 |
+
"""Save the AIBOM to the specified output file."""
|
175 |
+
if format_type == "json":
|
176 |
+
with open(output_file, "w") as f:
|
177 |
+
if pretty:
|
178 |
+
json.dump(aibom, f, indent=2)
|
179 |
+
else:
|
180 |
+
json.dump(aibom, f)
|
181 |
+
else: # yaml
|
182 |
+
try:
|
183 |
+
import yaml
|
184 |
+
with open(output_file, "w") as f:
|
185 |
+
yaml.dump(aibom, f, default_flow_style=False)
|
186 |
+
except ImportError:
|
187 |
+
print("Warning: PyYAML not installed. Falling back to JSON format.")
|
188 |
+
with open(output_file, "w") as f:
|
189 |
+
json.dump(aibom, f, indent=2 if pretty else None)
|
190 |
+
|
191 |
+
|
192 |
+
if __name__ == "__main__":
|
193 |
+
sys.exit(main())
|
src/aibom_generator/generator.py
ADDED
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Core functionality for generating CycloneDX AIBOMs from Hugging Face models.
|
3 |
+
"""
|
4 |
+
|
5 |
+
import json
|
6 |
+
import uuid
|
7 |
+
import datetime
|
8 |
+
from typing import Dict, List, Optional, Union, Any
|
9 |
+
|
10 |
+
from huggingface_hub import HfApi, ModelCard, ModelCardData
|
11 |
+
|
12 |
+
|
13 |
+
class AIBOMGenerator:
|
14 |
+
"""
|
15 |
+
Generator for AI Bills of Materials (AIBOMs) in CycloneDX format.
|
16 |
+
|
17 |
+
This class provides functionality to generate CycloneDX 1.6 compliant
|
18 |
+
AIBOMs for machine learning models hosted on the Hugging Face Hub.
|
19 |
+
"""
|
20 |
+
|
21 |
+
def __init__(
|
22 |
+
self,
|
23 |
+
hf_token: Optional[str] = None,
|
24 |
+
inference_model_url: Optional[str] = None,
|
25 |
+
use_inference: bool = True,
|
26 |
+
cache_dir: Optional[str] = None,
|
27 |
+
):
|
28 |
+
"""
|
29 |
+
Initialize the AIBOM Generator.
|
30 |
+
|
31 |
+
Args:
|
32 |
+
hf_token: Hugging Face API token for accessing private models
|
33 |
+
inference_model_url: URL of the inference model service for extracting
|
34 |
+
metadata from unstructured text
|
35 |
+
use_inference: Whether to use the inference model for metadata extraction
|
36 |
+
cache_dir: Directory to cache API responses and model cards
|
37 |
+
"""
|
38 |
+
self.hf_api = HfApi(token=hf_token)
|
39 |
+
self.inference_model_url = inference_model_url
|
40 |
+
self.use_inference = use_inference
|
41 |
+
self.cache_dir = cache_dir
|
42 |
+
|
43 |
+
def generate_aibom(
|
44 |
+
self,
|
45 |
+
model_id: str,
|
46 |
+
output_file: Optional[str] = None,
|
47 |
+
include_inference: Optional[bool] = None,
|
48 |
+
) -> Dict[str, Any]:
|
49 |
+
"""
|
50 |
+
Generate a CycloneDX AIBOM for the specified Hugging Face model.
|
51 |
+
|
52 |
+
Args:
|
53 |
+
model_id: The Hugging Face model ID (e.g., "google/bert-base-uncased")
|
54 |
+
output_file: Optional path to save the generated AIBOM
|
55 |
+
include_inference: Override the default inference model usage setting
|
56 |
+
|
57 |
+
Returns:
|
58 |
+
The generated AIBOM as a dictionary
|
59 |
+
"""
|
60 |
+
# Determine whether to use inference
|
61 |
+
use_inference = include_inference if include_inference is not None else self.use_inference
|
62 |
+
|
63 |
+
# Fetch model information
|
64 |
+
model_info = self._fetch_model_info(model_id)
|
65 |
+
model_card = self._fetch_model_card(model_id)
|
66 |
+
|
67 |
+
# Generate the AIBOM
|
68 |
+
aibom = self._create_aibom_structure(model_id, model_info, model_card, use_inference)
|
69 |
+
|
70 |
+
# Save to file if requested
|
71 |
+
if output_file:
|
72 |
+
with open(output_file, 'w') as f:
|
73 |
+
json.dump(aibom, f, indent=2)
|
74 |
+
|
75 |
+
return aibom
|
76 |
+
|
77 |
+
def _fetch_model_info(self, model_id: str) -> Dict[str, Any]:
|
78 |
+
"""
|
79 |
+
Fetch model information from the Hugging Face API.
|
80 |
+
|
81 |
+
Args:
|
82 |
+
model_id: The Hugging Face model ID
|
83 |
+
|
84 |
+
Returns:
|
85 |
+
Model information as a dictionary
|
86 |
+
"""
|
87 |
+
# TODO: Implement caching
|
88 |
+
try:
|
89 |
+
model_info = self.hf_api.model_info(model_id)
|
90 |
+
return model_info
|
91 |
+
except Exception as e:
|
92 |
+
# Log the error and return empty dict
|
93 |
+
print(f"Error fetching model info for {model_id}: {e}")
|
94 |
+
return {}
|
95 |
+
|
96 |
+
def _fetch_model_card(self, model_id: str) -> Optional[ModelCard]:
|
97 |
+
"""
|
98 |
+
Fetch the model card for the specified model.
|
99 |
+
|
100 |
+
Args:
|
101 |
+
model_id: The Hugging Face model ID
|
102 |
+
|
103 |
+
Returns:
|
104 |
+
ModelCard object if available, None otherwise
|
105 |
+
"""
|
106 |
+
# TODO: Implement caching
|
107 |
+
try:
|
108 |
+
model_card = ModelCard.load(model_id)
|
109 |
+
return model_card
|
110 |
+
except Exception as e:
|
111 |
+
# Log the error and return None
|
112 |
+
print(f"Error fetching model card for {model_id}: {e}")
|
113 |
+
return None
|
114 |
+
|
115 |
+
def _create_aibom_structure(
|
116 |
+
self,
|
117 |
+
model_id: str,
|
118 |
+
model_info: Dict[str, Any],
|
119 |
+
model_card: Optional[ModelCard],
|
120 |
+
use_inference: bool,
|
121 |
+
) -> Dict[str, Any]:
|
122 |
+
"""
|
123 |
+
Create the CycloneDX AIBOM structure.
|
124 |
+
|
125 |
+
Args:
|
126 |
+
model_id: The Hugging Face model ID
|
127 |
+
model_info: Model information from the API
|
128 |
+
model_card: ModelCard object if available
|
129 |
+
use_inference: Whether to use inference for metadata extraction
|
130 |
+
|
131 |
+
Returns:
|
132 |
+
CycloneDX AIBOM as a dictionary
|
133 |
+
"""
|
134 |
+
# Extract structured metadata
|
135 |
+
metadata = self._extract_structured_metadata(model_id, model_info, model_card)
|
136 |
+
|
137 |
+
# Extract unstructured metadata if requested and available
|
138 |
+
if use_inference and model_card and self.inference_model_url:
|
139 |
+
unstructured_metadata = self._extract_unstructured_metadata(model_card)
|
140 |
+
# Merge with structured metadata, giving priority to structured
|
141 |
+
metadata = {**unstructured_metadata, **metadata}
|
142 |
+
|
143 |
+
# Create the AIBOM structure
|
144 |
+
aibom = {
|
145 |
+
"bomFormat": "CycloneDX",
|
146 |
+
"specVersion": "1.6",
|
147 |
+
"serialNumber": f"urn:uuid:{str(uuid.uuid4())}",
|
148 |
+
"version": 1,
|
149 |
+
"metadata": self._create_metadata_section(model_id, metadata),
|
150 |
+
"components": [self._create_component_section(model_id, metadata)],
|
151 |
+
}
|
152 |
+
|
153 |
+
# Add external references if available
|
154 |
+
if "external_references" in metadata:
|
155 |
+
aibom["externalReferences"] = metadata["external_references"]
|
156 |
+
|
157 |
+
return aibom
|
158 |
+
|
159 |
+
def _extract_structured_metadata(
|
160 |
+
self,
|
161 |
+
model_id: str,
|
162 |
+
model_info: Dict[str, Any],
|
163 |
+
model_card: Optional[ModelCard],
|
164 |
+
) -> Dict[str, Any]:
|
165 |
+
"""
|
166 |
+
Extract structured metadata from model info and model card.
|
167 |
+
|
168 |
+
Args:
|
169 |
+
model_id: The Hugging Face model ID
|
170 |
+
model_info: Model information from the API
|
171 |
+
model_card: ModelCard object if available
|
172 |
+
|
173 |
+
Returns:
|
174 |
+
Structured metadata as a dictionary
|
175 |
+
"""
|
176 |
+
metadata = {}
|
177 |
+
|
178 |
+
# Extract from model_info
|
179 |
+
if model_info:
|
180 |
+
metadata.update({
|
181 |
+
"name": model_info.modelId.split("/")[-1] if hasattr(model_info, "modelId") else model_id.split("/")[-1],
|
182 |
+
"author": model_info.author if hasattr(model_info, "author") else None,
|
183 |
+
"tags": model_info.tags if hasattr(model_info, "tags") else [],
|
184 |
+
"pipeline_tag": model_info.pipeline_tag if hasattr(model_info, "pipeline_tag") else None,
|
185 |
+
"downloads": model_info.downloads if hasattr(model_info, "downloads") else 0,
|
186 |
+
"last_modified": model_info.lastModified if hasattr(model_info, "lastModified") else None,
|
187 |
+
})
|
188 |
+
|
189 |
+
# Extract from model_card
|
190 |
+
if model_card and model_card.data:
|
191 |
+
card_data = model_card.data.to_dict() if hasattr(model_card.data, "to_dict") else {}
|
192 |
+
|
193 |
+
# Map card data to metadata
|
194 |
+
metadata.update({
|
195 |
+
"language": card_data.get("language"),
|
196 |
+
"license": card_data.get("license"),
|
197 |
+
"library_name": card_data.get("library_name"),
|
198 |
+
"base_model": card_data.get("base_model"),
|
199 |
+
"datasets": card_data.get("datasets"),
|
200 |
+
"model_name": card_data.get("model_name"),
|
201 |
+
"tags": card_data.get("tags", metadata.get("tags", [])),
|
202 |
+
})
|
203 |
+
|
204 |
+
# Extract evaluation results if available
|
205 |
+
if hasattr(model_card.data, "eval_results") and model_card.data.eval_results:
|
206 |
+
metadata["eval_results"] = model_card.data.eval_results
|
207 |
+
|
208 |
+
return {k: v for k, v in metadata.items() if v is not None}
|
209 |
+
|
210 |
+
def _extract_unstructured_metadata(self, model_card: ModelCard) -> Dict[str, Any]:
|
211 |
+
"""
|
212 |
+
Extract metadata from unstructured text using the inference model.
|
213 |
+
|
214 |
+
Args:
|
215 |
+
model_card: ModelCard object
|
216 |
+
|
217 |
+
Returns:
|
218 |
+
Extracted metadata as a dictionary
|
219 |
+
"""
|
220 |
+
# TODO: Implement inference model integration
|
221 |
+
# This is a placeholder that will be replaced with actual inference model calls
|
222 |
+
return {}
|
223 |
+
|
224 |
+
def _create_metadata_section(self, model_id: str, metadata: Dict[str, Any]) -> Dict[str, Any]:
|
225 |
+
"""
|
226 |
+
Create the metadata section of the CycloneDX AIBOM.
|
227 |
+
|
228 |
+
Args:
|
229 |
+
model_id: The Hugging Face model ID
|
230 |
+
metadata: Extracted metadata
|
231 |
+
|
232 |
+
Returns:
|
233 |
+
Metadata section as a dictionary
|
234 |
+
"""
|
235 |
+
# Create timestamp
|
236 |
+
timestamp = datetime.datetime.utcnow().isoformat() + "Z"
|
237 |
+
|
238 |
+
# Create tools section
|
239 |
+
tools = [{
|
240 |
+
"vendor": "AIBOM Generator",
|
241 |
+
"name": "aibom-generator",
|
242 |
+
"version": __import__("aibom_generator").__version__,
|
243 |
+
}]
|
244 |
+
|
245 |
+
# Create authors section
|
246 |
+
authors = []
|
247 |
+
if "author" in metadata and metadata["author"]:
|
248 |
+
authors.append({
|
249 |
+
"name": metadata["author"],
|
250 |
+
"url": f"https://huggingface.co/{metadata['author']}"
|
251 |
+
})
|
252 |
+
|
253 |
+
# Create component section (reference to the main component)
|
254 |
+
component = {
|
255 |
+
"type": "machine-learning-model",
|
256 |
+
"name": metadata.get("name", model_id.split("/")[-1]),
|
257 |
+
"bom-ref": f"pkg:huggingface/{model_id}",
|
258 |
+
}
|
259 |
+
|
260 |
+
# Create properties section
|
261 |
+
properties = []
|
262 |
+
for key, value in metadata.items():
|
263 |
+
if key not in ["name", "author", "license"] and value is not None:
|
264 |
+
if isinstance(value, (list, dict)):
|
265 |
+
value = json.dumps(value)
|
266 |
+
properties.append({
|
267 |
+
"name": key,
|
268 |
+
"value": str(value)
|
269 |
+
})
|
270 |
+
|
271 |
+
# Assemble metadata section
|
272 |
+
metadata_section = {
|
273 |
+
"timestamp": timestamp,
|
274 |
+
"tools": tools,
|
275 |
+
}
|
276 |
+
|
277 |
+
if authors:
|
278 |
+
metadata_section["authors"] = authors
|
279 |
+
|
280 |
+
if component:
|
281 |
+
metadata_section["component"] = component
|
282 |
+
|
283 |
+
if properties:
|
284 |
+
metadata_section["properties"] = properties
|
285 |
+
|
286 |
+
return metadata_section
|
287 |
+
|
288 |
+
def _create_component_section(self, model_id: str, metadata: Dict[str, Any]) -> Dict[str, Any]:
|
289 |
+
"""
|
290 |
+
Create the component section of the CycloneDX AIBOM.
|
291 |
+
|
292 |
+
Args:
|
293 |
+
model_id: The Hugging Face model ID
|
294 |
+
metadata: Extracted metadata
|
295 |
+
|
296 |
+
Returns:
|
297 |
+
Component section as a dictionary
|
298 |
+
"""
|
299 |
+
# Create basic component information
|
300 |
+
component = {
|
301 |
+
"type": "machine-learning-model",
|
302 |
+
"bom-ref": f"pkg:huggingface/{model_id}",
|
303 |
+
"name": metadata.get("name", model_id.split("/")[-1]),
|
304 |
+
"purl": f"pkg:huggingface/{model_id}",
|
305 |
+
}
|
306 |
+
|
307 |
+
# Add description if available
|
308 |
+
if "description" in metadata:
|
309 |
+
component["description"] = metadata["description"]
|
310 |
+
|
311 |
+
# Add version if available
|
312 |
+
if "version" in metadata:
|
313 |
+
component["version"] = metadata["version"]
|
314 |
+
|
315 |
+
# Add license if available
|
316 |
+
if "license" in metadata:
|
317 |
+
component["licenses"] = [{
|
318 |
+
"license": {
|
319 |
+
"id": metadata["license"]
|
320 |
+
}
|
321 |
+
}]
|
322 |
+
|
323 |
+
# Add external references
|
324 |
+
component["externalReferences"] = [
|
325 |
+
{
|
326 |
+
"type": "website",
|
327 |
+
"url": f"https://huggingface.co/{model_id}"
|
328 |
+
}
|
329 |
+
]
|
330 |
+
|
331 |
+
# Add model card section
|
332 |
+
component["modelCard"] = self._create_model_card_section(metadata)
|
333 |
+
|
334 |
+
return component
|
335 |
+
|
336 |
+
def _create_model_card_section(self, metadata: Dict[str, Any]) -> Dict[str, Any]:
|
337 |
+
"""
|
338 |
+
Create the modelCard section of the component.
|
339 |
+
|
340 |
+
Args:
|
341 |
+
metadata: Extracted metadata
|
342 |
+
|
343 |
+
Returns:
|
344 |
+
ModelCard section as a dictionary
|
345 |
+
"""
|
346 |
+
model_card_section = {}
|
347 |
+
|
348 |
+
# Add model parameters if available
|
349 |
+
model_parameters = {}
|
350 |
+
for param in ["base_model", "library_name", "pipeline_tag"]:
|
351 |
+
if param in metadata and metadata[param]:
|
352 |
+
model_parameters[param] = metadata[param]
|
353 |
+
|
354 |
+
if model_parameters:
|
355 |
+
model_card_section["modelParameters"] = model_parameters
|
356 |
+
|
357 |
+
# Add quantitative analysis if available
|
358 |
+
if "eval_results" in metadata:
|
359 |
+
model_card_section["quantitativeAnalysis"] = {
|
360 |
+
"performanceMetrics": metadata["eval_results"]
|
361 |
+
}
|
362 |
+
|
363 |
+
# Add considerations if available
|
364 |
+
considerations = {}
|
365 |
+
for consideration in ["limitations", "ethical_considerations", "bias", "risks"]:
|
366 |
+
if consideration in metadata and metadata[consideration]:
|
367 |
+
considerations[consideration] = metadata[consideration]
|
368 |
+
|
369 |
+
if considerations:
|
370 |
+
model_card_section["considerations"] = considerations
|
371 |
+
|
372 |
+
# Add properties if available
|
373 |
+
properties = []
|
374 |
+
for key, value in metadata.items():
|
375 |
+
if key not in ["name", "author", "license", "base_model", "library_name",
|
376 |
+
"pipeline_tag", "eval_results", "limitations",
|
377 |
+
"ethical_considerations", "bias", "risks"] and value is not None:
|
378 |
+
if isinstance(value, (list, dict)):
|
379 |
+
value = json.dumps(value)
|
380 |
+
properties.append({
|
381 |
+
"name": key,
|
382 |
+
"value": str(value)
|
383 |
+
})
|
384 |
+
|
385 |
+
if properties:
|
386 |
+
model_card_section["properties"] = properties
|
387 |
+
|
388 |
+
return model_card_section
|
src/aibom_generator/inference.py
ADDED
@@ -0,0 +1,359 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Inference model integration for extracting metadata from unstructured text.
|
3 |
+
"""
|
4 |
+
|
5 |
+
import json
|
6 |
+
import logging
|
7 |
+
import re
|
8 |
+
import requests
|
9 |
+
from typing import Dict, List, Optional, Any, Union
|
10 |
+
|
11 |
+
logger = logging.getLogger(__name__)
|
12 |
+
|
13 |
+
|
14 |
+
class InferenceModelClient:
|
15 |
+
"""
|
16 |
+
Client for interacting with the inference model service to extract
|
17 |
+
metadata from unstructured text in model cards.
|
18 |
+
"""
|
19 |
+
|
20 |
+
def __init__(
|
21 |
+
self,
|
22 |
+
inference_url: str,
|
23 |
+
timeout: int = 30,
|
24 |
+
max_retries: int = 3,
|
25 |
+
):
|
26 |
+
"""
|
27 |
+
Initialize the inference model client.
|
28 |
+
|
29 |
+
Args:
|
30 |
+
inference_url: URL of the inference model service
|
31 |
+
timeout: Request timeout in seconds
|
32 |
+
max_retries: Maximum number of retries for failed requests
|
33 |
+
"""
|
34 |
+
self.inference_url = inference_url
|
35 |
+
self.timeout = timeout
|
36 |
+
self.max_retries = max_retries
|
37 |
+
|
38 |
+
def extract_metadata(
|
39 |
+
self,
|
40 |
+
model_card_text: str,
|
41 |
+
structured_metadata: Optional[Dict[str, Any]] = None,
|
42 |
+
fields: Optional[List[str]] = None,
|
43 |
+
) -> Dict[str, Any]:
|
44 |
+
"""
|
45 |
+
Extract metadata from unstructured text using the inference model.
|
46 |
+
|
47 |
+
Args:
|
48 |
+
model_card_text: The text content of the model card
|
49 |
+
structured_metadata: Optional structured metadata to provide context
|
50 |
+
fields: Optional list of specific fields to extract
|
51 |
+
|
52 |
+
Returns:
|
53 |
+
Extracted metadata as a dictionary
|
54 |
+
"""
|
55 |
+
if not self.inference_url:
|
56 |
+
logger.warning("No inference model URL provided, skipping extraction")
|
57 |
+
return {}
|
58 |
+
|
59 |
+
# Prepare the request payload
|
60 |
+
payload = {
|
61 |
+
"text": model_card_text,
|
62 |
+
"structured_metadata": structured_metadata or {},
|
63 |
+
"fields": fields or [],
|
64 |
+
}
|
65 |
+
|
66 |
+
# Make the request to the inference model
|
67 |
+
try:
|
68 |
+
response = self._make_request(payload)
|
69 |
+
return response.get("metadata", {})
|
70 |
+
except Exception as e:
|
71 |
+
logger.error(f"Error extracting metadata with inference model: {e}")
|
72 |
+
return {}
|
73 |
+
|
74 |
+
def _make_request(self, payload: Dict[str, Any]) -> Dict[str, Any]:
|
75 |
+
"""
|
76 |
+
Make a request to the inference model service.
|
77 |
+
|
78 |
+
Args:
|
79 |
+
payload: Request payload
|
80 |
+
|
81 |
+
Returns:
|
82 |
+
Response from the inference model
|
83 |
+
|
84 |
+
Raises:
|
85 |
+
Exception: If the request fails after max_retries
|
86 |
+
"""
|
87 |
+
headers = {"Content-Type": "application/json"}
|
88 |
+
|
89 |
+
for attempt in range(self.max_retries):
|
90 |
+
try:
|
91 |
+
response = requests.post(
|
92 |
+
self.inference_url,
|
93 |
+
headers=headers,
|
94 |
+
json=payload,
|
95 |
+
timeout=self.timeout,
|
96 |
+
)
|
97 |
+
response.raise_for_status()
|
98 |
+
return response.json()
|
99 |
+
except requests.exceptions.RequestException as e:
|
100 |
+
logger.warning(f"Request failed (attempt {attempt+1}/{self.max_retries}): {e}")
|
101 |
+
if attempt == self.max_retries - 1:
|
102 |
+
raise
|
103 |
+
|
104 |
+
# This should never be reached due to the raise in the loop
|
105 |
+
raise Exception("Failed to make request to inference model")
|
106 |
+
|
107 |
+
|
108 |
+
class FallbackExtractor:
|
109 |
+
"""
|
110 |
+
Fallback extractor for extracting metadata using regex and heuristics
|
111 |
+
when the inference model is not available or fails.
|
112 |
+
"""
|
113 |
+
|
114 |
+
def extract_metadata(
|
115 |
+
self,
|
116 |
+
model_card_text: str,
|
117 |
+
structured_metadata: Optional[Dict[str, Any]] = None,
|
118 |
+
fields: Optional[List[str]] = None,
|
119 |
+
) -> Dict[str, Any]:
|
120 |
+
"""
|
121 |
+
Extract metadata using regex and heuristics.
|
122 |
+
|
123 |
+
Args:
|
124 |
+
model_card_text: The text content of the model card
|
125 |
+
structured_metadata: Optional structured metadata to provide context
|
126 |
+
fields: Optional list of specific fields to extract
|
127 |
+
|
128 |
+
Returns:
|
129 |
+
Extracted metadata as a dictionary
|
130 |
+
"""
|
131 |
+
metadata = {}
|
132 |
+
|
133 |
+
# Extract model parameters
|
134 |
+
metadata.update(self._extract_model_parameters(model_card_text))
|
135 |
+
|
136 |
+
# Extract limitations and ethical considerations
|
137 |
+
metadata.update(self._extract_considerations(model_card_text))
|
138 |
+
|
139 |
+
# Extract datasets
|
140 |
+
metadata.update(self._extract_datasets(model_card_text))
|
141 |
+
|
142 |
+
# Extract evaluation results
|
143 |
+
metadata.update(self._extract_evaluation_results(model_card_text))
|
144 |
+
|
145 |
+
return metadata
|
146 |
+
|
147 |
+
def _extract_model_parameters(self, text: str) -> Dict[str, Any]:
|
148 |
+
"""Extract model parameters from text."""
|
149 |
+
params = {}
|
150 |
+
|
151 |
+
# Extract model type/architecture
|
152 |
+
architecture_patterns = [
|
153 |
+
r"(?:model|architecture)(?:\s+type)?(?:\s*:\s*|\s+is\s+)([A-Za-z0-9\-]+)",
|
154 |
+
r"based\s+on\s+(?:the\s+)?([A-Za-z0-9\-]+)(?:\s+architecture)?",
|
155 |
+
]
|
156 |
+
|
157 |
+
for pattern in architecture_patterns:
|
158 |
+
match = re.search(pattern, text, re.IGNORECASE)
|
159 |
+
if match:
|
160 |
+
params["architecture"] = match.group(1).strip()
|
161 |
+
break
|
162 |
+
|
163 |
+
# Extract number of parameters
|
164 |
+
param_patterns = [
|
165 |
+
r"(\d+(?:\.\d+)?)\s*(?:B|M|K)?\s*(?:billion|million|thousand)?\s*parameters",
|
166 |
+
r"parameters\s*:\s*(\d+(?:\.\d+)?)\s*(?:B|M|K)?",
|
167 |
+
]
|
168 |
+
|
169 |
+
for pattern in param_patterns:
|
170 |
+
match = re.search(pattern, text, re.IGNORECASE)
|
171 |
+
if match:
|
172 |
+
params["parameters"] = match.group(1).strip()
|
173 |
+
# TODO: Normalize to a standard unit
|
174 |
+
break
|
175 |
+
|
176 |
+
return {"model_parameters": params} if params else {}
|
177 |
+
|
178 |
+
def _extract_considerations(self, text: str) -> Dict[str, Any]:
|
179 |
+
"""Extract limitations and ethical considerations from text."""
|
180 |
+
considerations = {}
|
181 |
+
|
182 |
+
# Extract limitations
|
183 |
+
limitations_section = self._extract_section(text, ["limitations", "limits", "shortcomings"])
|
184 |
+
if limitations_section:
|
185 |
+
considerations["limitations"] = limitations_section
|
186 |
+
|
187 |
+
# Extract ethical considerations
|
188 |
+
ethics_section = self._extract_section(
|
189 |
+
text, ["ethical considerations", "ethics", "bias", "fairness", "risks"]
|
190 |
+
)
|
191 |
+
if ethics_section:
|
192 |
+
considerations["ethical_considerations"] = ethics_section
|
193 |
+
|
194 |
+
return {"considerations": considerations} if considerations else {}
|
195 |
+
|
196 |
+
def _extract_datasets(self, text: str) -> Dict[str, Any]:
|
197 |
+
"""Extract dataset information from text."""
|
198 |
+
datasets = []
|
199 |
+
|
200 |
+
# Extract dataset mentions
|
201 |
+
dataset_patterns = [
|
202 |
+
r"trained\s+on\s+(?:the\s+)?([A-Za-z0-9\-\s]+)(?:\s+dataset)?",
|
203 |
+
r"dataset(?:\s*:\s*|\s+is\s+)([A-Za-z0-9\-\s]+)",
|
204 |
+
r"using\s+(?:the\s+)?([A-Za-z0-9\-\s]+)(?:\s+dataset)",
|
205 |
+
]
|
206 |
+
|
207 |
+
for pattern in dataset_patterns:
|
208 |
+
for match in re.finditer(pattern, text, re.IGNORECASE):
|
209 |
+
dataset = match.group(1).strip()
|
210 |
+
if dataset and dataset.lower() not in ["this", "these", "those"]:
|
211 |
+
datasets.append(dataset)
|
212 |
+
|
213 |
+
return {"datasets": list(set(datasets))} if datasets else {}
|
214 |
+
|
215 |
+
def _extract_evaluation_results(self, text: str) -> Dict[str, Any]:
|
216 |
+
"""Extract evaluation results from text."""
|
217 |
+
results = {}
|
218 |
+
|
219 |
+
# Extract accuracy
|
220 |
+
accuracy_match = re.search(
|
221 |
+
r"accuracy(?:\s*:\s*|\s+of\s+|\s+is\s+)(\d+(?:\.\d+)?)\s*%?",
|
222 |
+
text,
|
223 |
+
re.IGNORECASE,
|
224 |
+
)
|
225 |
+
if accuracy_match:
|
226 |
+
results["accuracy"] = float(accuracy_match.group(1))
|
227 |
+
|
228 |
+
# Extract F1 score
|
229 |
+
f1_match = re.search(
|
230 |
+
r"f1(?:\s*[\-_]?score)?(?:\s*:\s*|\s+of\s+|\s+is\s+)(\d+(?:\.\d+)?)",
|
231 |
+
text,
|
232 |
+
re.IGNORECASE,
|
233 |
+
)
|
234 |
+
if f1_match:
|
235 |
+
results["f1"] = float(f1_match.group(1))
|
236 |
+
|
237 |
+
# Extract precision
|
238 |
+
precision_match = re.search(
|
239 |
+
r"precision(?:\s*:\s*|\s+of\s+|\s+is\s+)(\d+(?:\.\d+)?)",
|
240 |
+
text,
|
241 |
+
re.IGNORECASE,
|
242 |
+
)
|
243 |
+
if precision_match:
|
244 |
+
results["precision"] = float(precision_match.group(1))
|
245 |
+
|
246 |
+
# Extract recall
|
247 |
+
recall_match = re.search(
|
248 |
+
r"recall(?:\s*:\s*|\s+of\s+|\s+is\s+)(\d+(?:\.\d+)?)",
|
249 |
+
text,
|
250 |
+
re.IGNORECASE,
|
251 |
+
)
|
252 |
+
if recall_match:
|
253 |
+
results["recall"] = float(recall_match.group(1))
|
254 |
+
|
255 |
+
return {"evaluation_results": results} if results else {}
|
256 |
+
|
257 |
+
def _extract_section(self, text: str, section_names: List[str]) -> Optional[str]:
|
258 |
+
"""
|
259 |
+
Extract a section from the text based on section names.
|
260 |
+
|
261 |
+
Args:
|
262 |
+
text: The text to extract from
|
263 |
+
section_names: Possible names for the section
|
264 |
+
|
265 |
+
Returns:
|
266 |
+
The extracted section text, or None if not found
|
267 |
+
"""
|
268 |
+
# Create pattern to match section headers
|
269 |
+
header_pattern = r"(?:^|\n)(?:#+\s*|[0-9]+\.\s*|[A-Z\s]+:\s*)(?:{})(?:\s*:)?(?:\s*\n|\s*$)".format(
|
270 |
+
"|".join(section_names)
|
271 |
+
)
|
272 |
+
|
273 |
+
# Find all section headers
|
274 |
+
headers = list(re.finditer(header_pattern, text, re.IGNORECASE))
|
275 |
+
|
276 |
+
for i, match in enumerate(headers):
|
277 |
+
start = match.end()
|
278 |
+
|
279 |
+
# Find the end of the section (next header or end of text)
|
280 |
+
if i < len(headers) - 1:
|
281 |
+
end = headers[i + 1].start()
|
282 |
+
else:
|
283 |
+
end = len(text)
|
284 |
+
|
285 |
+
# Extract the section content
|
286 |
+
section = text[start:end].strip()
|
287 |
+
|
288 |
+
if section:
|
289 |
+
return section
|
290 |
+
|
291 |
+
return None
|
292 |
+
|
293 |
+
|
294 |
+
class MetadataExtractor:
|
295 |
+
"""
|
296 |
+
Metadata extractor that combines inference model and fallback extraction.
|
297 |
+
"""
|
298 |
+
|
299 |
+
def __init__(
|
300 |
+
self,
|
301 |
+
inference_url: Optional[str] = None,
|
302 |
+
use_inference: bool = True,
|
303 |
+
):
|
304 |
+
"""
|
305 |
+
Initialize the metadata extractor.
|
306 |
+
|
307 |
+
Args:
|
308 |
+
inference_url: URL of the inference model service
|
309 |
+
use_inference: Whether to use the inference model
|
310 |
+
"""
|
311 |
+
self.use_inference = use_inference and inference_url is not None
|
312 |
+
self.inference_client = InferenceModelClient(inference_url) if self.use_inference else None
|
313 |
+
self.fallback_extractor = FallbackExtractor()
|
314 |
+
|
315 |
+
def extract_metadata(
|
316 |
+
self,
|
317 |
+
model_card_text: str,
|
318 |
+
structured_metadata: Optional[Dict[str, Any]] = None,
|
319 |
+
fields: Optional[List[str]] = None,
|
320 |
+
) -> Dict[str, Any]:
|
321 |
+
"""
|
322 |
+
Extract metadata from model card text.
|
323 |
+
|
324 |
+
Args:
|
325 |
+
model_card_text: The text content of the model card
|
326 |
+
structured_metadata: Optional structured metadata to provide context
|
327 |
+
fields: Optional list of specific fields to extract
|
328 |
+
|
329 |
+
Returns:
|
330 |
+
Extracted metadata as a dictionary
|
331 |
+
"""
|
332 |
+
metadata = {}
|
333 |
+
|
334 |
+
# Try inference model first if enabled
|
335 |
+
if self.use_inference and self.inference_client:
|
336 |
+
try:
|
337 |
+
inference_metadata = self.inference_client.extract_metadata(
|
338 |
+
model_card_text, structured_metadata, fields
|
339 |
+
)
|
340 |
+
metadata.update(inference_metadata)
|
341 |
+
except Exception as e:
|
342 |
+
logger.error(f"Inference model extraction failed: {e}")
|
343 |
+
|
344 |
+
# Use fallback extractor for missing fields or if inference failed
|
345 |
+
if not metadata or (fields and not all(field in metadata for field in fields)):
|
346 |
+
missing_fields = fields if fields else None
|
347 |
+
if fields:
|
348 |
+
missing_fields = [field for field in fields if field not in metadata]
|
349 |
+
|
350 |
+
fallback_metadata = self.fallback_extractor.extract_metadata(
|
351 |
+
model_card_text, structured_metadata, missing_fields
|
352 |
+
)
|
353 |
+
|
354 |
+
# Only update with fallback data for fields that weren't extracted by inference
|
355 |
+
for key, value in fallback_metadata.items():
|
356 |
+
if key not in metadata or not metadata[key]:
|
357 |
+
metadata[key] = value
|
358 |
+
|
359 |
+
return metadata
|
src/aibom_generator/inference_model.py
ADDED
@@ -0,0 +1,532 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Inference model implementation for metadata extraction from model cards.
|
3 |
+
|
4 |
+
This module provides a fine-tuned model for extracting structured metadata
|
5 |
+
from unstructured text in Hugging Face model cards.
|
6 |
+
"""
|
7 |
+
|
8 |
+
import json
|
9 |
+
import logging
|
10 |
+
import os
|
11 |
+
import re
|
12 |
+
import torch
|
13 |
+
from typing import Dict, List, Optional, Any, Union
|
14 |
+
|
15 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
16 |
+
from transformers import AutoModelForSeq2SeqLM, T5Tokenizer
|
17 |
+
|
18 |
+
logger = logging.getLogger(__name__)
|
19 |
+
|
20 |
+
|
21 |
+
class ModelCardExtractor:
|
22 |
+
"""
|
23 |
+
Fine-tuned model for extracting metadata from model card text.
|
24 |
+
"""
|
25 |
+
|
26 |
+
def __init__(
|
27 |
+
self,
|
28 |
+
model_name: str = "distilbert-base-uncased",
|
29 |
+
device: str = "cpu",
|
30 |
+
max_length: int = 512,
|
31 |
+
cache_dir: Optional[str] = None,
|
32 |
+
):
|
33 |
+
"""
|
34 |
+
Initialize the model card extractor.
|
35 |
+
|
36 |
+
Args:
|
37 |
+
model_name: Name or path of the pre-trained model
|
38 |
+
device: Device to run the model on ('cpu' or 'cuda')
|
39 |
+
max_length: Maximum sequence length for tokenization
|
40 |
+
cache_dir: Directory to cache models
|
41 |
+
"""
|
42 |
+
self.model_name = model_name
|
43 |
+
self.device = device
|
44 |
+
self.max_length = max_length
|
45 |
+
self.cache_dir = cache_dir
|
46 |
+
|
47 |
+
# Load tokenizer and model
|
48 |
+
self.tokenizer = None
|
49 |
+
self.model = None
|
50 |
+
|
51 |
+
# Initialize extraction pipelines
|
52 |
+
self.section_classifier = None
|
53 |
+
self.metadata_extractor = None
|
54 |
+
|
55 |
+
# Load models
|
56 |
+
self._load_models()
|
57 |
+
|
58 |
+
def _load_models(self):
|
59 |
+
"""Load the required models for extraction."""
|
60 |
+
try:
|
61 |
+
# Load section classifier
|
62 |
+
logger.info(f"Loading section classifier model: {self.model_name}")
|
63 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
64 |
+
self.model_name,
|
65 |
+
cache_dir=self.cache_dir,
|
66 |
+
)
|
67 |
+
self.model = AutoModelForSequenceClassification.from_pretrained(
|
68 |
+
self.model_name,
|
69 |
+
cache_dir=self.cache_dir,
|
70 |
+
)
|
71 |
+
self.model.to(self.device)
|
72 |
+
|
73 |
+
# Create section classification pipeline
|
74 |
+
self.section_classifier = pipeline(
|
75 |
+
"text-classification",
|
76 |
+
model=self.model,
|
77 |
+
tokenizer=self.tokenizer,
|
78 |
+
device=0 if self.device == "cuda" else -1,
|
79 |
+
)
|
80 |
+
|
81 |
+
# For demonstration purposes, we'll use a T5-based model for extraction
|
82 |
+
# In a real implementation, this would be a fine-tuned model specific to the task
|
83 |
+
logger.info("Loading metadata extraction model")
|
84 |
+
extraction_model_name = "t5-small" # Placeholder for fine-tuned model
|
85 |
+
self.extraction_tokenizer = T5Tokenizer.from_pretrained(
|
86 |
+
extraction_model_name,
|
87 |
+
cache_dir=self.cache_dir,
|
88 |
+
)
|
89 |
+
self.extraction_model = AutoModelForSeq2SeqLM.from_pretrained(
|
90 |
+
extraction_model_name,
|
91 |
+
cache_dir=self.cache_dir,
|
92 |
+
)
|
93 |
+
self.extraction_model.to(self.device)
|
94 |
+
|
95 |
+
logger.info("Models loaded successfully")
|
96 |
+
except Exception as e:
|
97 |
+
logger.error(f"Error loading models: {e}")
|
98 |
+
raise
|
99 |
+
|
100 |
+
def extract_metadata(
|
101 |
+
self,
|
102 |
+
text: str,
|
103 |
+
fields: Optional[List[str]] = None,
|
104 |
+
) -> Dict[str, Any]:
|
105 |
+
"""
|
106 |
+
Extract metadata from model card text.
|
107 |
+
|
108 |
+
Args:
|
109 |
+
text: The model card text
|
110 |
+
fields: Optional list of specific fields to extract
|
111 |
+
|
112 |
+
Returns:
|
113 |
+
Extracted metadata as a dictionary
|
114 |
+
"""
|
115 |
+
# Split text into sections
|
116 |
+
sections = self._split_into_sections(text)
|
117 |
+
|
118 |
+
# Classify sections
|
119 |
+
classified_sections = self._classify_sections(sections)
|
120 |
+
|
121 |
+
# Extract metadata from each section
|
122 |
+
metadata = {}
|
123 |
+
for section_type, section_text in classified_sections.items():
|
124 |
+
if fields and section_type not in fields:
|
125 |
+
continue
|
126 |
+
|
127 |
+
extracted = self._extract_from_section(section_type, section_text)
|
128 |
+
if extracted:
|
129 |
+
metadata[section_type] = extracted
|
130 |
+
|
131 |
+
return metadata
|
132 |
+
|
133 |
+
def _split_into_sections(self, text: str) -> List[Dict[str, str]]:
|
134 |
+
"""
|
135 |
+
Split the model card text into sections.
|
136 |
+
|
137 |
+
Args:
|
138 |
+
text: The model card text
|
139 |
+
|
140 |
+
Returns:
|
141 |
+
List of sections with title and content
|
142 |
+
"""
|
143 |
+
# Simple section splitting based on headers
|
144 |
+
# In a real implementation, this would be more sophisticated
|
145 |
+
sections = []
|
146 |
+
|
147 |
+
# Match markdown headers (# Header, ## Header, etc.)
|
148 |
+
header_pattern = r"(?:^|\n)(#+)\s+(.*?)(?:\n|$)"
|
149 |
+
|
150 |
+
# Find all headers
|
151 |
+
headers = list(re.finditer(header_pattern, text))
|
152 |
+
|
153 |
+
for i, match in enumerate(headers):
|
154 |
+
header_level = len(match.group(1))
|
155 |
+
header_text = match.group(2).strip()
|
156 |
+
|
157 |
+
start = match.end()
|
158 |
+
|
159 |
+
# Find the end of the section (next header or end of text)
|
160 |
+
if i < len(headers) - 1:
|
161 |
+
end = headers[i + 1].start()
|
162 |
+
else:
|
163 |
+
end = len(text)
|
164 |
+
|
165 |
+
# Extract the section content
|
166 |
+
content = text[start:end].strip()
|
167 |
+
|
168 |
+
sections.append({
|
169 |
+
"title": header_text,
|
170 |
+
"level": header_level,
|
171 |
+
"content": content,
|
172 |
+
})
|
173 |
+
|
174 |
+
# If no sections were found, treat the entire text as one section
|
175 |
+
if not sections:
|
176 |
+
sections.append({
|
177 |
+
"title": "Main",
|
178 |
+
"level": 1,
|
179 |
+
"content": text.strip(),
|
180 |
+
})
|
181 |
+
|
182 |
+
return sections
|
183 |
+
|
184 |
+
def _classify_sections(self, sections: List[Dict[str, str]]) -> Dict[str, str]:
|
185 |
+
"""
|
186 |
+
Classify sections into metadata categories.
|
187 |
+
|
188 |
+
Args:
|
189 |
+
sections: List of sections with title and content
|
190 |
+
|
191 |
+
Returns:
|
192 |
+
Dictionary mapping section types to section content
|
193 |
+
"""
|
194 |
+
classified = {}
|
195 |
+
|
196 |
+
# Map common section titles to metadata fields
|
197 |
+
title_mappings = {
|
198 |
+
"model description": "description",
|
199 |
+
"description": "description",
|
200 |
+
"model details": "model_parameters",
|
201 |
+
"model architecture": "model_parameters",
|
202 |
+
"parameters": "model_parameters",
|
203 |
+
"training data": "datasets",
|
204 |
+
"dataset": "datasets",
|
205 |
+
"datasets": "datasets",
|
206 |
+
"training": "training_procedure",
|
207 |
+
"evaluation": "evaluation_results",
|
208 |
+
"results": "evaluation_results",
|
209 |
+
"performance": "evaluation_results",
|
210 |
+
"metrics": "evaluation_results",
|
211 |
+
"limitations": "limitations",
|
212 |
+
"biases": "ethical_considerations",
|
213 |
+
"bias": "ethical_considerations",
|
214 |
+
"ethical considerations": "ethical_considerations",
|
215 |
+
"ethics": "ethical_considerations",
|
216 |
+
"risks": "ethical_considerations",
|
217 |
+
"license": "license",
|
218 |
+
"citation": "citation",
|
219 |
+
"references": "citation",
|
220 |
+
}
|
221 |
+
|
222 |
+
for section in sections:
|
223 |
+
title = section["title"].lower()
|
224 |
+
content = section["content"]
|
225 |
+
|
226 |
+
# Check for direct title matches
|
227 |
+
matched = False
|
228 |
+
for key, value in title_mappings.items():
|
229 |
+
if key in title:
|
230 |
+
if value not in classified:
|
231 |
+
classified[value] = content
|
232 |
+
else:
|
233 |
+
classified[value] += "\n\n" + content
|
234 |
+
matched = True
|
235 |
+
break
|
236 |
+
|
237 |
+
# If no match by title, use the classifier
|
238 |
+
if not matched and self.section_classifier and len(content.split()) > 5:
|
239 |
+
try:
|
240 |
+
# This is a placeholder for actual classification
|
241 |
+
# In a real implementation, this would use the fine-tuned classifier
|
242 |
+
section_type = self._classify_text(content)
|
243 |
+
if section_type and section_type not in classified:
|
244 |
+
classified[section_type] = content
|
245 |
+
elif section_type:
|
246 |
+
classified[section_type] += "\n\n" + content
|
247 |
+
except Exception as e:
|
248 |
+
logger.error(f"Error classifying section: {e}")
|
249 |
+
|
250 |
+
return classified
|
251 |
+
|
252 |
+
def _classify_text(self, text: str) -> Optional[str]:
|
253 |
+
"""
|
254 |
+
Classify text into a metadata category.
|
255 |
+
|
256 |
+
Args:
|
257 |
+
text: The text to classify
|
258 |
+
|
259 |
+
Returns:
|
260 |
+
Metadata category or None if classification fails
|
261 |
+
"""
|
262 |
+
# This is a placeholder for actual classification
|
263 |
+
# In a real implementation, this would use the fine-tuned classifier
|
264 |
+
|
265 |
+
# Simple keyword-based classification for demonstration
|
266 |
+
keywords = {
|
267 |
+
"description": ["is a", "this model", "based on", "pretrained"],
|
268 |
+
"model_parameters": ["parameters", "layers", "hidden", "dimension", "architecture"],
|
269 |
+
"datasets": ["dataset", "corpus", "trained on", "fine-tuned on"],
|
270 |
+
"evaluation_results": ["accuracy", "f1", "precision", "recall", "performance"],
|
271 |
+
"limitations": ["limitation", "limited", "does not", "cannot", "fails to"],
|
272 |
+
"ethical_considerations": ["bias", "ethical", "fairness", "gender", "race"],
|
273 |
+
}
|
274 |
+
|
275 |
+
# Count keyword occurrences
|
276 |
+
counts = {category: 0 for category in keywords}
|
277 |
+
for category, words in keywords.items():
|
278 |
+
for word in words:
|
279 |
+
counts[category] += len(re.findall(r'\b' + re.escape(word) + r'\b', text.lower()))
|
280 |
+
|
281 |
+
# Return the category with the most keyword matches
|
282 |
+
if counts:
|
283 |
+
max_category = max(counts.items(), key=lambda x: x[1])
|
284 |
+
if max_category[1] > 0:
|
285 |
+
return max_category[0]
|
286 |
+
|
287 |
+
return None
|
288 |
+
|
289 |
+
def _extract_from_section(self, section_type: str, text: str) -> Any:
|
290 |
+
"""
|
291 |
+
Extract structured metadata from a section.
|
292 |
+
|
293 |
+
Args:
|
294 |
+
section_type: The type of section
|
295 |
+
text: The section text
|
296 |
+
|
297 |
+
Returns:
|
298 |
+
Extracted metadata
|
299 |
+
"""
|
300 |
+
# This is a placeholder for actual extraction
|
301 |
+
# In a real implementation, this would use the fine-tuned extraction model
|
302 |
+
|
303 |
+
if section_type == "description":
|
304 |
+
# Simply return the text for description
|
305 |
+
return text.strip()
|
306 |
+
|
307 |
+
elif section_type == "model_parameters":
|
308 |
+
# Extract model parameters using regex
|
309 |
+
params = {}
|
310 |
+
|
311 |
+
# Extract architecture
|
312 |
+
arch_match = re.search(r'(?:architecture|model type|based on)[:\s]+([A-Za-z0-9\-]+)', text, re.IGNORECASE)
|
313 |
+
if arch_match:
|
314 |
+
params["architecture"] = arch_match.group(1).strip()
|
315 |
+
|
316 |
+
# Extract parameter count
|
317 |
+
param_match = re.search(r'(\d+(?:\.\d+)?)\s*(?:B|M|K)?\s*(?:billion|million|thousand)?\s*parameters', text, re.IGNORECASE)
|
318 |
+
if param_match:
|
319 |
+
params["parameter_count"] = param_match.group(1).strip()
|
320 |
+
|
321 |
+
return params
|
322 |
+
|
323 |
+
elif section_type == "datasets":
|
324 |
+
# Extract dataset names
|
325 |
+
datasets = []
|
326 |
+
dataset_patterns = [
|
327 |
+
r'trained on\s+(?:the\s+)?([A-Za-z0-9\-\s]+)(?:\s+dataset)?',
|
328 |
+
r'dataset[:\s]+([A-Za-z0-9\-\s]+)',
|
329 |
+
r'using\s+(?:the\s+)?([A-Za-z0-9\-\s]+)(?:\s+dataset)',
|
330 |
+
]
|
331 |
+
|
332 |
+
for pattern in dataset_patterns:
|
333 |
+
for match in re.finditer(pattern, text, re.IGNORECASE):
|
334 |
+
dataset = match.group(1).strip()
|
335 |
+
if dataset and dataset.lower() not in ["this", "these", "those"]:
|
336 |
+
datasets.append(dataset)
|
337 |
+
|
338 |
+
return list(set(datasets))
|
339 |
+
|
340 |
+
elif section_type == "evaluation_results":
|
341 |
+
# Extract evaluation metrics
|
342 |
+
results = {}
|
343 |
+
|
344 |
+
# Extract accuracy
|
345 |
+
acc_match = re.search(r'accuracy[:\s]+(\d+(?:\.\d+)?)\s*%?', text, re.IGNORECASE)
|
346 |
+
if acc_match:
|
347 |
+
results["accuracy"] = float(acc_match.group(1))
|
348 |
+
|
349 |
+
# Extract F1 score
|
350 |
+
f1_match = re.search(r'f1(?:\s*[\-_]?score)?[:\s]+(\d+(?:\.\d+)?)', text, re.IGNORECASE)
|
351 |
+
if f1_match:
|
352 |
+
results["f1"] = float(f1_match.group(1))
|
353 |
+
|
354 |
+
# Extract precision
|
355 |
+
prec_match = re.search(r'precision[:\s]+(\d+(?:\.\d+)?)', text, re.IGNORECASE)
|
356 |
+
if prec_match:
|
357 |
+
results["precision"] = float(prec_match.group(1))
|
358 |
+
|
359 |
+
# Extract recall
|
360 |
+
recall_match = re.search(r'recall[:\s]+(\d+(?:\.\d+)?)', text, re.IGNORECASE)
|
361 |
+
if recall_match:
|
362 |
+
results["recall"] = float(recall_match.group(1))
|
363 |
+
|
364 |
+
return results
|
365 |
+
|
366 |
+
elif section_type == "limitations":
|
367 |
+
# Simply return the text for limitations
|
368 |
+
return text.strip()
|
369 |
+
|
370 |
+
elif section_type == "ethical_considerations":
|
371 |
+
# Simply return the text for ethical considerations
|
372 |
+
return text.strip()
|
373 |
+
|
374 |
+
elif section_type == "license":
|
375 |
+
# Extract license information
|
376 |
+
license_match = re.search(r'(?:license|licensing)[:\s]+([A-Za-z0-9\-\s]+)', text, re.IGNORECASE)
|
377 |
+
if license_match:
|
378 |
+
return license_match.group(1).strip()
|
379 |
+
return text.strip()
|
380 |
+
|
381 |
+
elif section_type == "citation":
|
382 |
+
# Simply return the text for citation
|
383 |
+
return text.strip()
|
384 |
+
|
385 |
+
# Default case
|
386 |
+
return text.strip()
|
387 |
+
|
388 |
+
|
389 |
+
class InferenceModelServer:
|
390 |
+
"""
|
391 |
+
Server for the inference model.
|
392 |
+
|
393 |
+
This class provides a server for the inference model that can be deployed
|
394 |
+
as a standalone service with a REST API.
|
395 |
+
"""
|
396 |
+
|
397 |
+
def __init__(
|
398 |
+
self,
|
399 |
+
model_name: str = "distilbert-base-uncased",
|
400 |
+
device: str = "cpu",
|
401 |
+
cache_dir: Optional[str] = None,
|
402 |
+
):
|
403 |
+
"""
|
404 |
+
Initialize the inference model server.
|
405 |
+
|
406 |
+
Args:
|
407 |
+
model_name: Name or path of the pre-trained model
|
408 |
+
device: Device to run the model on ('cpu' or 'cuda')
|
409 |
+
cache_dir: Directory to cache models
|
410 |
+
"""
|
411 |
+
self.extractor = ModelCardExtractor(
|
412 |
+
model_name=model_name,
|
413 |
+
device=device,
|
414 |
+
cache_dir=cache_dir,
|
415 |
+
)
|
416 |
+
|
417 |
+
def extract_metadata(
|
418 |
+
self,
|
419 |
+
text: str,
|
420 |
+
structured_metadata: Optional[Dict[str, Any]] = None,
|
421 |
+
fields: Optional[List[str]] = None,
|
422 |
+
) -> Dict[str, Any]:
|
423 |
+
"""
|
424 |
+
Extract metadata from model card text.
|
425 |
+
|
426 |
+
Args:
|
427 |
+
text: The model card text
|
428 |
+
structured_metadata: Optional structured metadata to provide context
|
429 |
+
fields: Optional list of specific fields to extract
|
430 |
+
|
431 |
+
Returns:
|
432 |
+
Extracted metadata as a dictionary
|
433 |
+
"""
|
434 |
+
try:
|
435 |
+
# Extract metadata using the extractor
|
436 |
+
metadata = self.extractor.extract_metadata(text, fields)
|
437 |
+
|
438 |
+
# Enhance with structured metadata if provided
|
439 |
+
if structured_metadata:
|
440 |
+
# Use structured metadata for fields not extracted
|
441 |
+
for key, value in structured_metadata.items():
|
442 |
+
if key not in metadata or not metadata[key]:
|
443 |
+
metadata[key] = value
|
444 |
+
|
445 |
+
return {"metadata": metadata, "success": True}
|
446 |
+
except Exception as e:
|
447 |
+
logger.error(f"Error extracting metadata: {e}")
|
448 |
+
return {"metadata": {}, "success": False, "error": str(e)}
|
449 |
+
|
450 |
+
|
451 |
+
def create_app(model_name: str = "distilbert-base-uncased", device: str = "cpu"):
|
452 |
+
"""
|
453 |
+
Create a Flask app for the inference model server.
|
454 |
+
|
455 |
+
Args:
|
456 |
+
model_name: Name or path of the pre-trained model
|
457 |
+
device: Device to run the model on ('cpu' or 'cuda')
|
458 |
+
|
459 |
+
Returns:
|
460 |
+
Flask app
|
461 |
+
"""
|
462 |
+
from flask import Flask, request, jsonify
|
463 |
+
|
464 |
+
app = Flask(__name__)
|
465 |
+
server = InferenceModelServer(model_name=model_name, device=device)
|
466 |
+
|
467 |
+
@app.route("/extract", methods=["POST"])
|
468 |
+
def extract():
|
469 |
+
data = request.json
|
470 |
+
text = data.get("text", "")
|
471 |
+
structured_metadata = data.get("structured_metadata", {})
|
472 |
+
fields = data.get("fields", [])
|
473 |
+
|
474 |
+
result = server.extract_metadata(text, structured_metadata, fields)
|
475 |
+
return jsonify(result)
|
476 |
+
|
477 |
+
@app.route("/health", methods=["GET"])
|
478 |
+
def health():
|
479 |
+
return jsonify({"status": "healthy"})
|
480 |
+
|
481 |
+
return app
|
482 |
+
|
483 |
+
|
484 |
+
def main():
|
485 |
+
"""Main entry point for the inference model server."""
|
486 |
+
import argparse
|
487 |
+
|
488 |
+
parser = argparse.ArgumentParser(
|
489 |
+
description="Start the inference model server for AIBOM metadata extraction."
|
490 |
+
)
|
491 |
+
|
492 |
+
parser.add_argument(
|
493 |
+
"--model",
|
494 |
+
help="Name or path of the pre-trained model",
|
495 |
+
default="distilbert-base-uncased",
|
496 |
+
)
|
497 |
+
|
498 |
+
parser.add_argument(
|
499 |
+
"--device",
|
500 |
+
help="Device to run the model on ('cpu' or 'cuda')",
|
501 |
+
choices=["cpu", "cuda"],
|
502 |
+
default="cpu",
|
503 |
+
)
|
504 |
+
|
505 |
+
parser.add_argument(
|
506 |
+
"--host",
|
507 |
+
help="Host to bind the server to",
|
508 |
+
default="0.0.0.0",
|
509 |
+
)
|
510 |
+
|
511 |
+
parser.add_argument(
|
512 |
+
"--port",
|
513 |
+
help="Port to bind the server to",
|
514 |
+
type=int,
|
515 |
+
default=5000,
|
516 |
+
)
|
517 |
+
|
518 |
+
parser.add_argument(
|
519 |
+
"--debug",
|
520 |
+
help="Enable debug mode",
|
521 |
+
action="store_true",
|
522 |
+
)
|
523 |
+
|
524 |
+
args = parser.parse_args()
|
525 |
+
|
526 |
+
# Create and run the app
|
527 |
+
app = create_app(model_name=args.model, device=args.device)
|
528 |
+
app.run(host=args.host, port=args.port, debug=args.debug)
|
529 |
+
|
530 |
+
|
531 |
+
if __name__ == "__main__":
|
532 |
+
main()
|
src/aibom_generator/integration.py
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Integration with the main generator class to use the inference model.
|
3 |
+
"""
|
4 |
+
|
5 |
+
import logging
|
6 |
+
from typing import Dict, List, Optional, Any
|
7 |
+
|
8 |
+
from huggingface_hub import ModelCard
|
9 |
+
|
10 |
+
from aibom_generator.inference import MetadataExtractor
|
11 |
+
from aibom_generator.utils import merge_metadata
|
12 |
+
|
13 |
+
logger = logging.getLogger(__name__)
|
14 |
+
|
15 |
+
|
16 |
+
class InferenceModelIntegration:
|
17 |
+
"""
|
18 |
+
Integration with the inference model for metadata extraction.
|
19 |
+
"""
|
20 |
+
|
21 |
+
def __init__(
|
22 |
+
self,
|
23 |
+
inference_url: Optional[str] = None,
|
24 |
+
use_inference: bool = True,
|
25 |
+
):
|
26 |
+
"""
|
27 |
+
Initialize the inference model integration.
|
28 |
+
|
29 |
+
Args:
|
30 |
+
inference_url: URL of the inference model service
|
31 |
+
use_inference: Whether to use the inference model
|
32 |
+
"""
|
33 |
+
self.extractor = MetadataExtractor(inference_url, use_inference)
|
34 |
+
|
35 |
+
def extract_metadata_from_model_card(
|
36 |
+
self,
|
37 |
+
model_card: ModelCard,
|
38 |
+
structured_metadata: Optional[Dict[str, Any]] = None,
|
39 |
+
fields: Optional[List[str]] = None,
|
40 |
+
) -> Dict[str, Any]:
|
41 |
+
"""
|
42 |
+
Extract metadata from a model card using the inference model.
|
43 |
+
|
44 |
+
Args:
|
45 |
+
model_card: The ModelCard object
|
46 |
+
structured_metadata: Optional structured metadata to provide context
|
47 |
+
fields: Optional list of specific fields to extract
|
48 |
+
|
49 |
+
Returns:
|
50 |
+
Extracted metadata as a dictionary
|
51 |
+
"""
|
52 |
+
if not model_card:
|
53 |
+
logger.warning("No model card provided for inference extraction")
|
54 |
+
return {}
|
55 |
+
|
56 |
+
# Get the model card text content
|
57 |
+
model_card_text = model_card.text if hasattr(model_card, "text") else ""
|
58 |
+
|
59 |
+
if not model_card_text:
|
60 |
+
logger.warning("Model card has no text content for inference extraction")
|
61 |
+
return {}
|
62 |
+
|
63 |
+
# Extract metadata using the extractor
|
64 |
+
extracted_metadata = self.extractor.extract_metadata(
|
65 |
+
model_card_text, structured_metadata, fields
|
66 |
+
)
|
67 |
+
|
68 |
+
return extracted_metadata
|
69 |
+
|
70 |
+
def enhance_metadata(
|
71 |
+
self,
|
72 |
+
structured_metadata: Dict[str, Any],
|
73 |
+
model_card: ModelCard,
|
74 |
+
) -> Dict[str, Any]:
|
75 |
+
"""
|
76 |
+
Enhance structured metadata with information extracted from the model card.
|
77 |
+
|
78 |
+
Args:
|
79 |
+
structured_metadata: Structured metadata from API
|
80 |
+
model_card: The ModelCard object
|
81 |
+
|
82 |
+
Returns:
|
83 |
+
Enhanced metadata as a dictionary
|
84 |
+
"""
|
85 |
+
# Identify missing fields that could be extracted from unstructured text
|
86 |
+
missing_fields = self._identify_missing_fields(structured_metadata)
|
87 |
+
|
88 |
+
if not missing_fields:
|
89 |
+
logger.info("No missing fields to extract from unstructured text")
|
90 |
+
return structured_metadata
|
91 |
+
|
92 |
+
# Extract missing fields from unstructured text
|
93 |
+
extracted_metadata = self.extract_metadata_from_model_card(
|
94 |
+
model_card, structured_metadata, missing_fields
|
95 |
+
)
|
96 |
+
|
97 |
+
# Merge the extracted metadata with the structured metadata
|
98 |
+
# Structured metadata takes precedence
|
99 |
+
enhanced_metadata = merge_metadata(structured_metadata, extracted_metadata)
|
100 |
+
|
101 |
+
return enhanced_metadata
|
102 |
+
|
103 |
+
def _identify_missing_fields(self, metadata: Dict[str, Any]) -> List[str]:
|
104 |
+
"""
|
105 |
+
Identify fields that are missing or incomplete in the metadata.
|
106 |
+
|
107 |
+
Args:
|
108 |
+
metadata: The metadata to check
|
109 |
+
|
110 |
+
Returns:
|
111 |
+
List of missing field names
|
112 |
+
"""
|
113 |
+
missing_fields = []
|
114 |
+
|
115 |
+
# Check for missing or empty fields
|
116 |
+
important_fields = [
|
117 |
+
"description",
|
118 |
+
"license",
|
119 |
+
"model_parameters",
|
120 |
+
"datasets",
|
121 |
+
"evaluation_results",
|
122 |
+
"limitations",
|
123 |
+
"ethical_considerations",
|
124 |
+
]
|
125 |
+
|
126 |
+
for field in important_fields:
|
127 |
+
if field not in metadata or not metadata[field]:
|
128 |
+
missing_fields.append(field)
|
129 |
+
elif isinstance(metadata[field], dict) and not any(metadata[field].values()):
|
130 |
+
missing_fields.append(field)
|
131 |
+
elif isinstance(metadata[field], list) and not metadata[field]:
|
132 |
+
missing_fields.append(field)
|
133 |
+
|
134 |
+
return missing_fields
|
src/aibom_generator/utils.py
ADDED
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Utility functions for the AIBOM Generator.
|
3 |
+
"""
|
4 |
+
|
5 |
+
import json
|
6 |
+
import logging
|
7 |
+
import os
|
8 |
+
import re
|
9 |
+
import uuid
|
10 |
+
from typing import Dict, List, Optional, Any, Union
|
11 |
+
|
12 |
+
logger = logging.getLogger(__name__)
|
13 |
+
|
14 |
+
|
15 |
+
def setup_logging(level=logging.INFO):
|
16 |
+
"""Set up logging configuration."""
|
17 |
+
logging.basicConfig(
|
18 |
+
level=level,
|
19 |
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
20 |
+
datefmt="%Y-%m-%d %H:%M:%S",
|
21 |
+
)
|
22 |
+
|
23 |
+
|
24 |
+
def ensure_directory(directory_path):
|
25 |
+
"""Ensure that a directory exists, creating it if necessary."""
|
26 |
+
if not os.path.exists(directory_path):
|
27 |
+
os.makedirs(directory_path)
|
28 |
+
return directory_path
|
29 |
+
|
30 |
+
|
31 |
+
def generate_uuid():
|
32 |
+
"""Generate a UUID for the AIBOM serialNumber."""
|
33 |
+
return str(uuid.uuid4())
|
34 |
+
|
35 |
+
|
36 |
+
def normalize_license_id(license_text):
|
37 |
+
"""
|
38 |
+
Normalize a license string to a SPDX license identifier if possible.
|
39 |
+
|
40 |
+
Args:
|
41 |
+
license_text: The license text to normalize
|
42 |
+
|
43 |
+
Returns:
|
44 |
+
SPDX license identifier or the original text if no match
|
45 |
+
"""
|
46 |
+
# Common license mappings
|
47 |
+
license_mappings = {
|
48 |
+
"mit": "MIT",
|
49 |
+
"apache": "Apache-2.0",
|
50 |
+
"apache 2": "Apache-2.0",
|
51 |
+
"apache 2.0": "Apache-2.0",
|
52 |
+
"apache-2": "Apache-2.0",
|
53 |
+
"apache-2.0": "Apache-2.0",
|
54 |
+
"gpl": "GPL-3.0-only",
|
55 |
+
"gpl-3": "GPL-3.0-only",
|
56 |
+
"gpl-3.0": "GPL-3.0-only",
|
57 |
+
"gpl3": "GPL-3.0-only",
|
58 |
+
"gpl v3": "GPL-3.0-only",
|
59 |
+
"gpl-2": "GPL-2.0-only",
|
60 |
+
"gpl-2.0": "GPL-2.0-only",
|
61 |
+
"gpl2": "GPL-2.0-only",
|
62 |
+
"gpl v2": "GPL-2.0-only",
|
63 |
+
"lgpl": "LGPL-3.0-only",
|
64 |
+
"lgpl-3": "LGPL-3.0-only",
|
65 |
+
"lgpl-3.0": "LGPL-3.0-only",
|
66 |
+
"bsd": "BSD-3-Clause",
|
67 |
+
"bsd-3": "BSD-3-Clause",
|
68 |
+
"bsd-3-clause": "BSD-3-Clause",
|
69 |
+
"bsd-2": "BSD-2-Clause",
|
70 |
+
"bsd-2-clause": "BSD-2-Clause",
|
71 |
+
"cc": "CC-BY-4.0",
|
72 |
+
"cc-by": "CC-BY-4.0",
|
73 |
+
"cc-by-4.0": "CC-BY-4.0",
|
74 |
+
"cc-by-sa": "CC-BY-SA-4.0",
|
75 |
+
"cc-by-sa-4.0": "CC-BY-SA-4.0",
|
76 |
+
"cc-by-nc": "CC-BY-NC-4.0",
|
77 |
+
"cc-by-nc-4.0": "CC-BY-NC-4.0",
|
78 |
+
"cc0": "CC0-1.0",
|
79 |
+
"cc0-1.0": "CC0-1.0",
|
80 |
+
"public domain": "CC0-1.0",
|
81 |
+
"unlicense": "Unlicense",
|
82 |
+
"proprietary": "NONE",
|
83 |
+
"commercial": "NONE",
|
84 |
+
}
|
85 |
+
|
86 |
+
if not license_text:
|
87 |
+
return None
|
88 |
+
|
89 |
+
# Normalize to lowercase and remove punctuation
|
90 |
+
normalized = re.sub(r'[^\w\s-]', '', license_text.lower())
|
91 |
+
|
92 |
+
# Check for direct matches
|
93 |
+
if normalized in license_mappings:
|
94 |
+
return license_mappings[normalized]
|
95 |
+
|
96 |
+
# Check for partial matches
|
97 |
+
for key, value in license_mappings.items():
|
98 |
+
if key in normalized:
|
99 |
+
return value
|
100 |
+
|
101 |
+
# Return original if no match
|
102 |
+
return license_text
|
103 |
+
|
104 |
+
|
105 |
+
def calculate_completeness_score(aibom: Dict[str, Any]) -> int:
|
106 |
+
"""
|
107 |
+
Calculate a completeness score for the AIBOM.
|
108 |
+
|
109 |
+
Args:
|
110 |
+
aibom: The AIBOM dictionary
|
111 |
+
|
112 |
+
Returns:
|
113 |
+
Completeness score (0-100)
|
114 |
+
"""
|
115 |
+
score = 0
|
116 |
+
max_score = 100
|
117 |
+
|
118 |
+
# Define scoring weights for different sections
|
119 |
+
weights = {
|
120 |
+
"required_fields": 20,
|
121 |
+
"metadata": 20,
|
122 |
+
"component_basic": 20,
|
123 |
+
"component_model_card": 30,
|
124 |
+
"external_references": 10,
|
125 |
+
}
|
126 |
+
|
127 |
+
# Check required fields (20%)
|
128 |
+
required_fields = ["bomFormat", "specVersion", "serialNumber", "version"]
|
129 |
+
required_score = sum(1 for field in required_fields if field in aibom)
|
130 |
+
score += (required_score / len(required_fields)) * weights["required_fields"]
|
131 |
+
|
132 |
+
# Check metadata (20%)
|
133 |
+
if "metadata" in aibom:
|
134 |
+
metadata = aibom["metadata"]
|
135 |
+
metadata_fields = ["timestamp", "tools", "authors", "component"]
|
136 |
+
metadata_score = sum(1 for field in metadata_fields if field in metadata)
|
137 |
+
score += (metadata_score / len(metadata_fields)) * weights["metadata"]
|
138 |
+
|
139 |
+
# Check component basic info (20%)
|
140 |
+
if "components" in aibom and aibom["components"]:
|
141 |
+
component = aibom["components"][0]
|
142 |
+
component_fields = ["type", "name", "bom-ref", "purl", "description", "licenses"]
|
143 |
+
component_score = sum(1 for field in component_fields if field in component)
|
144 |
+
score += (component_score / len(component_fields)) * weights["component_basic"]
|
145 |
+
|
146 |
+
# Check model card (30%)
|
147 |
+
if "modelCard" in component:
|
148 |
+
model_card = component["modelCard"]
|
149 |
+
model_card_fields = ["modelParameters", "quantitativeAnalysis", "considerations"]
|
150 |
+
model_card_score = sum(1 for field in model_card_fields if field in model_card)
|
151 |
+
score += (model_card_score / len(model_card_fields)) * weights["component_model_card"]
|
152 |
+
|
153 |
+
# Check external references (10%)
|
154 |
+
if "externalReferences" in aibom and aibom["externalReferences"]:
|
155 |
+
score += weights["external_references"]
|
156 |
+
|
157 |
+
return round(score)
|
158 |
+
|
159 |
+
|
160 |
+
def merge_metadata(primary: Dict[str, Any], secondary: Dict[str, Any]) -> Dict[str, Any]:
|
161 |
+
"""
|
162 |
+
Merge two metadata dictionaries, giving priority to the primary dictionary.
|
163 |
+
|
164 |
+
Args:
|
165 |
+
primary: Primary metadata dictionary
|
166 |
+
secondary: Secondary metadata dictionary
|
167 |
+
|
168 |
+
Returns:
|
169 |
+
Merged metadata dictionary
|
170 |
+
"""
|
171 |
+
result = secondary.copy()
|
172 |
+
|
173 |
+
for key, value in primary.items():
|
174 |
+
if value is not None:
|
175 |
+
if key in result and isinstance(value, dict) and isinstance(result[key], dict):
|
176 |
+
result[key] = merge_metadata(value, result[key])
|
177 |
+
else:
|
178 |
+
result[key] = value
|
179 |
+
|
180 |
+
return result
|
181 |
+
|
182 |
+
|
183 |
+
def extract_model_id_parts(model_id: str) -> Dict[str, str]:
|
184 |
+
"""
|
185 |
+
Extract parts from a Hugging Face model ID.
|
186 |
+
|
187 |
+
Args:
|
188 |
+
model_id: Hugging Face model ID (e.g., "google/bert-base-uncased")
|
189 |
+
|
190 |
+
Returns:
|
191 |
+
Dictionary with parts (owner, name)
|
192 |
+
"""
|
193 |
+
parts = model_id.split("/")
|
194 |
+
|
195 |
+
if len(parts) == 1:
|
196 |
+
return {
|
197 |
+
"owner": None,
|
198 |
+
"name": parts[0],
|
199 |
+
}
|
200 |
+
else:
|
201 |
+
return {
|
202 |
+
"owner": parts[0],
|
203 |
+
"name": "/".join(parts[1:]),
|
204 |
+
}
|
205 |
+
|
206 |
+
|
207 |
+
def create_purl(model_id: str) -> str:
|
208 |
+
"""
|
209 |
+
Create a Package URL (purl) for a Hugging Face model.
|
210 |
+
|
211 |
+
Args:
|
212 |
+
model_id: Hugging Face model ID
|
213 |
+
|
214 |
+
Returns:
|
215 |
+
Package URL string
|
216 |
+
"""
|
217 |
+
parts = extract_model_id_parts(model_id)
|
218 |
+
|
219 |
+
if parts["owner"]:
|
220 |
+
return f"pkg:huggingface/{parts['owner']}/{parts['name']}"
|
221 |
+
else:
|
222 |
+
return f"pkg:huggingface/{parts['name']}"
|
src/aibom_generator/worker.py
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Background worker for the AIBOM Generator.
|
3 |
+
|
4 |
+
This module provides a background worker that can be used to process
|
5 |
+
AIBOM generation tasks asynchronously.
|
6 |
+
"""
|
7 |
+
|
8 |
+
import logging
|
9 |
+
import os
|
10 |
+
import time
|
11 |
+
from typing import Dict, List, Optional, Any
|
12 |
+
|
13 |
+
from aibom_generator.generator import AIBOMGenerator
|
14 |
+
from aibom_generator.utils import setup_logging, calculate_completeness_score
|
15 |
+
|
16 |
+
# Set up logging
|
17 |
+
setup_logging()
|
18 |
+
logger = logging.getLogger(__name__)
|
19 |
+
|
20 |
+
|
21 |
+
class Worker:
|
22 |
+
"""
|
23 |
+
Background worker for AIBOM generation.
|
24 |
+
"""
|
25 |
+
|
26 |
+
def __init__(
|
27 |
+
self,
|
28 |
+
poll_interval: int = 60,
|
29 |
+
hf_token: Optional[str] = None,
|
30 |
+
inference_model_url: Optional[str] = None,
|
31 |
+
use_inference: bool = True,
|
32 |
+
cache_dir: Optional[str] = None,
|
33 |
+
):
|
34 |
+
"""
|
35 |
+
Initialize the worker.
|
36 |
+
|
37 |
+
Args:
|
38 |
+
poll_interval: Interval in seconds to poll for new tasks
|
39 |
+
hf_token: Hugging Face API token
|
40 |
+
inference_model_url: URL of the inference model service
|
41 |
+
use_inference: Whether to use the inference model
|
42 |
+
cache_dir: Directory to cache API responses and model cards
|
43 |
+
"""
|
44 |
+
self.poll_interval = poll_interval
|
45 |
+
self.generator = AIBOMGenerator(
|
46 |
+
hf_token=hf_token,
|
47 |
+
inference_model_url=inference_model_url,
|
48 |
+
use_inference=use_inference,
|
49 |
+
cache_dir=cache_dir,
|
50 |
+
)
|
51 |
+
self.running = False
|
52 |
+
|
53 |
+
def start(self):
|
54 |
+
"""Start the worker."""
|
55 |
+
self.running = True
|
56 |
+
logger.info("Worker started")
|
57 |
+
|
58 |
+
try:
|
59 |
+
while self.running:
|
60 |
+
# Process tasks
|
61 |
+
self._process_tasks()
|
62 |
+
|
63 |
+
# Sleep for poll interval
|
64 |
+
time.sleep(self.poll_interval)
|
65 |
+
except KeyboardInterrupt:
|
66 |
+
logger.info("Worker stopped by user")
|
67 |
+
except Exception as e:
|
68 |
+
logger.error(f"Worker error: {e}")
|
69 |
+
finally:
|
70 |
+
self.running = False
|
71 |
+
logger.info("Worker stopped")
|
72 |
+
|
73 |
+
def stop(self):
|
74 |
+
"""Stop the worker."""
|
75 |
+
self.running = False
|
76 |
+
|
77 |
+
def _process_tasks(self):
|
78 |
+
"""Process pending tasks."""
|
79 |
+
# This is a placeholder for actual task processing
|
80 |
+
# In a real implementation, this would fetch tasks from a queue or database
|
81 |
+
logger.debug("Processing tasks")
|
82 |
+
|
83 |
+
# Simulate task processing
|
84 |
+
# In a real implementation, this would process actual tasks
|
85 |
+
pass
|
86 |
+
|
87 |
+
|
88 |
+
def main():
|
89 |
+
"""Main entry point for the worker."""
|
90 |
+
# Create and start the worker
|
91 |
+
worker = Worker(
|
92 |
+
poll_interval=int(os.environ.get("AIBOM_POLL_INTERVAL", 60)),
|
93 |
+
hf_token=os.environ.get("HF_TOKEN"),
|
94 |
+
inference_model_url=os.environ.get("AIBOM_INFERENCE_URL"),
|
95 |
+
use_inference=os.environ.get("AIBOM_USE_INFERENCE", "true").lower() == "true",
|
96 |
+
cache_dir=os.environ.get("AIBOM_CACHE_DIR"),
|
97 |
+
)
|
98 |
+
|
99 |
+
worker.start()
|
100 |
+
|
101 |
+
|
102 |
+
if __name__ == "__main__":
|
103 |
+
main()
|