@@ -88,15 +88,7 @@ def load_file(
8888 data = fixing_old_schema (data , copy_data = True )
8989 if compact :
9090 if compact_context :
91- if _is_file (compact_context ):
92- with open (compact_context ) as fp :
93- context = json .load (fp )
94- elif _is_url (compact_context ):
95- context = _fetch_jsonld_context (compact_context )
96- else :
97- raise Exception (
98- f"compact_context has tobe a file or url, but { compact_context } provided"
99- )
91+ context = read_contextfile (compact_context )
10092 if _is_file (path_or_url ):
10193 data = jsonld .compact (
10294 data , ctx = context , options = {"base" : base_url }
@@ -128,7 +120,7 @@ def validate_data(data):
128120 # normalized = jsonld.normalize(data, kwargs)
129121 obj_type = identify_model_class (data ["@type" ][0 ])
130122 data_fixed = [fixing_old_schema (data , copy_data = True )]
131- context = _fetch_jsonld_context (CONTEXTFILE_URL )
123+ context = read_contextfile (CONTEXTFILE_URL )
132124 data_fixed_comp = jsonld .compact (data_fixed , context )
133125 del data_fixed_comp ["@context" ]
134126 conforms = False
@@ -141,6 +133,40 @@ def validate_data(data):
141133 return conforms , v_text
142134
143135
136+ def read_contextfile (contextfile ):
137+ """Read a context file and return the context."""
138+ if _is_file (contextfile ):
139+ with open (contextfile ) as fp :
140+ context = json .load (fp )
141+ elif _is_url (contextfile ):
142+ context = _fetch_jsonld_context (contextfile )
143+ else :
144+ raise Exception (
145+ f"compact_context has tobe a file or url, but { contextfile } provided"
146+ )
147+ return context
148+
149+
150+ def get_context_version (contextfile ):
151+ """Get the version from the context file path"""
152+ from packaging .version import InvalidVersion , Version
153+
154+ if contextfile .split ("/" )[- 3 ] != "releases" :
155+ raise ValueError (
156+ f"Can't get the version from { contextfile } , expected to have releases in the path"
157+ )
158+ else :
159+ try :
160+ Version (contextfile .split ("/" )[- 2 ])
161+ return contextfile .split ("/" )[- 2 ]
162+ except InvalidVersion :
163+ raise ValueError (
164+ f"Can't get the version from { contextfile } , "
165+ f"expected to have a valid version in the path, "
166+ f"but got { contextfile .split ('/' )[- 2 ]} "
167+ )
168+
169+
144170def to_newformat (path , format , prefixfile = None , contextfile = None ):
145171 """Convert a JSONLD document to n-triples format
146172
@@ -171,8 +197,7 @@ def to_newformat(path, format, prefixfile=None, contextfile=None):
171197 data = load_file (path )
172198 if format == "jsonld" :
173199 if contextfile is not None :
174- with open (contextfile ) as fp :
175- context = json .load (fp )
200+ context = read_contextfile (contextfile )
176201 data = jsonld .compact (data , context )
177202 return json .dumps (data , indent = 2 )
178203 kwargs = {"algorithm" : "URDNA2015" , "format" : "application/n-quads" }
0 commit comments