Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Scripts/*
!**/composer.json
!**/package.json
!**/bower.json
!**/.zenodo.json
*.ttl
env_3.9/*
somef_core_env/
Expand All @@ -27,6 +28,7 @@ repos.txt
!test_data/api_responses/*.json
!**/test_data/api_responses/codeberg/*.json
!**/test_data/api_responses/bitbucket/*.json
!**/test_data/api_responses/zenodo/*.json
uv.lock
.python-version
rebuild_from_somef/
9 changes: 3 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

SOMEF-Core is a lightweight export of [SOMEF](https://github.com/KnowledgeCaptureAndDiscovery/somef) (the parent project), containing its core metadata extraction functionality. It works both as a command line tool and as a reusable library, without the machine learning components (supervised classifiers, ontology detection) that are part of the full SOMEF tool. See the SOMEF repository for the full documentation and ML capabilities.

> This release of SOMEF-Core (0.0.1) corresponds to SOMEF [0.11.3](https://github.com/KnowledgeCaptureAndDiscovery/somef/releases/tag/0.11.3).
> This release of SOMEF-Core (0.0.2) corresponds to SOMEF [0.11.5](https://github.com/KnowledgeCaptureAndDiscovery/somef/releases/tag/0.11.5).

**Demo:** See a [demo running somef as a service](https://somef.linkeddata.es), through the [SOMEF-Vider tool](https://github.com/SoftwareUnderstanding/SOMEF-Vider/).

Expand Down Expand Up @@ -62,6 +62,7 @@ When using `-e`, publication metadata is enriched via OpenAlex. We recognize the
- **Identifier**: Identifier associated with the software (if any), such as Digital Object Identifiers and Software Heritage identifiers (SWH). DOIs associated with publications will also be detected. When using `-e`, the following enrichment identifiers are also added:
- `openaire_id`: URL to the OpenAIRE explore page for the software
- `swhid`: Software Heritage identifier (for Zenodo DOIs)
- `provider`: Name of the identifier provider. For Software Heritage identifiers this is set to Software Heritage. For DOIs registered with DataCite, this is set to the DataCite provider name (e.g., CERN - European Organization for Nuclear Research).
- **Images**: Images used to illustrate the software component
- **Installation instructions**: A set of instructions that indicate how to install a target repository
- **Invocation**: Execution command(s) needed to run a scientific software component
Expand Down Expand Up @@ -170,11 +171,7 @@ pip install somef-core

### NLTK data

SOMEF-Core uses [NLTK](https://www.nltk.org/) / WordNet to match README section headers (e.g. "Getting Started", "Citation") against metadata categories. Download the required data before running SOMEF-Core:

```bash
python -m nltk.downloader wordnet omw-1.4 punkt punkt_tab stopwords
```
SOMEF-Core uses [NLTK](https://www.nltk.org/) / WordNet to match README section headers (e.g. "Getting Started", "Citation") against metadata categories. Running `somef_core configure` (see below) takes care of downloading the required NLTK data automatically.

## Install from GitHub

Expand Down
143 changes: 138 additions & 5 deletions poetry.lock

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "somef_core"
version = "0.0.1"
version = "0.0.2"
description = "SOMEF-Core: lightweight metadata extraction engine for software repositories, usable as a CLI tool or as a library, without the ML-based classifiers and ontology detection of the full SOMEF tool."
authors = ["Daniel Garijo <daniel.garijo@upm.es>"]
readme = "README.md"
Expand All @@ -27,19 +27,20 @@ homepage = "https://github.com/SciCodes/somef-core"
numpy = ">=1.26.3,<3.0.0"
pandas = "^2.1.4"
textblob = ">=0.17.1,<0.21.0"
validators = "^0.35.0"
validators = ">=0.35,<0.37"
scipy = "^1.11.4"
inflect = "^7.0.0"
contractions = "^0.1.73"
chardet = ">=5.2,<8.0"
pytest = ">=8,<10"
bibtexparser = "^1.4.1"
bibtexparser = "^2.1.0"
nbformat = "^5.9.2"
markdown = "^3.5.2"
requests = "^2.34.2"
pyyaml = "^6.0.2"
lxml = "^6.1.1"
markdown-it-py = ">=3,<5"
rapidfuzz = "^3.14.6"

[tool.poetry.scripts]
somef_core = "somef_core.__main__:cli"
Expand Down
2 changes: 1 addition & 1 deletion src/somef_core/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# -*- coding: utf-8 -*-

__version__ = "0.0.1"
__version__ = "0.0.2"
8 changes: 6 additions & 2 deletions src/somef_core/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def cli():
click.echo("SOftware Metadata Extraction Framework (SOMEF) Command Line Interface")


@cli.group(help="Configure repository credentials", invoke_without_command=True)
@cli.group(help="Configure repository credentials and classifiers file path", invoke_without_command=True)
@click.option('-a', '--auto', help="Automatically configure SOMEF", is_flag=True, default=False)
@click.option('-b', '--base_uri', type=URLParamType(), help="Base URI for somef transformations",
default=constants.CONF_DEFAULT_BASE_URI)
Expand Down Expand Up @@ -87,7 +87,6 @@ def test():
"-ic",
is_flag=True,
default=False,
hidden=True,
help="Flag to ignore running the classifiers (by default False)"
)
@click.option(
Expand All @@ -112,6 +111,11 @@ def test():
type=URLParamType(),
help="Github/Gitlab Repository URL",
)
@optgroup.option(
"--doi",
help="Zenodo DOI or record URL (e.g. https://doi.org/10.5281/zenodo.22943101, "
"10.5281/zenodo.22943101or https://zenodo.org/records/22943101)",
)
@optgroup.option(
"--doc_src",
"-d",
Expand Down
43 changes: 32 additions & 11 deletions src/somef_core/header_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
import numpy as np
import pandas as pd
from textblob import Word

from rapidfuzz import process
from rapidfuzz.distance import Levenshtein
from .process_results import Result
from .parser import mardown_parser
from .utils import constants
Expand Down Expand Up @@ -306,17 +307,20 @@ def label_text(text: str, similarity_threshold=constants.CONF_DEFAULT_SIMILARITY
for token in tokenize_header(text):
synsets = get_synsets(token)
if synsets:
grp = match_group(synsets, similarity_threshold )
# grp = match_group(synsets, similarity_threshold )
# Skip if the header matches a known false positive for this group

# if isinstance(text, list):
# text = " ".join(text)

if is_false_positive_header(text, grp):
# print(f"Skipping false positive header '{text}' for category '{grp}'")
continue
if grp and grp not in labels:
labels.append(grp)
grp = match_group(synsets, similarity_threshold)
else:
grp = fuzzy_group(token)

# if isinstance(text, list):
# text = " ".join(text)

if is_false_positive_header(text, grp):
# print(f"Skipping false positive header '{text}' for category '{grp}'")
continue
if grp and grp not in labels:
labels.append(grp)
return labels

def is_false_positive_header(text: str, category: str) -> bool:
Expand Down Expand Up @@ -710,3 +714,20 @@ def extract_os_from_content(text: str) -> List[dict]:
})

return results

def fuzzy_group(token, max_distance=1, min_length=5):

"""
Try to match a word to a category, allowing small typos (ej: 'Instalation' would be accpet as 'installation').
See the dictionary in constants.
"""

t = token.lower()
if t in constants.HEADER_VOCABULARY:
return constants.HEADER_VOCABULARY[t]
if len(t) < min_length:
return ""
match = process.extractOne(t, constants.HEADER_VOCABULARY.keys(),
scorer=Levenshtein.distance, score_cutoff=max_distance)
return constants.HEADER_VOCABULARY[match[0]] if match else ""

26 changes: 16 additions & 10 deletions src/somef_core/parser/codemeta_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -642,16 +642,22 @@ def parse_codemeta_json_file(file_path, metadata_result: Result, source):
)

if "identifier" in data:
metadata_result.add_result(
constants.CAT_IDENTIFIER,
{
"value": data["identifier"],
"type": constants.STRING
},
1,
constants.TECHNIQUE_CODE_CONFIG_PARSER,
source
)
if isinstance(data["identifier"], list) :
identifiers = data["identifier"]
else:
identifiers = [data["identifier"]]

for identifier in identifiers:
metadata_result.add_result(
constants.CAT_IDENTIFIER,
{
"value": identifier,
"type": constants.STRING
},
1,
constants.TECHNIQUE_CODE_CONFIG_PARSER,
source
)

if "readme" in data:
metadata_result.add_result(
Expand Down
24 changes: 18 additions & 6 deletions src/somef_core/parser/codeowners_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from pathlib import Path
from ..process_results import Result
from ..utils import constants
from .. import configuration

def parse_codeowners_structured(dir_path, filename):
codeowners = []
Expand Down Expand Up @@ -159,11 +160,23 @@ def enrich_user(username, repo_type, server_url=None, gitlab_authorization=None)
# response = requests.get(api_url, timeout=5)
# Build auth header — same token works for gitlab.com and self-hosted instances
gl_headers = {}
if gitlab_authorization:
token = gitlab_authorization
if not token.startswith("Bearer "):
token = "Bearer " + token
gl_headers["Authorization"] = token
token = gitlab_authorization
if not token:
try:
file_paths = configuration.get_configuration_file()
if constants.CONF_GITLAB_AUTHORIZATION in file_paths:
token = file_paths[constants.CONF_GITLAB_AUTHORIZATION]
except Exception:
pass
if token and isinstance(token, str):
t = token.strip()
if t.lower().startswith('bearer '):
t = t[7:].strip()
elif t.lower().startswith('token '):
t = t[6:].strip()
elif t.lower().startswith('private-token '):
t = t[14:].strip()
gl_headers['Authorization'] = f'Bearer {t}'
response = requests.get(api_url, headers=gl_headers, timeout=5)
if response.status_code != 200:
logging.warning(f"GitLab API request failed for {username}: {response.status_code}")
Expand All @@ -180,7 +193,6 @@ def enrich_user(username, repo_type, server_url=None, gitlab_authorization=None)
except Exception as e:
logging.error(f"Error enriching GitLab user {username}: {e}")
return None

elif repo_type == constants.RepositoryType.CODEBERG:
url = f"https://codeberg.org/api/v1/users/{username}"
response = requests.get(url, timeout=5)
Expand Down
4 changes: 3 additions & 1 deletion src/somef_core/parser/description_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,9 @@ def parse_description_file(file_path, metadata_result: Result, source):
"value": req,
"name": name,
"version": version,
"type": constants.SOFTWARE_DEPENDENCY
"type": constants.SOFTWARE_DEPENDENCY,
"dependency_type": constants.DEPENDENCY_TYPE_RUNTIME,
"dependency_resolver": "cran"
},
1,
constants.TECHNIQUE_CODE_CONFIG_PARSER,
Expand Down
4 changes: 3 additions & 1 deletion src/somef_core/parser/gemspec_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,9 @@ def parse_gemspec_file(file_path, metadata_result: Result, source):
constants.CAT_REQUIREMENTS,
{
"value": dependencies,
"type": constants.SOFTWARE_DEPENDENCY
"type": constants.SOFTWARE_DEPENDENCY,
"dependency_type": constants.DEPENDENCY_TYPE_RUNTIME,
"dependency_resolver": "bundler"
},
1,
constants.TECHNIQUE_CODE_CONFIG_PARSER,
Expand Down
4 changes: 3 additions & 1 deletion src/somef_core/parser/python_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,9 @@ def parse_requirements_txt(file_path, metadata_result: Result, source):
req = {
"value": line,
"name": name,
"type": constants.SOFTWARE_DEPENDENCY
"type": constants.SOFTWARE_DEPENDENCY,
"dependency_type": constants.DEPENDENCY_TYPE_RUNTIME,
"dependency_resolver": "pip"
}
if version:
req['version'] = version
Expand Down
Loading
Loading