Update processor.py
Browse files13 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061622 unmodified lines656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617 unmodified lines19419519619719819920020120220320420520620720820921021121221321411 unmodified lines2262272282292302312322332342352362372382392402412422432442453 unmodified lines2492502512522532542553 unmodified lines2592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962971 unmodified line29930030130230330430530630730830931031131231331431531631731831932032132232332432513 unmodified linesself.token = tokenself.api = HfApi(token=token)# --- 1. METADATA & INSPECTION ---def get_dataset_metadata(self, dataset_id):configs = []splits = []license_name = "unknown"# 1. Get Configstry:configs = get_dataset_config_names(dataset_id, token=self.token)except Exception as e:logger.warning(f"Could not fetch configs: {e}")configs = ['default']# 2. Get Splits & Licensetry:selected_config = configs[0] if configs else 'default'infos = get_dataset_infos(dataset_id, token=self.token)info_obj = Noneif selected_config in infos:info_obj = infos[selected_config]elif 'default' in infos:info_obj = infos['default']elif len(infos) > 0:info_obj = list(infos.values())[0]if info_obj:splits = list(info_obj.splits.keys())license_name = info_obj.license or "unknown"except Exception as e:logger.warning(f"Metadata fetch fallback: {e}")splits = ['train', 'test', 'validation']return {"status": "success","configs": configs if configs else ['default'],"splits": splits if splits else ['train'],"license_detected": license_name}def get_splits_for_config(self, dataset_id, config_name):try:infos = get_dataset_infos(dataset_id, config_name=config_name, token=self.token)if config_name in infos:2 unmodified linessplits = list(infos.values())[0].splits.keys()else:splits = ['train', 'test']except:splits = ['train', 'test', 'validation']return {"status": "success", "splits": splits}def inspect_dataset(self, dataset_id, config, split):try:conf = config if config != 'default' else Noneds_stream = load_dataset(dataset_id, name=conf, split=split, streaming=True, token=self.token)sample_rows = []schema_map = {}for i, row in enumerate(ds_stream):if i >= 10: break# Create clean sample for UIclean_row = {}for k, v in row.items():# Convert objects to strings for display safetyif not isinstance(v, (str, int, float, bool, list, dict, type(None))):clean_row[k] = str(v)else:clean_row[k] = vsample_rows.append(clean_row)# Analyze Schemafor k, v in row.items():if k not in schema_map:schema_map[k] = {"is_list": False, "keys": set()}val = v# Check for JSON stringif isinstance(val, str):try:val = json.loads(val)except: passif isinstance(val, list):schema_map[k]["is_list"] = Trueif len(val) > 0 and isinstance(val[0], dict):schema_map[k]["keys"].update(val[0].keys())elif isinstance(val, dict):schema_map[k]["keys"].update(val.keys())formatted_schema = {}for k, info in schema_map.items():formatted_schema[k] = {"type": "List" if info["is_list"] else "Object","keys": list(info["keys"])}return {"status": "success","samples": sample_rows,"schema": formatted_schema,"dataset_id": dataset_id}except Exception as e:return {"status": "error", "message": str(e)}# --- 2. EXTRACTION LOGIC ---def _get_value_by_path(self, obj, path):if not path: return objkeys = path.split('.')current = objfor key in keys:if isinstance(current, str):s = current.strip()if (s.startswith('{') and s.endswith('}')) or (s.startswith('[') and s.endswith(']')):try:current = json.loads(s)except: passif isinstance(current, dict) and key in current:current = current[key]else:return Nonereturn currentdef _extract_from_list_logic(self, row, source_col, filter_key, filter_val, target_path):data = row.get(source_col)if isinstance(data, str):try:data = json.loads(data)except: return Noneif not isinstance(data, list):return Nonematched_item = Nonefor item in data:if str(item.get(filter_key, '')) == str(filter_val):matched_item = itembreakif matched_item:return self._get_value_by_path(matched_item, target_path)return Nonedef _apply_projection(self, row, recipe):new_row = {}# Setup Context for Python/Evaleval_context = row.copy()eval_context['row'] = roweval_context['json'] = json17 unmodified lines)elif t_type == 'python':expression = col_def['expression']val = eval(expression, {}, eval_context)new_row[target_col] = valexcept Exception as e:# Fail Fast: Raise error to stop the generatorraise ValueError(f"Column '{target_col}' failed: {str(e)}")return new_row# --- 3. DOCUMENTATION (CARD) ---def _generate_card(self, source_id, target_id, recipe, license_name):logger.info(f"Generating card for {target_id} with license {license_name}")card_data = DatasetCardData(language="en",license=license_name,11 unmodified linesThe following operations were applied to the source data:| Target Column | Source | Type | Logic / Filter ||---------------|--------|------|----------------|"""for col in recipe['columns']:c_type = col.get('type', 'simple')c_name = col['name']c_src = col.get('source', '-')logic = "-"if c_type == 'simple': logic = "Direct Mapping"elif c_type == 'list_search': logic = f"Get `{col['target_key']}` where `{col['filter_key']} == {col['filter_val']}`"elif c_type == 'python': logic = f"`{col.get('expression')}`"content += f"| **{c_name}** | `{c_src}` | {c_type} | {logic} |\n"if recipe.get('filter_rule'):content += f"\n### Row Filtering\n**Filter Applied:** `{recipe['filter_rule']}`\n"3 unmodified linescard = DatasetCard.from_template(card_data, content=content)return card# --- 4. EXECUTION ---def process_and_push(self, source_id, config, split, target_id, recipe, max_rows=None, new_license=None):logger.info(f"Job started: {source_id} -> {target_id}")3 unmodified linesds_stream = load_dataset(source_id, name=conf, split=split, streaming=True, token=self.token)count = 0for i, row in enumerate(ds_stream):if max_rows and count >= int(max_rows): break# Filterif recipe.get('filter_rule'):try:ctx = row.copy()ctx['row'] = rowif not eval(recipe['filter_rule'], {}, ctx):continueexcept Exception as e:raise ValueError(f"Filter crashed on row {i}: {e}")# Projectiontry:yield self._apply_projection(row, recipe)count += 1except ValueError as ve:raise veexcept Exception as e:raise ValueError(f"Crash on row {i}: {e}")try:# 1. Push Datanew_dataset = datasets.Dataset.from_generator(gen)new_dataset.push_to_hub(target_id, token=self.token)# 2. Push Cardtry:card = self._generate_card(source_id, target_id, recipe, new_license or "unknown")card.push_to_hub(target_id, token=self.token)except Exception as e:logger.error(f"Failed to push Dataset Card: {e}")# We do NOT fail the whole job, but we log it.return {"status": "success", "rows_processed": len(new_dataset)}1 unmodified linelogger.error(f"Job Failed: {e}")return {"status": "failed", "error": str(e)}# --- 5. PREVIEW ---def preview_transform(self, dataset_id, config, split, recipe):conf = config if config != 'default' else Noneds_stream = load_dataset(dataset_id, name=conf, split=split, streaming=True, token=self.token)processed = []for row in ds_stream:if len(processed) >= 5: break# Filterpassed = Trueif recipe.get('filter_rule'):try:ctx = row.copy()ctx['row'] = rowif not eval(recipe['filter_rule'], {}, ctx): passed = Falseexcept: passed = Falseif passed:try:processed.append(self._apply_projection(row, recipe))except Exception as e:processed.append({"error": str(e)}) # Show error in previewreturn processed13 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273742 unmodified lines777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024117 unmodified lines25926026126226326426526626726826927027127227327427527627727827928028128228311 unmodified lines2952962972982993003013023033043053063073083093103113123133143153163 unmodified lines3203213223233243253263273283 unmodified lines3323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723731 unmodified line37537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541613 unmodified linesself.token = tokenself.api = HfApi(token=token)# ==========================================# 1. METADATA & INSPECTION# ==========================================def get_dataset_metadata(self, dataset_id):"""Fetches available Configs (subsets), Splits, and License infowithout downloading the actual data rows."""configs = ['default']splits = ['train', 'test', 'validation']license_name = "unknown"try:# 1. Fetch Configstry:found_configs = get_dataset_config_names(dataset_id, token=self.token)if found_configs:configs = found_configsexcept Exception:pass # Keep default# 2. Fetch Metadata (Splits & License)try:selected = configs[0]# This API call can fail on some datasets, so we wrap it safelyinfos = get_dataset_infos(dataset_id, token=self.token)info = Noneif selected in infos:info = infos[selected]elif 'default' in infos:info = infos['default']elif infos:info = list(infos.values())[0]if info:splits = list(info.splits.keys())license_name = info.license or "unknown"except Exception:pass # Keep defaults if metadata failsreturn {"status": "success","configs": configs,"splits": splits,"license_detected": license_name}except Exception as e:return {"status": "error", "message": str(e)}def get_splits_for_config(self, dataset_id, config_name):"""Updates the Split dropdown when the user changes the Config."""try:infos = get_dataset_infos(dataset_id, config_name=config_name, token=self.token)if config_name in infos:2 unmodified linessplits = list(infos.values())[0].splits.keys()else:splits = ['train', 'test']return {"status": "success", "splits": splits}except:return {"status": "success", "splits": ['train', 'test', 'validation']}def _flatten_object(self, obj, parent_key='', sep='.'):"""Recursively finds all keys in nested dicts or JSON stringsto populate the 'Simple Path' dropdown in the UI."""items = {}# Transparently parse JSON stringsif isinstance(obj, str):s = obj.strip()if (s.startswith('{') and s.endswith('}')) or (s.startswith('[') and s.endswith(']')):try:obj = json.loads(s)except:pass # Keep as string if parse failsif isinstance(obj, dict):for k, v in obj.items():new_key = f"{parent_key}{sep}{k}" if parent_key else kitems.update(self._flatten_object(v, new_key, sep=sep))elif isinstance(obj, list):# We mark lists but do not recurse infinitelynew_key = f"{parent_key}" if parent_key else "list_content"items[new_key] = "List"else:# Leaf nodeitems[parent_key] = type(obj).__name__return itemsdef inspect_dataset(self, dataset_id, config, split):"""Scans the first 10 rows to build a Schema Tree for the UI."""try:conf = config if config != 'default' else Noneds_stream = load_dataset(dataset_id, name=conf, split=split, streaming=True, token=self.token)sample_rows = []available_paths = set()schema_map = {} # Used for List Mode detectionfor i, row in enumerate(ds_stream):if i >= 10: break# 1. Clean row for UI Preview (convert objects to strings)clean_row = {}for k, v in row.items():if not isinstance(v, (str, int, float, bool, list, dict, type(None))):clean_row[k] = str(v)else:clean_row[k] = vsample_rows.append(clean_row)# 2. Deep Flattening for "Simple Path" dropdownsflattened = self._flatten_object(row)available_paths.update(flattened.keys())# 3. Top Level Analysis for "List Mode" detectionfor k, v in row.items():if k not in schema_map:schema_map[k] = {"type": "Object"}val = vif isinstance(val, str):try: val = json.loads(val)except: passif isinstance(val, list):schema_map[k]["type"] = "List"# Reconstruct Schema Tree for UI groupingsorted_paths = sorted(list(available_paths))schema_tree = {}for path in sorted_paths:root = path.split('.')[0]if root not in schema_tree:schema_tree[root] = []schema_tree[root].append(path)return {"status": "success","samples": sample_rows,"schema_tree": schema_tree, # Used by Simple Path Dropdown"schema": schema_map, # Used by List Mode Dropdown"dataset_id": dataset_id}except Exception as e:return {"status": "error", "message": str(e)}# ==========================================# 2. CORE EXTRACTION LOGIC# ==========================================def _get_value_by_path(self, obj, path):"""Navigates dot notation (meta.user.id), automatically parsingJSON strings if encountered along the path."""if not path: return objkeys = path.split('.')current = objfor key in keys:# Auto-parse JSON string if encounteredif isinstance(current, str):s = current.strip()if (s.startswith('{') and s.endswith('}')) or (s.startswith('[') and s.endswith(']')):try:current = json.loads(s)except:passif isinstance(current, dict) and key in current:current = current[key]else:return None # Path brokenreturn currentdef _extract_from_list_logic(self, row, source_col, filter_key, filter_val, target_path):"""Logic for: FROM source_col FIND ITEM WHERE filter_key == filter_val EXTRACT target_path"""data = row.get(source_col)# Parse if stringif isinstance(data, str):try:data = json.loads(data)except:return Noneif not isinstance(data, list):return Nonematched_item = Nonefor item in data:# String comparison for safetyif str(item.get(filter_key, '')) == str(filter_val):matched_item = itembreakif matched_item:return self._get_value_by_path(matched_item, target_path)return Nonedef _apply_projection(self, row, recipe):"""Builds the new row based on the recipe.Raises ValueError if user Python code fails (Fail Fast)."""new_row = {}# Setup Eval Context (Variables available in Python Mode)eval_context = row.copy()eval_context['row'] = roweval_context['json'] = json17 unmodified lines)elif t_type == 'python':# Execute user codeexpression = col_def['expression']val = eval(expression, {}, eval_context)new_row[target_col] = valexcept Exception as e:# Fail Fast: Stop the generator immediately if a column failsraise ValueError(f"Column '{target_col}' failed: {str(e)}")return new_row# ==========================================# 3. DOCUMENTATION (MODEL CARD)# ==========================================def _generate_card(self, source_id, target_id, recipe, license_name):"""Creates a README.md for the new dataset."""card_data = DatasetCardData(language="en",license=license_name,11 unmodified linesThe following operations were applied to the source data:| Target Column | Operation Type | Logic ||---------------|----------------|-------|"""for col in recipe['columns']:c_type = col.get('type', 'simple')c_name = col['name']logic = "-"if c_type == 'simple':logic = f"Mapped from `{col.get('source')}`"elif c_type == 'list_search':logic = f"Extracted `{col['target_key']}` where `{col['filter_key']} == {col['filter_val']}`"elif c_type == 'python':logic = f"Python: `{col.get('expression')}`"content += f"| **{c_name}** | {c_type} | {logic} |\n"if recipe.get('filter_rule'):content += f"\n### Row Filtering\n**Filter Applied:** `{recipe['filter_rule']}`\n"3 unmodified linescard = DatasetCard.from_template(card_data, content=content)return card# ==========================================# 4. EXECUTION# ==========================================def process_and_push(self, source_id, config, split, target_id, recipe, max_rows=None, new_license=None):logger.info(f"Job started: {source_id} -> {target_id}")3 unmodified linesds_stream = load_dataset(source_id, name=conf, split=split, streaming=True, token=self.token)count = 0for i, row in enumerate(ds_stream):if max_rows and count >= int(max_rows):break# 1. Filterif recipe.get('filter_rule'):try:ctx = row.copy()ctx['row'] = rowctx['json'] = jsonctx['re'] = reif not eval(recipe['filter_rule'], {}, ctx):continueexcept Exception as e:raise ValueError(f"Filter crashed on row {i}: {e}")# 2. Projectiontry:yield self._apply_projection(row, recipe)count += 1except ValueError as ve:# Pass the specific column error upraise veexcept Exception as e:raise ValueError(f"Unexpected crash on row {i}: {e}")try:# 1. Process & Push Datanew_dataset = datasets.Dataset.from_generator(gen)new_dataset.push_to_hub(target_id, token=self.token)# 2. Generate & Push Cardtry:card = self._generate_card(source_id, target_id, recipe, new_license or "unknown")card.push_to_hub(target_id, token=self.token)except Exception as e:logger.error(f"Failed to push Dataset Card: {e}")return {"status": "success", "rows_processed": len(new_dataset)}1 unmodified linelogger.error(f"Job Failed: {e}")return {"status": "failed", "error": str(e)}# ==========================================# 5. PREVIEW# ==========================================def preview_transform(self, dataset_id, config, split, recipe):conf = config if config != 'default' else Nonetry:ds_stream = load_dataset(dataset_id, name=conf, split=split, streaming=True, token=self.token)processed = []for i, row in enumerate(ds_stream):if len(processed) >= 5: break# Check Filterpassed = Trueif recipe.get('filter_rule'):try:ctx = row.copy()ctx['row'] = rowctx['json'] = jsonctx['re'] = reif not eval(recipe['filter_rule'], {}, ctx):passed = Falseexcept:passed = False # Skip invalid rows in previewif passed:try:new_row = self._apply_projection(row, recipe)processed.append(new_row)except Exception as e:# In preview, we want to see the error, not crashprocessed.append({"_preview_error": f"Error: {str(e)}"})return processedexcept Exception as e:# Return global error if loading failsraise e
processor.py+194-103