after_merge
stringlengths
28
79.6k
before_merge
stringlengths
20
79.6k
url
stringlengths
38
71
full_traceback
stringlengths
43
922k
traceback_type
stringclasses
555 values
def _get_aoe2_base(cls, gamedata): """ Create the aoe2-base modpack. """ modpack = Modpack("aoe2_base") mod_def = modpack.get_info() mod_def.set_version("1.0c") mod_def.set_uid(2000) mod_def.add_assets_to_load("data/*") cls.organize_nyan_objects(modpack, gamedata) cls.organize_media_objects(modpack, gamedata) return modpack
def _get_aoe2_base(cls, gamedata): """ Create the aoe2-base modpack. """ modpack = Modpack("aoe2-base") mod_def = modpack.get_info() mod_def.set_version("1.0c") mod_def.set_uid(2000) mod_def.add_assets_to_load("data/*") cls.organize_nyan_objects(modpack, gamedata) cls.organize_media_objects(modpack, gamedata) return modpack
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def organize_nyan_objects(modpack, full_data_set): """ Put available nyan objects into a given modpack. """ created_nyan_files = {} # Access all raw API objects raw_api_objects = [] raw_api_objects.extend(full_data_set.pregen_nyan_objects.values()) for unit_line in full_data_set.unit_lines.values(): raw_api_objects.extend(unit_line.get_raw_api_objects().values()) for building_line in full_data_set.building_lines.values(): raw_api_objects.extend(building_line.get_raw_api_objects().values()) for ambient_group in full_data_set.ambient_groups.values(): raw_api_objects.extend(ambient_group.get_raw_api_objects().values()) for variant_group in full_data_set.variant_groups.values(): raw_api_objects.extend(variant_group.get_raw_api_objects().values()) for tech_group in full_data_set.tech_groups.values(): raw_api_objects.extend(tech_group.get_raw_api_objects().values()) for terrain_group in full_data_set.terrain_groups.values(): raw_api_objects.extend(terrain_group.get_raw_api_objects().values()) for civ_group in full_data_set.civ_groups.values(): raw_api_objects.extend(civ_group.get_raw_api_objects().values()) # Create the files for raw_api_object in raw_api_objects: obj_location = raw_api_object.get_location() if isinstance(obj_location, ForwardRef): # Resolve location and add nested object nyan_object = obj_location.resolve() nyan_object.add_nested_object(raw_api_object.get_nyan_object()) continue obj_filename = raw_api_object.get_filename() nyan_file_path = f"{modpack.info.name}/{obj_location}{obj_filename}" if nyan_file_path in created_nyan_files.keys(): nyan_file = created_nyan_files[nyan_file_path] else: nyan_file = NyanFile(obj_location, obj_filename, modpack.info.name) created_nyan_files.update({nyan_file.get_relative_file_path(): nyan_file}) modpack.add_data_export(nyan_file) nyan_file.add_nyan_object(raw_api_object.get_nyan_object()) # Create an import tree from the files import_tree = ImportTree() for nyan_file in created_nyan_files.values(): import_tree.expand_from_file(nyan_file) for nyan_object in full_data_set.nyan_api_objects.values(): import_tree.expand_from_object(nyan_object) for nyan_file in created_nyan_files.values(): nyan_file.set_import_tree(import_tree) AoCModpackSubprocessor._set_static_aliases(modpack, import_tree)
def organize_nyan_objects(modpack, full_data_set): """ Put available nyan objects into a given modpack. """ created_nyan_files = {} # Access all raw API objects raw_api_objects = [] raw_api_objects.extend(full_data_set.pregen_nyan_objects.values()) for unit_line in full_data_set.unit_lines.values(): raw_api_objects.extend(unit_line.get_raw_api_objects().values()) for building_line in full_data_set.building_lines.values(): raw_api_objects.extend(building_line.get_raw_api_objects().values()) for ambient_group in full_data_set.ambient_groups.values(): raw_api_objects.extend(ambient_group.get_raw_api_objects().values()) for variant_group in full_data_set.variant_groups.values(): raw_api_objects.extend(variant_group.get_raw_api_objects().values()) for tech_group in full_data_set.tech_groups.values(): raw_api_objects.extend(tech_group.get_raw_api_objects().values()) for terrain_group in full_data_set.terrain_groups.values(): raw_api_objects.extend(terrain_group.get_raw_api_objects().values()) for civ_group in full_data_set.civ_groups.values(): raw_api_objects.extend(civ_group.get_raw_api_objects().values()) # Create the files for raw_api_object in raw_api_objects: obj_location = raw_api_object.get_location() if isinstance(obj_location, ForwardRef): # Resolve location and add nested object nyan_object = obj_location.resolve() nyan_object.add_nested_object(raw_api_object.get_nyan_object()) continue obj_filename = raw_api_object.get_filename() nyan_file_path = f"{modpack.info.name}/{obj_location}{obj_filename}" if nyan_file_path in created_nyan_files.keys(): nyan_file = created_nyan_files[nyan_file_path] else: nyan_file = NyanFile(obj_location, obj_filename, modpack.info.name) created_nyan_files.update({nyan_file.get_relative_file_path(): nyan_file}) modpack.add_data_export(nyan_file) nyan_file.add_nyan_object(raw_api_object.get_nyan_object()) # Create an import tree from the files import_tree = ImportTree() for nyan_file in created_nyan_files.values(): import_tree.expand_from_file(nyan_file) for nyan_object in full_data_set.nyan_api_objects.values(): import_tree.expand_from_object(nyan_object) for nyan_file in created_nyan_files.values(): nyan_file.set_import_tree(import_tree)
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def generate_modifiers(full_data_set, pregen_converter_group): """ Generate standard modifiers. :param full_data_set: GenieObjectContainer instance that contains all relevant data for the conversion process. :type full_data_set: ...dataformat.aoc.genie_object_container.GenieObjectContainer :param pregen_converter_group: GenieObjectGroup instance that stores pregenerated API objects for referencing with ForwardRef :type pregen_converter_group: ...dataformat.aoc.genie_object_container.GenieObjectGroup """ pregen_nyan_objects = full_data_set.pregen_nyan_objects api_objects = full_data_set.nyan_api_objects modifier_parent = "engine.modifier.multiplier.MultiplierModifier" type_parent = "engine.modifier.multiplier.effect.flat_attribute_change.type.Flyover" types_location = "data/aux/modifier/flyover_cliff/" # ======================================================================= # Flyover effect multiplier # ======================================================================= modifier_ref_in_modpack = "aux.modifier.flyover_cliff.AttackMultiplierFlyover" modifier_raw_api_object = RawAPIObject( modifier_ref_in_modpack, "AttackMultiplierFlyover", api_objects, types_location ) modifier_raw_api_object.set_filename("flyover_cliff") modifier_raw_api_object.add_raw_parent(type_parent) pregen_converter_group.add_raw_api_object(modifier_raw_api_object) pregen_nyan_objects.update({modifier_ref_in_modpack: modifier_raw_api_object}) # Increases effect value by 25% modifier_raw_api_object.add_raw_member("multiplier", 1.25, modifier_parent) # Relative angle to cliff must not be larger than 90° modifier_raw_api_object.add_raw_member("relative_angle", 90, type_parent) # Affects all cliffs types = [ForwardRef(pregen_converter_group, "aux.game_entity_type.types.Cliff")] modifier_raw_api_object.add_raw_member("flyover_types", types, type_parent) modifier_raw_api_object.add_raw_member("blacklisted_entities", [], type_parent) # ======================================================================= # Elevation difference effect multiplier (higher unit) # ======================================================================= modifier_parent = "engine.modifier.multiplier.MultiplierModifier" type_parent = "engine.modifier.multiplier.effect.flat_attribute_change.type.ElevationDifferenceHigh" types_location = "data/aux/modifier/elevation_difference/" modifier_ref_in_modpack = "aux.modifier.elevation_difference.AttackMultiplierHigh" modifier_raw_api_object = RawAPIObject( modifier_ref_in_modpack, "AttackMultiplierHigh", api_objects, types_location ) modifier_raw_api_object.set_filename("elevation_difference") modifier_raw_api_object.add_raw_parent(type_parent) pregen_converter_group.add_raw_api_object(modifier_raw_api_object) pregen_nyan_objects.update({modifier_ref_in_modpack: modifier_raw_api_object}) # Increases effect value to 125% modifier_raw_api_object.add_raw_member("multiplier", 1.25, modifier_parent) # Min elevation difference is not set # ======================================================================= # Elevation difference effect multiplier (lower unit) # ======================================================================= modifier_parent = "engine.modifier.multiplier.MultiplierModifier" type_parent = "engine.modifier.multiplier.effect.flat_attribute_change.type.ElevationDifferenceLow" types_location = "data/aux/modifier/elevation_difference/" modifier_ref_in_modpack = "aux.modifier.elevation_difference.AttackMultiplierLow" modifier_raw_api_object = RawAPIObject( modifier_ref_in_modpack, "AttackMultiplierLow", api_objects, types_location ) modifier_raw_api_object.set_filename("elevation_difference") modifier_raw_api_object.add_raw_parent(type_parent) pregen_converter_group.add_raw_api_object(modifier_raw_api_object) pregen_nyan_objects.update({modifier_ref_in_modpack: modifier_raw_api_object}) # Decreases effect value to 75% modifier_raw_api_object.add_raw_member("multiplier", 0.75, modifier_parent)
def generate_modifiers(full_data_set, pregen_converter_group): """ Generate standard modifiers. :param full_data_set: GenieObjectContainer instance that contains all relevant data for the conversion process. :type full_data_set: ...dataformat.aoc.genie_object_container.GenieObjectContainer :param pregen_converter_group: GenieObjectGroup instance that stores pregenerated API objects for referencing with ForwardRef :type pregen_converter_group: ...dataformat.aoc.genie_object_container.GenieObjectGroup """ pregen_nyan_objects = full_data_set.pregen_nyan_objects api_objects = full_data_set.nyan_api_objects modifier_parent = "engine.modifier.multiplier.MultiplierModifier" type_parent = "engine.modifier.multiplier.effect.flat_attribute_change.type.Flyover" types_location = "data/aux/modifier/flyover_cliff" # ======================================================================= # Flyover effect multiplier # ======================================================================= modifier_ref_in_modpack = "aux.modifier.flyover_cliff.AttackMultiplierFlyover" modifier_raw_api_object = RawAPIObject( modifier_ref_in_modpack, "AttackMultiplierFlyover", api_objects, types_location ) modifier_raw_api_object.set_filename("flyover_cliff") modifier_raw_api_object.add_raw_parent(type_parent) pregen_converter_group.add_raw_api_object(modifier_raw_api_object) pregen_nyan_objects.update({modifier_ref_in_modpack: modifier_raw_api_object}) # Increases effect value by 25% modifier_raw_api_object.add_raw_member("multiplier", 1.25, modifier_parent) # Relative angle to cliff must not be larger than 90° modifier_raw_api_object.add_raw_member("relative_angle", 90, type_parent) # Affects all cliffs types = [ForwardRef(pregen_converter_group, "aux.game_entity_type.types.Cliff")] modifier_raw_api_object.add_raw_member("flyover_types", types, type_parent) modifier_raw_api_object.add_raw_member("blacklisted_entities", [], type_parent) # ======================================================================= # Elevation difference effect multiplier (higher unit) # ======================================================================= modifier_parent = "engine.modifier.multiplier.MultiplierModifier" type_parent = "engine.modifier.multiplier.effect.flat_attribute_change.type.ElevationDifferenceHigh" types_location = "data/aux/modifier/elevation_difference" modifier_ref_in_modpack = "aux.modifier.elevation_difference.AttackMultiplierHigh" modifier_raw_api_object = RawAPIObject( modifier_ref_in_modpack, "AttackMultiplierHigh", api_objects, types_location ) modifier_raw_api_object.set_filename("elevation_difference") modifier_raw_api_object.add_raw_parent(type_parent) pregen_converter_group.add_raw_api_object(modifier_raw_api_object) pregen_nyan_objects.update({modifier_ref_in_modpack: modifier_raw_api_object}) # Increases effect value to 125% modifier_raw_api_object.add_raw_member("multiplier", 1.25, modifier_parent) # Min elevation difference is not set # ======================================================================= # Elevation difference effect multiplier (lower unit) # ======================================================================= modifier_parent = "engine.modifier.multiplier.MultiplierModifier" type_parent = "engine.modifier.multiplier.effect.flat_attribute_change.type.ElevationDifferenceLow" types_location = "data/aux/modifier/elevation_difference" modifier_ref_in_modpack = "aux.modifier.elevation_difference.AttackMultiplierLow" modifier_raw_api_object = RawAPIObject( modifier_ref_in_modpack, "AttackMultiplierLow", api_objects, types_location ) modifier_raw_api_object.set_filename("elevation_difference") modifier_raw_api_object.add_raw_parent(type_parent) pregen_converter_group.add_raw_api_object(modifier_raw_api_object) pregen_nyan_objects.update({modifier_ref_in_modpack: modifier_raw_api_object}) # Decreases effect value to 75% modifier_raw_api_object.add_raw_member("multiplier", 0.75, modifier_parent)
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def live_ability(converter_group, line, container_obj_ref, diff=None): """ Creates a patch for the Live ability of a line. :param converter_group: Group that gets the patch. :type converter_group: ...dataformat.converter_object.ConverterObjectGroup :param line: Unit/Building line that has the ability. :type line: ...dataformat.converter_object.ConverterObjectGroup :param container_obj_ref: Reference of the raw API object the patch is nested in. :type container_obj_ref: str :param diff: A diff between two ConvertObject instances. :type diff: ...dataformat.converter_object.ConverterObject :returns: The forward references for the generated patches. :rtype: list """ head_unit_id = line.get_head_unit_id() tech_id = converter_group.get_id() dataset = line.data patches = [] name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version) tech_lookup_dict = internal_name_lookups.get_tech_lookups(dataset.game_version) game_entity_name = name_lookup_dict[head_unit_id][0] if diff: diff_hp = diff["hit_points"] if isinstance(diff_hp, NoDiffMember): return patches diff_hp_value = diff_hp.get_value() else: return patches patch_target_ref = f"{game_entity_name}.Live.Health" patch_target_forward_ref = ForwardRef(line, patch_target_ref) # Wrapper wrapper_name = f"Change{game_entity_name}HealthWrapper" wrapper_ref = f"{container_obj_ref}.{wrapper_name}" wrapper_raw_api_object = RawAPIObject( wrapper_ref, wrapper_name, dataset.nyan_api_objects ) wrapper_raw_api_object.add_raw_parent("engine.aux.patch.Patch") if isinstance(line, GenieBuildingLineGroup): # Store building upgrades next to their game entity definition, # not in the Age up techs. wrapper_raw_api_object.set_location( "data/game_entity/generic/%s/" % (name_lookup_dict[head_unit_id][1]) ) wrapper_raw_api_object.set_filename(f"{tech_lookup_dict[tech_id][1]}_upgrade") else: wrapper_raw_api_object.set_location( ForwardRef(converter_group, container_obj_ref) ) # Nyan patch nyan_patch_name = f"Change{game_entity_name}Health" nyan_patch_ref = f"{container_obj_ref}.{wrapper_name}.{nyan_patch_name}" nyan_patch_location = ForwardRef(converter_group, wrapper_ref) nyan_patch_raw_api_object = RawAPIObject( nyan_patch_ref, nyan_patch_name, dataset.nyan_api_objects, nyan_patch_location ) nyan_patch_raw_api_object.add_raw_parent("engine.aux.patch.NyanPatch") nyan_patch_raw_api_object.set_patch_target(patch_target_forward_ref) # HP max value nyan_patch_raw_api_object.add_raw_patch_member( "max_value", diff_hp_value, "engine.aux.attribute.AttributeSetting", MemberOperator.ADD, ) # HP starting value nyan_patch_raw_api_object.add_raw_patch_member( "starting_value", diff_hp_value, "engine.aux.attribute.AttributeSetting", MemberOperator.ADD, ) patch_forward_ref = ForwardRef(converter_group, nyan_patch_ref) wrapper_raw_api_object.add_raw_member( "patch", patch_forward_ref, "engine.aux.patch.Patch" ) converter_group.add_raw_api_object(wrapper_raw_api_object) converter_group.add_raw_api_object(nyan_patch_raw_api_object) wrapper_forward_ref = ForwardRef(converter_group, wrapper_ref) patches.append(wrapper_forward_ref) return patches
def live_ability(converter_group, line, container_obj_ref, diff=None): """ Creates a patch for the Live ability of a line. :param converter_group: Group that gets the patch. :type converter_group: ...dataformat.converter_object.ConverterObjectGroup :param line: Unit/Building line that has the ability. :type line: ...dataformat.converter_object.ConverterObjectGroup :param container_obj_ref: Reference of the raw API object the patch is nested in. :type container_obj_ref: str :param diff: A diff between two ConvertObject instances. :type diff: ...dataformat.converter_object.ConverterObject :returns: The forward references for the generated patches. :rtype: list """ head_unit_id = line.get_head_unit_id() tech_id = converter_group.get_id() dataset = line.data patches = [] name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version) tech_lookup_dict = internal_name_lookups.get_tech_lookups(dataset.game_version) game_entity_name = name_lookup_dict[head_unit_id][0] if diff: diff_hp = diff["hit_points"] if isinstance(diff_hp, NoDiffMember): return patches diff_hp_value = diff_hp.get_value() else: return patches patch_target_ref = f"{game_entity_name}.Live.Health" patch_target_forward_ref = ForwardRef(line, patch_target_ref) # Wrapper wrapper_name = f"Change{game_entity_name}HealthWrapper" wrapper_ref = f"{container_obj_ref}.{wrapper_name}" wrapper_raw_api_object = RawAPIObject( wrapper_ref, wrapper_name, dataset.nyan_api_objects ) wrapper_raw_api_object.add_raw_parent("engine.aux.patch.Patch") if isinstance(line, GenieBuildingLineGroup): # Store building upgrades next to their game entity definition, # not in the Age up techs. wrapper_raw_api_object.set_location( "data/game_entity/generic/%s/" % (name_lookup_dict[head_unit_id][1]) ) wrapper_raw_api_object.set_filename(f"{tech_lookup_dict[tech_id][1]}_upgrade") else: wrapper_raw_api_object.set_location( ForwardRef(converter_group, container_obj_ref) ) # Nyan patch nyan_patch_name = f"Change{game_entity_name}Health" nyan_patch_ref = f"{container_obj_ref}.{wrapper_name}.{nyan_patch_name}" nyan_patch_location = ForwardRef(converter_group, wrapper_ref) nyan_patch_raw_api_object = RawAPIObject( nyan_patch_ref, nyan_patch_name, dataset.nyan_api_objects, nyan_patch_location ) nyan_patch_raw_api_object.add_raw_parent("engine.aux.patch.NyanPatch") nyan_patch_raw_api_object.set_patch_target(patch_target_forward_ref) # HP max value nyan_patch_raw_api_object.add_raw_patch_member( "max_value", diff_hp_value, "engine.aux.attribute.AttributeSetting", MemberOperator.ADD, ) patch_forward_ref = ForwardRef(converter_group, nyan_patch_ref) wrapper_raw_api_object.add_raw_member( "patch", patch_forward_ref, "engine.aux.patch.Patch" ) converter_group.add_raw_api_object(wrapper_raw_api_object) converter_group.add_raw_api_object(nyan_patch_raw_api_object) wrapper_forward_ref = ForwardRef(converter_group, wrapper_ref) patches.append(wrapper_forward_ref) return patches
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def hp_upgrade(converter_group, line, value, operator, team=False): """ Creates a patch for the HP modify effect (ID: 0). :param converter_group: Tech/Civ that gets the patch. :type converter_group: ...dataformat.converter_object.ConverterObjectGroup :param line: Unit/Building line that has the ability. :type line: ...dataformat.converter_object.ConverterObjectGroup :param value: Value used for patching the member. :type value: MemberOperator :param operator: Operator used for patching the member. :type operator: MemberOperator :returns: The forward references for the generated patches. :rtype: list """ head_unit_id = line.get_head_unit_id() dataset = line.data patches = [] obj_id = converter_group.get_id() if isinstance(converter_group, GenieTechEffectBundleGroup): tech_lookup_dict = internal_name_lookups.get_tech_lookups(dataset.game_version) obj_name = tech_lookup_dict[obj_id][0] else: civ_lookup_dict = internal_name_lookups.get_civ_lookups(dataset.game_version) obj_name = civ_lookup_dict[obj_id][0] name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version) game_entity_name = name_lookup_dict[head_unit_id][0] patch_target_ref = f"{game_entity_name}.Live.Health" patch_target_forward_ref = ForwardRef(line, patch_target_ref) # Wrapper wrapper_name = f"Change{game_entity_name}MaxHealthWrapper" wrapper_ref = f"{obj_name}.{wrapper_name}" wrapper_location = ForwardRef(converter_group, obj_name) wrapper_raw_api_object = RawAPIObject( wrapper_ref, wrapper_name, dataset.nyan_api_objects, wrapper_location ) wrapper_raw_api_object.add_raw_parent("engine.aux.patch.Patch") # Nyan patch nyan_patch_name = f"Change{game_entity_name}MaxHealth" nyan_patch_ref = f"{obj_name}.{wrapper_name}.{nyan_patch_name}" nyan_patch_location = ForwardRef(converter_group, wrapper_ref) nyan_patch_raw_api_object = RawAPIObject( nyan_patch_ref, nyan_patch_name, dataset.nyan_api_objects, nyan_patch_location ) nyan_patch_raw_api_object.add_raw_parent("engine.aux.patch.NyanPatch") nyan_patch_raw_api_object.set_patch_target(patch_target_forward_ref) nyan_patch_raw_api_object.add_raw_patch_member( "max_value", value, "engine.aux.attribute.AttributeSetting", operator ) nyan_patch_raw_api_object.add_raw_patch_member( "starting_value", value, "engine.aux.attribute.AttributeSetting", operator ) patch_forward_ref = ForwardRef(converter_group, nyan_patch_ref) wrapper_raw_api_object.add_raw_member( "patch", patch_forward_ref, "engine.aux.patch.Patch" ) if team: wrapper_raw_api_object.add_raw_parent("engine.aux.patch.type.DiplomaticPatch") stances = [ dataset.nyan_api_objects["engine.aux.diplomatic_stance.type.Self"], dataset.pregen_nyan_objects[ "aux.diplomatic_stance.types.Friendly" ].get_nyan_object(), ] wrapper_raw_api_object.add_raw_member( "stances", stances, "engine.aux.patch.type.DiplomaticPatch" ) converter_group.add_raw_api_object(wrapper_raw_api_object) converter_group.add_raw_api_object(nyan_patch_raw_api_object) wrapper_forward_ref = ForwardRef(converter_group, wrapper_ref) patches.append(wrapper_forward_ref) return patches
def hp_upgrade(converter_group, line, value, operator, team=False): """ Creates a patch for the HP modify effect (ID: 0). :param converter_group: Tech/Civ that gets the patch. :type converter_group: ...dataformat.converter_object.ConverterObjectGroup :param line: Unit/Building line that has the ability. :type line: ...dataformat.converter_object.ConverterObjectGroup :param value: Value used for patching the member. :type value: MemberOperator :param operator: Operator used for patching the member. :type operator: MemberOperator :returns: The forward references for the generated patches. :rtype: list """ head_unit_id = line.get_head_unit_id() dataset = line.data patches = [] obj_id = converter_group.get_id() if isinstance(converter_group, GenieTechEffectBundleGroup): tech_lookup_dict = internal_name_lookups.get_tech_lookups(dataset.game_version) obj_name = tech_lookup_dict[obj_id][0] else: civ_lookup_dict = internal_name_lookups.get_civ_lookups(dataset.game_version) obj_name = civ_lookup_dict[obj_id][0] name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version) game_entity_name = name_lookup_dict[head_unit_id][0] patch_target_ref = f"{game_entity_name}.Live.Health" patch_target_forward_ref = ForwardRef(line, patch_target_ref) # Wrapper wrapper_name = f"Change{game_entity_name}MaxHealthWrapper" wrapper_ref = f"{obj_name}.{wrapper_name}" wrapper_location = ForwardRef(converter_group, obj_name) wrapper_raw_api_object = RawAPIObject( wrapper_ref, wrapper_name, dataset.nyan_api_objects, wrapper_location ) wrapper_raw_api_object.add_raw_parent("engine.aux.patch.Patch") # Nyan patch nyan_patch_name = f"Change{game_entity_name}MaxHealth" nyan_patch_ref = f"{obj_name}.{wrapper_name}.{nyan_patch_name}" nyan_patch_location = ForwardRef(converter_group, wrapper_ref) nyan_patch_raw_api_object = RawAPIObject( nyan_patch_ref, nyan_patch_name, dataset.nyan_api_objects, nyan_patch_location ) nyan_patch_raw_api_object.add_raw_parent("engine.aux.patch.NyanPatch") nyan_patch_raw_api_object.set_patch_target(patch_target_forward_ref) nyan_patch_raw_api_object.add_raw_patch_member( "max_value", value, "engine.aux.attribute.AttributeSetting", operator ) patch_forward_ref = ForwardRef(converter_group, nyan_patch_ref) wrapper_raw_api_object.add_raw_member( "patch", patch_forward_ref, "engine.aux.patch.Patch" ) if team: wrapper_raw_api_object.add_raw_parent("engine.aux.patch.type.DiplomaticPatch") stances = [ dataset.nyan_api_objects["engine.aux.diplomatic_stance.type.Self"], dataset.pregen_nyan_objects[ "aux.diplomatic_stance.types.Friendly" ].get_nyan_object(), ] wrapper_raw_api_object.add_raw_member( "stances", stances, "engine.aux.patch.type.DiplomaticPatch" ) converter_group.add_raw_api_object(wrapper_raw_api_object) converter_group.add_raw_api_object(nyan_patch_raw_api_object) wrapper_forward_ref = ForwardRef(converter_group, wrapper_ref) patches.append(wrapper_forward_ref) return patches
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def _get_aoe2_base(cls, gamedata): """ Create the aoe2-base modpack. """ modpack = Modpack("de2_base") mod_def = modpack.get_info() mod_def.set_version("TODO") mod_def.set_uid(2000) mod_def.add_assets_to_load("data/*") AoCModpackSubprocessor.organize_nyan_objects(modpack, gamedata) AoCModpackSubprocessor.organize_media_objects(modpack, gamedata) return modpack
def _get_aoe2_base(cls, gamedata): """ Create the aoe2-base modpack. """ modpack = Modpack("de2-base") mod_def = modpack.get_info() mod_def.set_version("TODO") mod_def.set_uid(2000) mod_def.add_assets_to_load("data/*") AoCModpackSubprocessor.organize_nyan_objects(modpack, gamedata) AoCModpackSubprocessor.organize_media_objects(modpack, gamedata) return modpack
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def _get_aoe1_base(cls, gamedata): """ Create the aoe1-base modpack. """ modpack = Modpack("aoe1_base") mod_def = modpack.get_info() mod_def.set_version("1.0B") mod_def.set_uid(1000) mod_def.add_assets_to_load("data/*") AoCModpackSubprocessor.organize_nyan_objects(modpack, gamedata) AoCModpackSubprocessor.organize_media_objects(modpack, gamedata) return modpack
def _get_aoe1_base(cls, gamedata): """ Create the aoe1-base modpack. """ modpack = Modpack("aoe1-base") mod_def = modpack.get_info() mod_def.set_version("1.0B") mod_def.set_uid(1000) mod_def.add_assets_to_load("data/*") AoCModpackSubprocessor.organize_nyan_objects(modpack, gamedata) AoCModpackSubprocessor.organize_media_objects(modpack, gamedata) return modpack
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def _get_swgb_base(cls, gamedata): """ Create the swgb-base modpack. """ modpack = Modpack("swgb_base") mod_def = modpack.get_info() mod_def.set_version("GOG") mod_def.set_uid(5000) mod_def.add_assets_to_load("data/*") AoCModpackSubprocessor.organize_nyan_objects(modpack, gamedata) AoCModpackSubprocessor.organize_media_objects(modpack, gamedata) return modpack
def _get_swgb_base(cls, gamedata): """ Create the swgb-base modpack. """ modpack = Modpack("swgb-base") mod_def = modpack.get_info() mod_def.set_version("GOG") mod_def.set_uid(5000) mod_def.add_assets_to_load("data/*") AoCModpackSubprocessor.organize_nyan_objects(modpack, gamedata) AoCModpackSubprocessor.organize_media_objects(modpack, gamedata) return modpack
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def expand_from_file(self, nyan_file): """ Expands the tree from a nyan file. :param nyan_file: File with nyan objects. :type nyan_file: .convert.export.formats.nyan_file.NyanFile """ current_node = self.root fqon = nyan_file.get_fqon() node_type = NodeType.FILESYS for node_str in fqon: if current_node.has_child(node_str): # Choose the already created node current_node = current_node.get_child(node_str) else: # Add a new node new_node = Node(node_str, node_type, current_node) current_node.add_child(new_node) current_node = new_node # Process fqons of the contained objects for nyan_object in nyan_file.nyan_objects: self.expand_from_object(nyan_object)
def expand_from_file(self, nyan_file): """ Expands the tree from a nyan file. :param nyan_file: File with nyan objects. :type nyan_file: .convert.export.formats.nyan_file.NyanFile """ # Process fqon of the file current_node = self.root fqon = nyan_file.get_fqon() node_type = NodeType.FILESYS for node_str in fqon: if current_node.has_child(node_str): # Choose the already created node current_node = current_node.get_child(node_str) else: # Add a new node new_node = Node(node_str, node_type, current_node) current_node.add_child(new_node) current_node = new_node # Process fqons of the contained objects for nyan_object in nyan_file.nyan_objects: self.expand_from_object(nyan_object)
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def get_alias_fqon(self, fqon, namespace=None): """ Find the (shortened) fqon by traversing the tree to the fqon node and then going upwards until an alias is found. :param fqon: Object reference for which an alias should be found. :type fqon: tuple :param namespace: Identifier of a namespace. If this is a (nested) object, we check if the fqon is in the namespace before searching for an alias. :type namespace: tuple """ if namespace: current_node = self.root if len(namespace) <= len(fqon): # Check if the fqon is in the namespace by comparing their identifiers for index in range(len(namespace)): current_node = current_node.get_child(namespace[index]) if namespace[index] != fqon[index]: break else: # Check if the namespace node is an object if current_node.node_type in (NodeType.OBJECT, NodeType.NESTED): # The object with the fqon is nested and we don't have to look # up an alias return (fqon[-1],) # Traverse the tree downwards current_node = self.root for part in fqon: current_node = current_node.get_child(part) # Traverse the tree upwards sfqon = [] while current_node.depth > 0: if current_node.alias: sfqon.insert(0, current_node.alias) current_node.mark() break sfqon.insert(0, current_node.name) current_node = current_node.parent if not current_node.alias: print(fqon) return tuple(sfqon)
def get_alias_fqon(self, fqon): """ Find the (shortened) fqon by traversing the tree to the fqon node and then going upwards until a marked node is found. """ # Traverse the tree downwards current_node = self.root for part in fqon: current_node = current_node.get_child(part) # Traverse the tree upwards sfqon = [] while current_node.depth > 0: sfqon.insert(0, current_node.name) if current_node.alias: break current_node = current_node.parent return tuple(sfqon)
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def __init__(self, name, node_type, parent): """ Create a node for an import tree. :param name: Name of the node. :type name: str :param node_type: Type of the node. :type node_type: NodeType :param parent: Parent node of this node. :type parent: Node """ self.name = name self.node_type = node_type self.parent = parent if not self.parent and self.node_type is not NodeType.ROOT: raise Exception("Only node with type ROOT are allowed to have no parent") self.depth = 0 if self.node_type is NodeType.ROOT: self.depth = 0 else: self.depth = self.parent.depth + 1 self.children = {} self.marked = False self.alias = ""
def __init__(self, name, node_type, parent): """ Create a node for an import tree. :param name: Name of the node. :type name: str :param node_type: Type of the node. :type node_type: NodeType :param parent: Parent node of this node. :type parent: Node """ self.name = name self.node_type = node_type self.parent = parent if not self.parent and self.node_type is not NodeType.ROOT: raise Exception("Only node with type ROOT are allowed to have no parent") self.depth = 0 if self.node_type is NodeType.ROOT: self.depth = 0 else: self.depth = self.parent.depth + 1 self.children = {} self.alias = False
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def mark(self): """ Mark this node as an alias node. """ self.marked = True
def mark(self): """ Mark this node as an alias node. """ self.alias = True
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def unmark(self): """ Unmark this node as an alias node. """ self.marked = False
def unmark(self): """ Unmark this node as an alias node. """ self.alias = False
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def _prepare_object_content(self, indent_depth, import_tree=None): """ Returns a string containing the nyan object's content (members, nested objects). Subroutine of dump(). """ output_str = "" empty = True if len(self._inherited_members) > 0: for inherited_member in self._inherited_members: if inherited_member.has_value(): empty = False output_str += "%s%s\n" % ( (indent_depth + 1) * INDENT, inherited_member.dump( indent_depth + 1, import_tree=import_tree, namespace=self.get_fqon(), ), ) if not empty: output_str += "\n" if len(self._members) > 0: empty = False for member in self._members: if self.is_patch(): # Patches do not need the type definition output_str += "%s%s\n" % ( (indent_depth + 1) * INDENT, member.dump_short( indent_depth + 1, import_tree=import_tree, namespace=self.get_fqon(), ), ) else: output_str += "%s%s\n" % ( (indent_depth + 1) * INDENT, member.dump( indent_depth + 1, import_tree=import_tree, namespace=self.get_fqon(), ), ) output_str += "\n" # Nested objects if len(self._nested_objects) > 0: empty = False for nested_object in self._nested_objects: output_str += "%s%s" % ( (indent_depth + 1) * INDENT, nested_object.dump(indent_depth + 1, import_tree=import_tree), ) output_str += "" # Empty objects need a 'pass' line if empty: output_str += f"{(indent_depth + 1) * INDENT}pass\n\n" return output_str
def _prepare_object_content(self, indent_depth, import_tree=None): """ Returns a string containing the nyan object's content (members, nested objects). Subroutine of dump(). """ output_str = "" empty = True if len(self._inherited_members) > 0: for inherited_member in self._inherited_members: if inherited_member.has_value(): empty = False output_str += "%s%s\n" % ( (indent_depth + 1) * INDENT, inherited_member.dump(import_tree=import_tree), ) if not empty: output_str += "\n" if len(self._members) > 0: empty = False for member in self._members: if self.is_patch(): # Patches do not need the type definition output_str += "%s%s\n" % ( (indent_depth + 1) * INDENT, member.dump_short(import_tree=import_tree), ) else: output_str += "%s%s\n" % ( (indent_depth + 1) * INDENT, member.dump(import_tree=import_tree), ) output_str += "\n" # Nested objects if len(self._nested_objects) > 0: empty = False for nested_object in self._nested_objects: output_str += "%s%s" % ( (indent_depth + 1) * INDENT, nested_object.dump(indent_depth + 1, import_tree), ) output_str += "" # Empty objects need a 'pass' line if empty: output_str += f"{(indent_depth + 1) * INDENT}pass\n\n" return output_str
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def _prepare_inheritance_content(self, import_tree=None): """ Returns a string containing the nyan object's inheritance set in the header. Subroutine of dump(). """ output_str = "(" if len(self._parents) > 0: for parent in self._parents: if import_tree: sfqon = ".".join( import_tree.get_alias_fqon( parent.get_fqon(), namespace=self.get_fqon() ) ) else: sfqon = ".".join(parent.get_fqon()) output_str += f"{sfqon}, " output_str = output_str[:-2] output_str += "):\n" return output_str
def _prepare_inheritance_content(self, import_tree=None): """ Returns a string containing the nyan object's inheritance set in the header. Subroutine of dump(). """ output_str = "(" if len(self._parents) > 0: for parent in self._parents: if import_tree: sfqon = ".".join(import_tree.get_alias_fqon(parent.get_fqon())) else: sfqon = ".".join(parent.get_fqon()) output_str += f"{sfqon}, " output_str = output_str[:-2] output_str += "):\n" return output_str
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def dump(self, indent_depth, import_tree=None, namespace=None): """ Returns the nyan string representation of the member. """ output_str = f"{self.name}" type_str = "" if isinstance(self._member_type, NyanObject): if import_tree: sfqon = ".".join( import_tree.get_alias_fqon(self._member_type.get_fqon(), namespace) ) else: sfqon = ".".join(self._member_type.get_fqon()) type_str = sfqon else: type_str = self._member_type.value if self._optional: output_str += f" : optional({type_str})" else: output_str += f" : {type_str}" if self.is_complex(): if isinstance(self._set_type, NyanObject): if import_tree: sfqon = ".".join( import_tree.get_alias_fqon(self._set_type.get_fqon(), namespace) ) else: sfqon = ".".join(self._set_type.get_fqon()) output_str += f"({sfqon})" else: output_str += f"({self._set_type.value})" if self.is_initialized(): output_str += " %s%s %s" % ( "@" * self._override_depth, self._operator.value, self._get_str_representation( indent_depth, import_tree=import_tree, namespace=namespace ), ) return output_str
def dump(self, import_tree=None): """ Returns the nyan string representation of the member. """ output_str = f"{self.name}" type_str = "" if isinstance(self._member_type, NyanObject): if import_tree: sfqon = ".".join(import_tree.get_alias_fqon(self._member_type.get_fqon())) else: sfqon = ".".join(self._member_type.get_fqon()) type_str = sfqon else: type_str = self._member_type.value if self._optional: output_str += f" : optional({type_str})" else: output_str += f" : {type_str}" if self.is_complex(): if isinstance(self._set_type, NyanObject): if import_tree: sfqon = ".".join(import_tree.get_alias_fqon(self._set_type.get_fqon())) else: sfqon = ".".join(self._set_type.get_fqon()) output_str += f"({sfqon})" else: output_str += f"({self._set_type.value})" if self.is_initialized(): output_str += " %s%s %s" % ( "@" * self._override_depth, self._operator.value, self._get_str_representation(import_tree=import_tree), ) return output_str
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def dump_short(self, indent_depth, import_tree=None, namespace=None): """ Returns the nyan string representation of the member, but without the type definition. """ return "%s %s%s %s" % ( self.get_name(), "@" * self._override_depth, self._operator.value, self._get_str_representation( indent_depth, import_tree=import_tree, namespace=namespace ), )
def dump_short(self, import_tree=None): """ Returns the nyan string representation of the member, but without the type definition. """ return "%s %s%s %s" % ( self.get_name(), "@" * self._override_depth, self._operator.value, self._get_str_representation(import_tree=import_tree), )
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def _get_primitive_value_str( self, member_type, value, import_tree=None, namespace=None ): """ Returns the nyan string representation of primitive values. Subroutine of _get_str_representation() """ if member_type in (MemberType.TEXT, MemberType.FILE): return f'"{value}"' elif isinstance(member_type, NyanObject): if import_tree: sfqon = ".".join( import_tree.get_alias_fqon(value.get_fqon(), namespace=namespace) ) else: sfqon = ".".join(value.get_fqon()) return sfqon return f"{value}"
def _get_primitive_value_str(self, member_type, value, import_tree=None): """ Returns the nyan string representation of primitive values. Subroutine of _get_str_representation() """ if member_type is MemberType.FLOAT: return f"{value}f" elif member_type in (MemberType.TEXT, MemberType.FILE): return f'"{value}"' elif isinstance(member_type, NyanObject): if import_tree: sfqon = ".".join(import_tree.get_alias_fqon(value.get_fqon())) else: sfqon = ".".join(value.get_fqon()) return sfqon return f"{value}"
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def _get_str_representation(self, indent_depth, import_tree=None, namespace=None): """ Returns the nyan string representation of the value. """ if not self.is_initialized(): return f"UNINITIALIZED VALUE {self.__repr__()}" if self._optional and self.value is MemberSpecialValue.NYAN_NONE: return MemberSpecialValue.NYAN_NONE.value if self.value is MemberSpecialValue.NYAN_INF: return MemberSpecialValue.NYAN_INF.value if self._member_type in ( MemberType.INT, MemberType.FLOAT, MemberType.TEXT, MemberType.FILE, MemberType.BOOLEAN, ): return self._get_primitive_value_str( self._member_type, self.value, import_tree=import_tree, namespace=namespace ) elif self._member_type in (MemberType.SET, MemberType.ORDEREDSET): return self._get_complex_value_str( indent_depth, self._member_type, self.value, import_tree=import_tree, namespace=namespace, ) elif isinstance(self._member_type, NyanObject): if import_tree: sfqon = ".".join( import_tree.get_alias_fqon(self.value.get_fqon(), namespace) ) else: sfqon = ".".join(self.value.get_fqon()) return sfqon else: raise Exception(f"{self.__repr__()} has no valid type")
def _get_str_representation(self, import_tree=None): """ Returns the nyan string representation of the value. """ if not self.is_initialized(): return f"UNINITIALIZED VALUE {self.__repr__()}" if self._optional and self.value is MemberSpecialValue.NYAN_NONE: return MemberSpecialValue.NYAN_NONE.value if self.value is MemberSpecialValue.NYAN_INF: return MemberSpecialValue.NYAN_INF.value if self._member_type in ( MemberType.INT, MemberType.FLOAT, MemberType.TEXT, MemberType.FILE, MemberType.BOOLEAN, ): return self._get_primitive_value_str( self._member_type, self.value, import_tree=import_tree ) elif self._member_type in (MemberType.SET, MemberType.ORDEREDSET): output_str = "" if self._member_type is MemberType.ORDEREDSET: output_str += "o" output_str += "{" if len(self.value) > 0: for val in self.value: output_str += "%s, " % self._get_primitive_value_str( self._set_type, val, import_tree=import_tree ) return output_str[:-2] + "}" return output_str + "}" elif isinstance(self._member_type, NyanObject): if import_tree: sfqon = ".".join(import_tree.get_alias_fqon(self.value.get_fqon())) else: sfqon = ".".join(self.value.get_fqon()) return sfqon else: raise Exception(f"{self.__repr__()} has no valid type")
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def dump(self, indent_depth, import_tree=None, namespace=None): """ Returns the string representation of the member. """ return self.dump_short(indent_depth, import_tree=import_tree, namespace=namespace)
def dump(self, import_tree=None): """ Returns the string representation of the member. """ return self.dump_short(import_tree=import_tree)
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def dump_short(self, indent_depth, import_tree=None, namespace=None): """ Returns the nyan string representation of the member, but without the type definition. """ return "%s %s%s %s" % ( self.get_name_with_origin(), "@" * self._override_depth, self._operator.value, self._get_str_representation( indent_depth, import_tree=import_tree, namespace=namespace ), )
def dump_short(self, import_tree=None): """ Returns the nyan string representation of the member, but without the type definition. """ return "%s %s%s %s" % ( self.get_name_with_origin(), "@" * self._override_depth, self._operator.value, self._get_str_representation(import_tree=import_tree), )
https://github.com/SFTtech/openage/issues/1355
INFO [py] launching openage v0.4.1-377-g2be30ba76 INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] Y Should we call wine to determine an AOE installation? [Y/n] n Could not find any installation directory automatically. Please enter an AOE2 install path manually. /home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' INFO [py] Game edition detected: INFO [py] * Age of Empires 2: Definitive Edition INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] Starting conversion... INFO [py] Extracting Genie data... INFO [py] Creating API-like objects... INFO [py] Linking API-like objects... INFO [py] Generating auxiliary objects... INFO [py] Creating nyan objects... Traceback (most recent call last): File "/usr/bin/openage", line 15, in <module> main() File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main used_asset_path = convert_assets( File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets for current_item in convert(args): File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert yield from convert_metadata(args) File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata modpacks = args.converter.convert(gamespec, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert modpacks = cls._post_processor(dataset) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor DE2NyanSubprocessor.convert(full_data_set) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert cls._process_game_entities(gamedata) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities cls.tech_group_to_tech(tech_group) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech patches.extend(DE2TechSubprocessor.get_patches(tech_group)) File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches patches.extend(cls.resource_modify_effect(converter_group, File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] KeyError: 208
KeyError
def convert_assets(assets, args, srcdir=None, prev_source_dir_path=None): """ Perform asset conversion. Requires original assets and stores them in usable and free formats. assets must be a filesystem-like object pointing at the game's asset dir. srcdir must be None, or point at some source directory. If gen_extra_files is True, some more files, mostly for debugging purposes, are created. This method prepares srcdir and targetdir to allow a pleasant, unified conversion experience, then passes them to .driver.convert(). """ # acquire conversion source directory if srcdir is None: srcdir = acquire_conversion_source_dir(prev_source_dir_path) converted_path = assets / "converted" converted_path.mkdirs() targetdir = DirectoryCreator(converted_path).root # Set compression level for media output if it was not set if "compression_level" not in vars(args): args.compression_level = 1 # Set verbosity for debug output if "debug_info" not in vars(args): if args.devmode: args.debug_info = 3 else: args.debug_info = 0 # add a dir for debug info debug_log_path = ( converted_path / "debug" / datetime.now().strftime("%Y-%m-%d-%H-%M-%S") ) debugdir = DirectoryCreator(debug_log_path).root args.debugdir = AccessSynchronizer(debugdir).root # Create CLI args info debug_cli_args(args.debugdir, args.debug_info, args) # Initialize game versions data auxiliary_files_dir = args.cfg_dir / "converter" / "games" args.avail_game_eds, args.avail_game_exps = create_version_objects( auxiliary_files_dir ) # Acquire game version info args.game_version = get_game_version( srcdir, args.avail_game_eds, args.avail_game_exps ) debug_game_version(args.debugdir, args.debug_info, args) # Mount assets into conversion folder data_dir = mount_asset_dirs(srcdir, args.game_version) if not data_dir: return None # make srcdir and targetdir safe for threaded conversion args.srcdir = AccessSynchronizer(data_dir).root args.targetdir = AccessSynchronizer(targetdir).root # Create mountpoint info debug_mounts(args.debugdir, args.debug_info, args) def flag(name): """ Convenience function for accessing boolean flags in args. Flags default to False if they don't exist. """ return getattr(args, name, False) args.flag = flag # import here so codegen.py doesn't depend on it. from .tool.driver import convert converted_count = 0 total_count = None for current_item in convert(args): if isinstance(current_item, int): # convert is informing us about the estimated number of remaining # items. total_count = current_item + converted_count continue # TODO a GUI would be nice here. if total_count is None: info("[%s] %s", converted_count, current_item) else: info("[%s] %s", format_progress(converted_count, total_count), current_item) converted_count += 1 # clean args del args.srcdir del args.targetdir return data_dir.resolve_native_path()
def convert_assets(assets, args, srcdir=None, prev_source_dir_path=None): """ Perform asset conversion. Requires original assets and stores them in usable and free formats. assets must be a filesystem-like object pointing at the game's asset dir. srcdir must be None, or point at some source directory. If gen_extra_files is True, some more files, mostly for debugging purposes, are created. This method prepares srcdir and targetdir to allow a pleasant, unified conversion experience, then passes them to .driver.convert(). """ # acquire conversion source directory if srcdir is None: srcdir = acquire_conversion_source_dir(prev_source_dir_path) converted_path = assets / "converted" converted_path.mkdirs() targetdir = DirectoryCreator(converted_path).root # add a dir for debug info debug_log_path = ( converted_path / "debug" / datetime.now().strftime("%Y-%m-%d-%H-%M-%S") ) debugdir = DirectoryCreator(debug_log_path).root args.debugdir = AccessSynchronizer(debugdir).root # Create CLI args info debug_cli_args(args.debugdir, args.debug_info, args) # Initialize game versions data auxiliary_files_dir = args.cfg_dir / "converter" / "games" args.avail_game_eds, args.avail_game_exps = create_version_objects( auxiliary_files_dir ) # Acquire game version info args.game_version = get_game_version( srcdir, args.avail_game_eds, args.avail_game_exps ) debug_game_version(args.debugdir, args.debug_info, args) # Mount assets into conversion folder data_dir = mount_asset_dirs(srcdir, args.game_version) if not data_dir: return None # make srcdir and targetdir safe for threaded conversion args.srcdir = AccessSynchronizer(data_dir).root args.targetdir = AccessSynchronizer(targetdir).root # Create mountpoint info debug_mounts(args.debugdir, args.debug_info, args) def flag(name): """ Convenience function for accessing boolean flags in args. Flags default to False if they don't exist. """ return getattr(args, name, False) args.flag = flag # import here so codegen.py doesn't depend on it. from .tool.driver import convert converted_count = 0 total_count = None for current_item in convert(args): if isinstance(current_item, int): # convert is informing us about the estimated number of remaining # items. total_count = current_item + converted_count continue # TODO a GUI would be nice here. if total_count is None: info("[%s] %s", converted_count, current_item) else: info("[%s] %s", format_progress(converted_count, total_count), current_item) converted_count += 1 # clean args del args.srcdir del args.targetdir return data_dir.resolve_native_path()
https://github.com/SFTtech/openage/issues/1350
INFO [py] launching openage v0.4.1-371-g0c6e704b INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] y Traceback (most recent call last): File "/app/bin/openage", line 15, in <module> main() File "/app/lib/python3.8/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/app/lib/python3.8/site-packages/openage/game/main.py", line 68, in main used_asset_path = convert_assets(root["assets"], root["cfg"], args, File "/app/lib/python3.8/site-packages/openage/convert/main.py", line 52, in convert_assets debug_cli_args(args.debugdir, args.debug_info, args) AttributeError: 'UnionPath' object has no attribute 'debug_info'
AttributeError
def main(args, error): """CLI entry point""" del error # unused # initialize libopenage from ..cppinterface.setup import setup setup(args) # conversion source if args.source_dir is not None: srcdir = CaseIgnoringDirectory(args.source_dir).root else: srcdir = None # mount the config folder at "cfg/" from ..cvar.location import get_config_path from ..util.fslike.union import Union root = Union().root root["cfg"].mount(get_config_path()) args.cfg_dir = root["cfg"] if args.interactive: interactive_browser(root["cfg"], srcdir) return 0 # conversion target from ..assets import get_asset_path outdir = get_asset_path(args.output_dir) if args.force or wanna_convert() or conversion_required(outdir, args): if not convert_assets(outdir, args, srcdir): return 1 else: print("assets are up to date; no conversion is required.") print("override with --force.") return 0
def main(args, error): """CLI entry point""" del error # unused # initialize libopenage from ..cppinterface.setup import setup setup(args) # conversion source if args.source_dir is not None: srcdir = CaseIgnoringDirectory(args.source_dir).root else: srcdir = None # Set verbosity for debug output if not args.debug_info: if args.devmode: args.debug_info = 3 else: args.debug_info = 0 # mount the config folder at "cfg/" from ..cvar.location import get_config_path from ..util.fslike.union import Union root = Union().root root["cfg"].mount(get_config_path()) args.cfg_dir = root["cfg"] if args.interactive: interactive_browser(root["cfg"], srcdir) return 0 # conversion target from ..assets import get_asset_path outdir = get_asset_path(args.output_dir) if args.force or wanna_convert() or conversion_required(outdir, args): if not convert_assets(outdir, args, srcdir): return 1 else: print("assets are up to date; no conversion is required.") print("override with --force.") return 0
https://github.com/SFTtech/openage/issues/1350
INFO [py] launching openage v0.4.1-371-g0c6e704b INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] y Traceback (most recent call last): File "/app/bin/openage", line 15, in <module> main() File "/app/lib/python3.8/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/app/lib/python3.8/site-packages/openage/game/main.py", line 68, in main used_asset_path = convert_assets(root["assets"], root["cfg"], args, File "/app/lib/python3.8/site-packages/openage/convert/main.py", line 52, in convert_assets debug_cli_args(args.debugdir, args.debug_info, args) AttributeError: 'UnionPath' object has no attribute 'debug_info'
AttributeError
def main(args, error): """ Makes sure that the assets have been converted, and jumps into the C++ main method. """ del error # unused # we have to import stuff inside the function # as it depends on generated/compiled code from .main_cpp import run_game from .. import config from ..assets import get_asset_path from ..convert.main import conversion_required, convert_assets from ..cppinterface.setup import setup as cpp_interface_setup from ..cvar.location import get_config_path from ..util.fslike.union import Union # initialize libopenage cpp_interface_setup(args) info("launching openage %s", config.VERSION) info("compiled by %s", config.COMPILER) if config.DEVMODE: info("running in DEVMODE") # create virtual file system for data paths root = Union().root # mount the assets folder union at "assets/" root["assets"].mount(get_asset_path(args.asset_dir)) # mount the config folder at "cfg/" root["cfg"].mount(get_config_path(args.cfg_dir)) args.cfg_dir = root["cfg"] # ensure that the assets have been converted if wanna_convert() or conversion_required(root["assets"], args): # try to get previously used source dir asset_location_path = root["cfg"] / "asset_location" try: with asset_location_path.open("r") as file_obj: prev_source_dir_path = file_obj.read().strip() except FileNotFoundError: prev_source_dir_path = None used_asset_path = convert_assets( root["assets"], args, prev_source_dir_path=prev_source_dir_path ) if used_asset_path: # Remember the asset location with asset_location_path.open("wb") as file_obj: file_obj.write(used_asset_path) else: err("game asset conversion failed") return 1 # Exit here with an explanation because the converted assets are incompatible! # Remove this when the gamestate works again info("Generated nyan assets are not yet compatible to the engine.") info( "Please revert to release v0.4.1 if you want to test the previous working gamestate." ) info("Exiting...") import sys sys.exit() # start the game, continue in main_cpp.pyx! return run_game(args, root)
def main(args, error): """ Makes sure that the assets have been converted, and jumps into the C++ main method. """ del error # unused # we have to import stuff inside the function # as it depends on generated/compiled code from .main_cpp import run_game from .. import config from ..assets import get_asset_path from ..convert.main import conversion_required, convert_assets from ..cppinterface.setup import setup as cpp_interface_setup from ..cvar.location import get_config_path from ..util.fslike.union import Union # initialize libopenage cpp_interface_setup(args) info("launching openage %s", config.VERSION) info("compiled by %s", config.COMPILER) if config.DEVMODE: info("running in DEVMODE") # create virtual file system for data paths root = Union().root # mount the assets folder union at "assets/" root["assets"].mount(get_asset_path(args.asset_dir)) # mount the config folder at "cfg/" root["cfg"].mount(get_config_path(args.cfg_dir)) # ensure that the assets have been converted if wanna_convert() or conversion_required(root["assets"], args): # try to get previously used source dir asset_location_path = root["cfg"] / "asset_location" try: with asset_location_path.open("r") as file_obj: prev_source_dir_path = file_obj.read().strip() except FileNotFoundError: prev_source_dir_path = None used_asset_path = convert_assets( root["assets"], root["cfg"], args, prev_source_dir_path=prev_source_dir_path ) if used_asset_path: # Remember the asset location with asset_location_path.open("wb") as file_obj: file_obj.write(used_asset_path) else: err("game asset conversion failed") return 1 # start the game, continue in main_cpp.pyx! return run_game(args, root)
https://github.com/SFTtech/openage/issues/1350
INFO [py] launching openage v0.4.1-371-g0c6e704b INFO [py] compiled by GNU 10.2.0 Do you want to convert assets? [Y/n] y Traceback (most recent call last): File "/app/bin/openage", line 15, in <module> main() File "/app/lib/python3.8/site-packages/openage/__main__.py", line 132, in main return args.entrypoint(args, cli.error) File "/app/lib/python3.8/site-packages/openage/game/main.py", line 68, in main used_asset_path = convert_assets(root["assets"], root["cfg"], args, File "/app/lib/python3.8/site-packages/openage/convert/main.py", line 52, in convert_assets debug_cli_args(args.debugdir, args.debug_info, args) AttributeError: 'UnionPath' object has no attribute 'debug_info'
AttributeError
def main(): """CLI entry point""" args = parse_args() cppname = "libopenage" cppdir = Path(cppname).absolute() out_cppdir = Path(args.output_dir) / cppname if args.verbose: hdr_count = len(args.all_files) plural = "s" if hdr_count > 1 else "" print( "extracting pxd information from {} header{}...".format(hdr_count, plural) ) for filename in args.all_files: filename = Path(filename).resolve() if cppdir not in filename.parents: print("pxdgen source file is not in " + cppdir + ": " + filename) sys.exit(1) # join out_cppdir with relative path from cppdir pxdfile_relpath = filename.with_suffix(".pxd").relative_to(cppdir) pxdfile = out_cppdir / pxdfile_relpath if args.verbose: print("creating '{}' for '{}':".format(pxdfile, filename)) generator = PXDGenerator(filename) result = generator.generate( pxdfile, ignore_timestamps=args.ignore_timestamps, print_warnings=True ) if args.verbose and not result: print("nothing done.") # create empty __init__.py in all parent directories. # Cython requires this; else it won't find the .pxd files. for dirname in pxdfile_relpath.parents: template = out_cppdir / dirname / "__init__" for extension in ("py", "pxd"): initfile = template.with_suffix("." + extension) if not initfile.exists(): print( "\x1b[36mpxdgen: create package index %s\x1b[0m" % (initfile.relative_to(args.output_dir)) ) initfile.touch()
def main(): """CLI entry point""" args = parse_args() cppname = "libopenage" cppdir = Path(cppname).absolute() out_cppdir = Path(args.output_dir) / cppname if args.verbose: hdr_count = len(args.all_files) plural = "s" if hdr_count > 1 else "" print( "extracting pxd information from {} header{}...".format(hdr_count, plural) ) for filename in args.all_files: filename = Path(filename).resolve() if cppdir not in filename.parents: print("pxdgen source file is not in " + cppdir + ": " + filename) sys.exit(1) # join out_cppdir with relative path from cppdir pxdfile_relpath = filename.with_suffix(".pxd").relative_to(cppdir) pxdfile = out_cppdir / pxdfile_relpath if args.verbose: print("creating '{}' for '{}':".format(pxdfile, filename)) generator = PXDGenerator(filename) result = generator.generate( pxdfile, ignore_timestamps=args.ignore_timestamps, print_warnings=True ) if args.verbose and not result: print("nothing done.") # create empty __init__.py in all parent directories. # Cython requires this; else it won't find the .pxd files. for dirname in pxdfile_relpath.parents: template = out_cppdir / dirname / "__init__" for extension in ("py", "pxd"): initfile = template.with_suffix("." + extension) if not initfile.exists(): print( "\x1b[36mpxdgen: create package index %s\x1b[0m" % (initfile.relative_to(CWD)) ) initfile.touch()
https://github.com/SFTtech/openage/issues/1093
% make pxdgen VERBOSE=1 /usr/bin/cmake -S/tmp/portage/games-strategy/openage-9999/work/openage-9999 -B/tmp/portage/games-strategy/openage-9999/work/openage-9999_build --check-build-system CMakeFiles/Makefile.cmake 0 make -f CMakeFiles/Makefile2 pxdgen make[1]: Entering directory '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build' /usr/bin/cmake -S/tmp/portage/games-strategy/openage-9999/work/openage-9999 -B/tmp/portage/games-strategy/openage-9999/work/openage-9999_build --check-build-system CMakeFiles/Makefile.cmake 0 /usr/bin/cmake -E cmake_progress_start /tmp/portage/games-strategy/openage-9999/work/openage-9999_build/CMakeFiles 1 make -f CMakeFiles/Makefile2 CMakeFiles/pxdgen.dir/all make[2]: Entering directory '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build' make -f CMakeFiles/pxdgen.dir/build.make CMakeFiles/pxdgen.dir/depend make[3]: Entering directory '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build' cd /tmp/portage/games-strategy/openage-9999/work/openage-9999_build &amp;&amp; /usr/bin/cmake -E cmake_depends "Unix Makefiles" /tmp/portage/games-strategy/openage-9999/work/openage-9999 /tmp/portage/games-strategy/openage-9999/work/openage-9999 /tmp/portage/games-strategy/openage-9999/work/openage-9999_build /tmp/portage/games-strategy/openage-9999/work/openage-9999_build /tmp/portage/games-strategy/openage-9999/work/openage-9999_build/CMakeFiles/pxdgen.dir/DependInfo.cmake --color= make[3]: Leaving directory '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build' make -f CMakeFiles/pxdgen.dir/build.make CMakeFiles/pxdgen.dir/build make[3]: Entering directory '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build' [100%] pxdgen: generating .pxd files from headers cd /tmp/portage/games-strategy/openage-9999/work/openage-9999 &amp;&amp; /usr/bin/python3.6 -m buildsystem.pxdgen --file-list /tmp/portage/games-strategy/openage-9999/work/openage-9999_build/py/pxdgen_sources --output-dir /tmp/portage/games-strategy/openage-9999/work/openage-9999_build Traceback (most recent call last): File "/usr/lib64/python3.6/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/usr/lib64/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/tmp/portage/games-strategy/openage-9999/work/openage-9999/buildsystem/pxdgen.py", line 479, in <module> main() File "/tmp/portage/games-strategy/openage-9999/work/openage-9999/buildsystem/pxdgen.py", line 473, in main initfile.relative_to(CWD))) File "/usr/lib64/python3.6/pathlib.py", line 874, in relative_to .format(str(self), str(formatted))) ValueError: '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build/libopenage/__init__.py' does not start with '/tmp/portage/games-strategy/openage-9999/work/openage-9999' make[3]: *** [CMakeFiles/pxdgen.dir/build.make:94: py/pxdgen_timefile] Error 1 make[3]: Leaving directory '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build' make[2]: *** [CMakeFiles/Makefile2:1198: CMakeFiles/pxdgen.dir/all] Error 2 make[2]: Leaving directory '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build' make[1]: *** [CMakeFiles/Makefile2:1209: CMakeFiles/pxdgen.dir/rule] Error 2 make[1]: Leaving directory '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build' make: *** [Makefile:652: pxdgen] Error 2
ValueError
def main(argv=None): """Top-level argparsing; invokes subparser for all submodules.""" cli = argparse.ArgumentParser( "openage", description=("free age of empires II engine clone") ) cli.add_argument( "--version", "-V", nargs=0, action=PrintVersion, help="print version info and exit", ) # shared arguments for all subcommands global_cli = argparse.ArgumentParser(add_help=False) global_cli.add_argument( "--verbose", "-v", action="count", default=ENV_VERBOSITY, help="increase verbosity", ) global_cli.add_argument( "--quiet", "-q", action="count", default=0, help="decrease verbosity" ) global_cli.add_argument( "--devmode", action="store_true", help="force-enable development mode" ) global_cli.add_argument( "--no-devmode", action="store_true", help="force-disable devlopment mode" ) global_cli.add_argument( "--trap-exceptions", action="store_true", help=( "upon throwing an exception a debug break is " "triggered. this will crash openage if no " "debugger is present" ), ) # shared directory arguments for most subcommands cfg_cli = argparse.ArgumentParser(add_help=False) cfg_cli.add_argument( "--asset-dir", help="Use this as an additional asset directory." ) cfg_cli.add_argument( "--cfg-dir", help="Use this as an additional config directory." ) subparsers = cli.add_subparsers(dest="subcommand") # enable reimports for "init_subparser" # pylint: disable=reimported from .game.main import init_subparser game_cli = subparsers.add_parser("game", parents=[global_cli, cfg_cli]) init_subparser(game_cli) from .testing.main import init_subparser init_subparser(subparsers.add_parser("test", parents=[global_cli, cfg_cli])) from .convert.main import init_subparser init_subparser(subparsers.add_parser("convert", parents=[global_cli])) from .convert.singlefile import init_subparser init_subparser(subparsers.add_parser("convert-file", parents=[global_cli])) from .codegen.main import init_subparser init_subparser(subparsers.add_parser("codegen", parents=[global_cli])) args = cli.parse_args(argv) if not args.subcommand: # the user didn't specify a subcommand. default to 'game'. args = game_cli.parse_args(argv) # process the shared args set_loglevel(verbosity_to_level(args.verbose - args.quiet)) if args.no_devmode and args.devmode: cli.error("can't force enable and disable devmode at the same time") try: from . import config if args.no_devmode: config.DEVMODE = False if args.devmode: config.DEVMODE = True except ImportError: if args.no_devmode or args.devmode: print("code was not yet generated, ignoring devmode activation request") if "asset_dir" in args and args.asset_dir: if not os.path.exists(args.asset_dir): cli.error("asset directory does not exist: " + args.asset_dir) # call the entry point for the subcommand. return args.entrypoint(args, cli.error)
def main(argv=None): """Top-level argparsing; invokes subparser for all submodules.""" cli = argparse.ArgumentParser( "openage", description=("free age of empires II engine clone") ) cli.add_argument( "--version", "-V", nargs=0, action=PrintVersion, help="print version info and exit", ) # shared arguments for all subcommands global_cli = argparse.ArgumentParser(add_help=False) global_cli.add_argument( "--verbose", "-v", action="count", default=ENV_VERBOSITY, help="increase verbosity", ) global_cli.add_argument( "--quiet", "-q", action="count", default=0, help="decrease verbosity" ) global_cli.add_argument( "--devmode", action="store_true", help="force-enable development mode" ) global_cli.add_argument( "--no-devmode", action="store_true", help="force-disable devlopment mode" ) global_cli.add_argument( "--trap-exceptions", action="store_true", help=( "upon throwing an exception a debug break is " "triggered. this will crash openage if no " "debugger is present" ), ) # shared directory arguments for most subcommands cfg_cli = argparse.ArgumentParser(add_help=False) cfg_cli.add_argument( "--asset-dir", help="Use this as an additional asset directory." ) cfg_cli.add_argument( "--cfg-dir", help="Use this as an additional config directory." ) subparsers = cli.add_subparsers(dest="subcommand") # enable reimports for "init_subparser" # pylint: disable=reimported from .game.main import init_subparser game_cli = subparsers.add_parser("game", parents=[global_cli, cfg_cli]) init_subparser(game_cli) from .testing.main import init_subparser init_subparser(subparsers.add_parser("test", parents=[global_cli, cfg_cli])) from .convert.main import init_subparser init_subparser(subparsers.add_parser("convert", parents=[global_cli, cfg_cli])) from .convert.singlefile import init_subparser init_subparser(subparsers.add_parser("convert-file", parents=[global_cli, cfg_cli])) from .codegen.main import init_subparser init_subparser(subparsers.add_parser("codegen", parents=[global_cli])) args = cli.parse_args(argv) if not args.subcommand: # the user didn't specify a subcommand. default to 'game'. args = game_cli.parse_args(argv) # process the shared args set_loglevel(verbosity_to_level(args.verbose - args.quiet)) if args.no_devmode and args.devmode: cli.error("can't force enable and disable devmode at the same time") try: from . import config if args.no_devmode: config.DEVMODE = False if args.devmode: config.DEVMODE = True except ImportError: if args.no_devmode or args.devmode: print("code was not yet generated, ignoring devmode activation request") if "asset_dir" in args and args.asset_dir: if not os.path.exists(args.asset_dir): cli.error("directory does not exist: " + args.asset_dir) # call the entry point for the subcommand. return args.entrypoint(args, cli.error)
https://github.com/SFTtech/openage/issues/853
dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... INFO parsing slp image... INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... INFO parsing palette data... INFO packing texture... Traceback (most recent call last): File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/dev/openage/openage/__main__.py", line 128, in <module> exit(main()) File "/home/dev/openage/openage/__main__.py", line 121, in main return args.entrypoint(args, cli.error) File "/home/dev/openage/openage/convert/singlefile.py", line 72, in main tex.save(Directory(path).root, filename) File "/home/dev/openage/openage/convert/texture.py", line 170, in save raise ValueError("Texture must be saved as name.png. got: %s" % filename) ValueError: Texture must be saved as name.png. got: test
ValueError
def get_asset_path(custom_asset_dir=None): """ Returns a Path object for the game assets. `custom_asset_dir` can a custom asset directory, which is mounted at the top of the union filesystem (i.e. has highest priority). This function is used by the both the conversion process and the game startup. The conversion uses it for its output, the game as its data source(s). """ # if we're in devmode, use only the in-repo asset folder if not custom_asset_dir and config.DEVMODE: return Directory(os.path.join(config.BUILD_SRC_DIR, "assets")).root # else, mount the possible locations in an union: # overlay the global dir and the user dir. result = Union().root # the cmake-determined folder for storing assets global_data = Path(config.GLOBAL_ASSET_DIR) if global_data.is_dir(): result.mount(WriteBlocker(Directory(global_data).root).root) # user-data directory as provided by environment variables # and platform standards # we always create this! home_data = default_dirs.get_dir("data_home") / "openage" result.mount(Directory(home_data, create_if_missing=True).root / "assets") # the program argument overrides it all if custom_asset_dir: result.mount(Directory(custom_asset_dir).root) return result
def get_asset_path(args): """ Returns a Path object for the game assets. args are the arguments, as provided by the CLI's ArgumentParser. """ # if we're in devmode, use only the build source asset folder if not args.asset_dir and config.DEVMODE: return Directory(os.path.join(config.BUILD_SRC_DIR, "assets")).root # else, mount the possible locations in an union: # overlay the global dir and the user dir. result = Union().root # the cmake-determined folder for storing assets global_data = Path(config.GLOBAL_ASSET_DIR) if global_data.is_dir(): result.mount(WriteBlocker(Directory(global_data).root).root) # user-data directory as provided by environment variables # and platform standards # we always create this! home_data = default_dirs.get_dir("data_home") / "openage" result.mount(Directory(home_data, create_if_missing=True).root / "assets") # the program argument overrides it all if args.asset_dir: result.mount(Directory(args.asset_dir).root) return result
https://github.com/SFTtech/openage/issues/853
dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... INFO parsing slp image... INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... INFO parsing palette data... INFO packing texture... Traceback (most recent call last): File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/dev/openage/openage/__main__.py", line 128, in <module> exit(main()) File "/home/dev/openage/openage/__main__.py", line 121, in main return args.entrypoint(args, cli.error) File "/home/dev/openage/openage/convert/singlefile.py", line 72, in main tex.save(Directory(path).root, filename) File "/home/dev/openage/openage/convert/texture.py", line 170, in save raise ValueError("Texture must be saved as name.png. got: %s" % filename) ValueError: Texture must be saved as name.png. got: test
ValueError
def interactive_browser(srcdir=None): """ launch an interactive view for browsing the original archives. """ info("launching interactive data browser...") # the variables are actually used, in the interactive prompt. # pylint: disable=unused-variable data, game_versions = mount_input(srcdir) if not data: warn("cannot launch browser as no valid input assets were found.") return def save(path, target): """ save a path to a custom target """ with path.open("rb") as infile: with open(target, "rb") as outfile: outfile.write(infile.read()) def save_slp(path, target, palette=None): """ save a slp as png. """ from .texture import Texture from .slp import SLP from .driver import get_palette if not palette: palette = get_palette(data) with path.open("rb") as slpfile: tex = Texture(SLP(slpfile.read()), palette) out_path, filename = os.path.split(target) tex.save(Directory(out_path).root, filename) import code from pprint import pprint import rlcompleter completer = rlcompleter.Completer(locals()) readline.parse_and_bind("tab: complete") readline.parse_and_bind("set show-all-if-ambiguous on") readline.set_completer(completer.complete) code.interact( banner=( "\nuse `pprint` for beautiful output!\n" "you can access stuff by the `data` variable!\n" "`data` is an openage.util.fslike.path.Path!\n\n" "* version detection: pprint(game_versions)\n" "* list contents: pprint(list(data['graphics'].list()))\n" "* dump data: save(data['file/path'], '/tmp/outputfile')\n" "* save a slp as png: save_slp(data['dir/123.slp'], '/tmp/pic.png')\n" ), local=locals(), )
def interactive_browser(srcdir=None): """ launch an interactive view for browsing the original archives. """ info("launching interactive data browser...") # the variable is actually used, in the interactive prompt. # pylint: disable=unused-variable data, game_versions = mount_input(srcdir) if not data: warn("cannot launch browser as no valid input assets were found.") return def save(path, target): """ save a path to a custom target """ with path.open("rb") as infile: with open(target, "rb") as outfile: outfile.write(infile.read()) def save_slp(path, target, palette=None): """ save a slp as png. """ from .texture import Texture from .slp import SLP from .driver import get_palette if not palette: palette = get_palette(data, game_versions) with path.open("rb") as slpfile: tex = Texture(SLP(slpfile.read()), palette) out_path, filename = os.path.split(target) tex.save(Directory(out_path).root, filename) import code from pprint import pprint import rlcompleter completer = rlcompleter.Completer(locals()) readline.parse_and_bind("tab: complete") readline.parse_and_bind("set show-all-if-ambiguous on") readline.set_completer(completer.complete) code.interact( banner=( "\nuse `pprint` for beautiful output!\n" "you can access stuff by the `data` variable!\n" "`data` is an openage.util.fslike.path.Path!\n" "* list contents: `pprint(list(data['graphics'].list()))`\n" "* dump data: `save(data['file/path'], '/tmp/outputfile')`.\n" "* save a slp as png: `save_slp(data['dir/123.slp'], '/tmp/pic.png')`.\n" ), local=locals(), )
https://github.com/SFTtech/openage/issues/853
dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... INFO parsing slp image... INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... INFO parsing palette data... INFO packing texture... Traceback (most recent call last): File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/dev/openage/openage/__main__.py", line 128, in <module> exit(main()) File "/home/dev/openage/openage/__main__.py", line 121, in main return args.entrypoint(args, cli.error) File "/home/dev/openage/openage/convert/singlefile.py", line 72, in main tex.save(Directory(path).root, filename) File "/home/dev/openage/openage/convert/texture.py", line 170, in save raise ValueError("Texture must be saved as name.png. got: %s" % filename) ValueError: Texture must be saved as name.png. got: test
ValueError
def save_slp(path, target, palette=None): """ save a slp as png. """ from .texture import Texture from .slp import SLP from .driver import get_palette if not palette: palette = get_palette(data) with path.open("rb") as slpfile: tex = Texture(SLP(slpfile.read()), palette) out_path, filename = os.path.split(target) tex.save(Directory(out_path).root, filename)
def save_slp(path, target, palette=None): """ save a slp as png. """ from .texture import Texture from .slp import SLP from .driver import get_palette if not palette: palette = get_palette(data, game_versions) with path.open("rb") as slpfile: tex = Texture(SLP(slpfile.read()), palette) out_path, filename = os.path.split(target) tex.save(Directory(out_path).root, filename)
https://github.com/SFTtech/openage/issues/853
dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... INFO parsing slp image... INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... INFO parsing palette data... INFO packing texture... Traceback (most recent call last): File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/dev/openage/openage/__main__.py", line 128, in <module> exit(main()) File "/home/dev/openage/openage/__main__.py", line 121, in main return args.entrypoint(args, cli.error) File "/home/dev/openage/openage/convert/singlefile.py", line 72, in main tex.save(Directory(path).root, filename) File "/home/dev/openage/openage/convert/texture.py", line 170, in save raise ValueError("Texture must be saved as name.png. got: %s" % filename) ValueError: Texture must be saved as name.png. got: test
ValueError
def init_subparser(cli): """Initializes the parser for convert-specific args.""" cli.set_defaults(entrypoint=main) cli.add_argument("--source-dir", default=None, help="source data directory") cli.add_argument( "--output-dir", default=None, help="destination data output directory" ) cli.add_argument( "--force", action="store_true", help="force conversion, even if up-to-date assets already exist.", ) cli.add_argument( "--gen-extra-files", action="store_true", help="generate some extra files, useful for debugging the converter.", ) cli.add_argument( "--no-media", action="store_true", help="do not convert any media files (slp, wav, ...)", ) cli.add_argument( "--no-metadata", action="store_true", help=( "do not store any metadata (except for those associated with media files)" ), ) cli.add_argument( "--no-sounds", action="store_true", help="do not convert any sound files" ) cli.add_argument( "--no-graphics", action="store_true", help="do not convert game graphics" ) cli.add_argument( "--no-interface", action="store_true", help="do not convert interface graphics" ) cli.add_argument( "--no-scripts", action="store_true", help="do not convert scripts (AI and Random Maps)", ) cli.add_argument( "--no-pickle-cache", action="store_true", help="don't use a pickle file to skip the dat file reading.", ) cli.add_argument("--jobs", "-j", type=int, default=None) cli.add_argument( "--interactive", "-i", action="store_true", help="browse the files interactively", ) cli.add_argument( "--id", type=int, default=None, help="only convert files with this id (used for debugging..)", )
def init_subparser(cli): """Initializes the parser for convert-specific args.""" cli.set_defaults(entrypoint=main) cli.add_argument("--source-dir", default=None, help="source data directory") cli.add_argument( "--force", action="store_true", help="force conversion, even if up-to-date assets already exist.", ) cli.add_argument( "--gen-extra-files", action="store_true", help="generate some extra files, useful for debugging the converter.", ) cli.add_argument( "--no-media", action="store_true", help="do not convert any media files (slp, wav, ...)", ) cli.add_argument( "--no-metadata", action="store_true", help=( "do not store any metadata (except for those associated with media files)" ), ) cli.add_argument( "--no-sounds", action="store_true", help="do not convert any sound files" ) cli.add_argument( "--no-graphics", action="store_true", help="do not convert game graphics" ) cli.add_argument( "--no-interface", action="store_true", help="do not convert interface graphics" ) cli.add_argument( "--no-scripts", action="store_true", help="do not convert scripts (AI and Random Maps)", ) cli.add_argument( "--no-pickle-cache", action="store_true", help="don't use a pickle file to skip the dat file reading.", ) cli.add_argument("--jobs", "-j", type=int, default=None) cli.add_argument( "--interactive", "-i", action="store_true", help="browse the files interactively", ) cli.add_argument( "--id", type=int, default=None, help="only convert files with this id (used for debugging..)", )
https://github.com/SFTtech/openage/issues/853
dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... INFO parsing slp image... INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... INFO parsing palette data... INFO packing texture... Traceback (most recent call last): File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/dev/openage/openage/__main__.py", line 128, in <module> exit(main()) File "/home/dev/openage/openage/__main__.py", line 121, in main return args.entrypoint(args, cli.error) File "/home/dev/openage/openage/convert/singlefile.py", line 72, in main tex.save(Directory(path).root, filename) File "/home/dev/openage/openage/convert/texture.py", line 170, in save raise ValueError("Texture must be saved as name.png. got: %s" % filename) ValueError: Texture must be saved as name.png. got: test
ValueError
def main(args, error): """CLI entry point""" del error # unused # initialize libopenage from ..cppinterface.setup import setup setup(args) # conversion source if args.source_dir is not None: srcdir = CaseIgnoringDirectory(args.source_dir).root else: srcdir = None if args.interactive: interactive_browser(srcdir) return 0 # conversion target from ..assets import get_asset_path outdir = get_asset_path(args.output_dir) if args.force or conversion_required(outdir, args): if not convert_assets(outdir, args, srcdir): return 1 else: print("assets are up to date; no conversion is required.") print("override with --force.")
def main(args, error): """CLI entry point""" del error # unused # initialize libopenage from ..cppinterface.setup import setup setup(args) # conversion source if args.source_dir is not None: srcdir = CaseIgnoringDirectory(args.source_dir).root else: srcdir = None if args.interactive: interactive_browser(srcdir) return 0 # conversion target from ..assets import get_asset_path assets = get_asset_path(args) if args.force or conversion_required(assets, args): if not convert_assets(assets, args, srcdir): return 1 else: print("assets are up to date; no conversion is required.") print("override with --force.")
https://github.com/SFTtech/openage/issues/853
dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... INFO parsing slp image... INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... INFO parsing palette data... INFO packing texture... Traceback (most recent call last): File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/dev/openage/openage/__main__.py", line 128, in <module> exit(main()) File "/home/dev/openage/openage/__main__.py", line 121, in main return args.entrypoint(args, cli.error) File "/home/dev/openage/openage/convert/singlefile.py", line 72, in main tex.save(Directory(path).root, filename) File "/home/dev/openage/openage/convert/texture.py", line 170, in save raise ValueError("Texture must be saved as name.png. got: %s" % filename) ValueError: Texture must be saved as name.png. got: test
ValueError
def init_subparser(cli): """Initializes the parser for convert-specific args.""" import argparse cli.set_defaults(entrypoint=main) cli.add_argument("--palette", default="50500", help="palette number") cli.add_argument( "--interfac", type=argparse.FileType("rb"), help=( "drs archive where palette " "is contained (interfac.drs). " "If not set, assumed to be in same " "directory as the source drs archive" ), ) cli.add_argument( "drs", type=argparse.FileType("rb"), help=( "drs archive filename that contains the slp " "e.g. path ~/games/aoe/graphics.drs" ), ) cli.add_argument("slp", help=("slp filename inside the drs archive e.g. 326.slp")) cli.add_argument("output", help="image output path name")
def init_subparser(cli): """Initializes the parser for convert-specific args.""" cli.set_defaults(entrypoint=main) cli.add_argument("--palette", default="50500", help="palette number") cli.add_argument( "--interfac", help=("drs archive where palette is contained (interfac.drs)") ) cli.add_argument( "drs", help=( "drs archive filename that contains the slp " "e.g. path ~/games/aoe/graphics.drs" ), ) cli.add_argument("slp", help=("slp filename inside the drs archive e.g. 326.slp")) cli.add_argument("output", help="image output path name")
https://github.com/SFTtech/openage/issues/853
dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... INFO parsing slp image... INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... INFO parsing palette data... INFO packing texture... Traceback (most recent call last): File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/dev/openage/openage/__main__.py", line 128, in <module> exit(main()) File "/home/dev/openage/openage/__main__.py", line 121, in main return args.entrypoint(args, cli.error) File "/home/dev/openage/openage/convert/singlefile.py", line 72, in main tex.save(Directory(path).root, filename) File "/home/dev/openage/openage/convert/texture.py", line 170, in save raise ValueError("Texture must be saved as name.png. got: %s" % filename) ValueError: Texture must be saved as name.png. got: test
ValueError
def main(args, error): """CLI entry point for single file conversions""" del error # unused drspath = Path(args.drs.name) outputpath = Path(args.output) if args.interfac: interfacfile = args.interfac else: # if no interfac was given, assume # the same path of the drs archive. interfacfile = drspath.with_name("interfac.drs").open("rb") # pylint: disable=no-member # here, try opening slps from interfac or whereever info("opening slp in drs '%s:%s'..." % (drspath, args.slp)) slpfile = DRS(args.drs).root[args.slp].open("rb") # import here to prevent that the __main__ depends on SLP # just by importing this singlefile.py. from .slp import SLP # parse the slp image info("parsing slp image...") slpimage = SLP(slpfile.read()) # open color palette info("opening palette in drs '%s:%s.bina'..." % (interfacfile.name, args.palette)) palettefile = DRS(interfacfile).root["%s.bina" % args.palette].open("rb") info("parsing palette data...") palette = ColorTable(palettefile.read()) # create texture info("packing texture...") tex = Texture(slpimage, palette) # to save as png: tex.save(Directory(outputpath.parent).root, outputpath.name)
def main(args, error): """CLI entry point for single file conversions""" del error # unused if args.interfac: interfacfile = args.interfac else: # if no interfac was given, assume # the same path of the drs archive. drspath = os.path.split(args.drs)[0] interfacfile = os.path.join(drspath, "interfac.drs") # if .png was passed, strip it away. if args.output.endswith(".png"): args.output = args.output[:-4] # here, try opening slps from interfac or whereever info("opening slp in drs '%s:%s'..." % (args.drs, args.slp)) slpfile = DRS(open(args.drs, "rb")).root[args.slp].open("rb") # import here to prevent that the __main__ depends on SLP # just by importing this singlefile.py. from .slp import SLP # parse the slp image info("parsing slp image...") slpimage = SLP(slpfile.read()) # open color palette info("opening palette in drs '%s:%s.bina'..." % (interfacfile, args.palette)) palettefile = ( DRS(open(interfacfile, "rb")).root["%s.bina" % args.palette].open("rb") ) info("parsing palette data...") palette = ColorTable(palettefile.read()) # create texture info("packing texture...") tex = Texture(slpimage, palette) # to save as png: path, filename = os.path.split(args.output) tex.save(Directory(path).root, filename)
https://github.com/SFTtech/openage/issues/853
dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... INFO parsing slp image... INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... INFO parsing palette data... INFO packing texture... Traceback (most recent call last): File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/dev/openage/openage/__main__.py", line 128, in <module> exit(main()) File "/home/dev/openage/openage/__main__.py", line 121, in main return args.entrypoint(args, cli.error) File "/home/dev/openage/openage/convert/singlefile.py", line 72, in main tex.save(Directory(path).root, filename) File "/home/dev/openage/openage/convert/texture.py", line 170, in save raise ValueError("Texture must be saved as name.png. got: %s" % filename) ValueError: Texture must be saved as name.png. got: test
ValueError
def save(self, targetdir, filename, meta_formats=None): """ Store the image data into the target directory path, with given filename="dir/out.png" If metaformats are requested, export e.g. as "dir/out.docx". """ if not isinstance(targetdir, Path): raise ValueError("util.fslike Path expected as targetdir") if not isinstance(filename, str): raise ValueError("str expected as filename, not %s" % type(filename)) basename, ext = os.path.splitext(filename) # only allow png, although PIL could of course # do other formats. if ext != ".png": raise ValueError( "Filename invalid, a texture must be saved" "as 'filename.png', not '%s'" % (filename) ) # without the dot ext = ext[1:] # generate PNG file with targetdir[filename].open("wb") as imagefile: self.image_data.get_pil_image().save(imagefile, ext) if meta_formats: # generate formatted texture metadata formatter = data_formatter.DataFormatter() formatter.add_data(self.dump(basename)) formatter.export(targetdir, meta_formats)
def save(self, targetdir, filename, meta_formats=None): """ Store the image data into the target directory path, with given filename="dir/out.png" If metaformats are requested, export e.g. as "dir/out.docx". """ if not isinstance(targetdir, Path): raise ValueError("util.fslike Path expected as targetdir") if not isinstance(filename, str): raise ValueError("str expected as filename, not %s" % type(filename)) basename, ext = os.path.splitext(filename) if ext != ".png": raise ValueError("Texture must be saved as name.png. got: %s" % filename) # without the dot ext = ext[1:] # generate PNG file with targetdir[filename].open("wb") as imagefile: self.image_data.get_pil_image().save(imagefile, ext) if meta_formats: # generate formatted texture metadata formatter = data_formatter.DataFormatter() formatter.add_data(self.dump(basename)) formatter.export(targetdir, meta_formats)
https://github.com/SFTtech/openage/issues/853
dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... INFO parsing slp image... INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... INFO parsing palette data... INFO packing texture... Traceback (most recent call last): File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/dev/openage/openage/__main__.py", line 128, in <module> exit(main()) File "/home/dev/openage/openage/__main__.py", line 121, in main return args.entrypoint(args, cli.error) File "/home/dev/openage/openage/convert/singlefile.py", line 72, in main tex.save(Directory(path).root, filename) File "/home/dev/openage/openage/convert/texture.py", line 170, in save raise ValueError("Texture must be saved as name.png. got: %s" % filename) ValueError: Texture must be saved as name.png. got: test
ValueError
def get_config_path(custom_cfg_dir=None): """ Locates the main configuration file by name in some searchpaths. Optionally, mount a custom directory with highest priority. """ # if we're in devmode, use only the build source config folder if config.DEVMODE: return Directory(os.path.join(config.BUILD_SRC_DIR, "cfg")).root # else, mount the possible locations in an union # to overlay the global dir and the user dir. result = Union().root # mount the global config dir # we don't use xdg config_dirs because that would be /etc/xdg/openage # and nobody would ever look in there. global_configs = pathlib.Path(config.GLOBAL_CONFIG_DIR) if global_configs.is_dir(): result.mount(WriteBlocker(Directory(global_configs).root).root) # then the per-user config dir (probably ~/.config/openage) home_cfg = default_dirs.get_dir("config_home") / "openage" result.mount(Directory(home_cfg, create_if_missing=True).root) # the optional command line argument overrides it all if custom_cfg_dir: result.mount(Directory(custom_cfg_dir).root) return result
def get_config_path(args): """ Locates the main configuration file by name in some searchpaths. """ # if we're in devmode, use only the build source config folder if config.DEVMODE: return Directory(os.path.join(config.BUILD_SRC_DIR, "cfg")).root # else, mount the possible locations in an union # to overlay the global dir and the user dir. result = Union().root # mount the global config dir # we don't use xdg config_dirs because that would be /etc/xdg/openage # and nobody would ever look in there. global_configs = pathlib.Path(config.GLOBAL_CONFIG_DIR) if global_configs.is_dir(): result.mount(WriteBlocker(Directory(global_configs).root).root) # then the per-user config dir (probably ~/.config/openage) home_cfg = default_dirs.get_dir("config_home") / "openage" result.mount(Directory(home_cfg, create_if_missing=True).root) # the optional command line argument overrides it all if args.cfg_dir: result.mount(Directory(args.cfg_dir).root) return result
https://github.com/SFTtech/openage/issues/853
dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... INFO parsing slp image... INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... INFO parsing palette data... INFO packing texture... Traceback (most recent call last): File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/dev/openage/openage/__main__.py", line 128, in <module> exit(main()) File "/home/dev/openage/openage/__main__.py", line 121, in main return args.entrypoint(args, cli.error) File "/home/dev/openage/openage/convert/singlefile.py", line 72, in main tex.save(Directory(path).root, filename) File "/home/dev/openage/openage/convert/texture.py", line 170, in save raise ValueError("Texture must be saved as name.png. got: %s" % filename) ValueError: Texture must be saved as name.png. got: test
ValueError
def main(args, error): """ Makes sure that the assets have been converted, and jumps into the C++ main method. """ del error # unused # we have to import stuff inside the function # as it depends on generated/compiled code from .main_cpp import run_game from .. import config from ..assets import get_asset_path from ..convert.main import conversion_required, convert_assets from ..cppinterface.setup import setup as cpp_interface_setup from ..cvar.location import get_config_path from ..util.fslike.union import Union # initialize libopenage cpp_interface_setup(args) info("launching openage {}".format(config.VERSION)) info("compiled by {}".format(config.COMPILER)) if config.DEVMODE: info("running in DEVMODE") # create virtual file system for data paths root = Union().root # mount the assets folder union at "assets/" root["assets"].mount(get_asset_path(args.asset_dir)) # mount the config folder at "cfg/" root["cfg"].mount(get_config_path(args.cfg_dir)) # ensure that the assets have been converted if conversion_required(root["assets"], args): if not convert_assets(root["assets"], args): err("game asset conversion failed") return 1 # start the game, continue in main_cpp.pyx! return run_game(args, root)
def main(args, error): """ Makes sure that the assets have been converted, and jumps into the C++ main method. """ del error # unused # we have to import stuff inside the function # as it depends on generated/compiled code from .main_cpp import run_game from .. import config from ..assets import get_asset_path from ..convert.main import conversion_required, convert_assets from ..cppinterface.setup import setup as cpp_interface_setup from ..cvar.location import get_config_path from ..util.fslike.union import Union # initialize libopenage cpp_interface_setup(args) info("launching openage {}".format(config.VERSION)) info("compiled by {}".format(config.COMPILER)) if config.DEVMODE: info("running in DEVMODE") # create virtual file system for data paths root = Union().root # mount the assets folder union at "assets/" root["assets"].mount(get_asset_path(args)) # mount the config folder at "cfg/" root["cfg"].mount(get_config_path(args)) # ensure that the assets have been converted if conversion_required(root["assets"], args): if not convert_assets(root["assets"], args): err("game asset conversion failed") return 1 # start the game, continue in main_cpp.pyx! return run_game(args, root)
https://github.com/SFTtech/openage/issues/853
dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... INFO parsing slp image... INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... INFO parsing palette data... INFO packing texture... Traceback (most recent call last): File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/dev/openage/openage/__main__.py", line 128, in <module> exit(main()) File "/home/dev/openage/openage/__main__.py", line 121, in main return args.entrypoint(args, cli.error) File "/home/dev/openage/openage/convert/singlefile.py", line 72, in main tex.save(Directory(path).root, filename) File "/home/dev/openage/openage/convert/texture.py", line 170, in save raise ValueError("Texture must be saved as name.png. got: %s" % filename) ValueError: Texture must be saved as name.png. got: test
ValueError
def get_string_resources(args): """reads the (language) string resources""" from .stringresource import StringResource stringres = StringResource() srcdir = args.srcdir count = 0 # AoK:TC uses .DLL PE files for its string resources, # HD uses plaintext files if GameVersion.age2_fe in args.game_versions: from .hdlanguagefile import read_hd_language_file for lang in srcdir["resources"].list(): try: if lang == b"_common": continue langfilename = [ "resources", lang.decode(), "strings", "key-value", "key-value-strings-utf8.txt", ] with srcdir[langfilename].open("rb") as langfile: stringres.fill_from(read_hd_language_file(langfile, lang)) count += 1 except FileNotFoundError: # that's fine, there are no language files for every language. pass elif GameVersion.age2_hd_3x in args.game_versions: from .hdlanguagefile import read_hd_language_file # HD Edition 3.x and below store language .txt files in the Bin/ folder. # Specific language strings are in Bin/$LANG/*.txt. for lang in srcdir["bin"].list(): dirname = ["bin", lang.decode()] # There are some .txt files immediately in bin/, but they don't seem # to contain anything useful. (Everything is overridden by files in # Bin/$LANG/.) if not srcdir[dirname].is_dir(): continue for basename in srcdir[dirname].list(): langfilename = ["bin", lang.decode(), basename] with srcdir[langfilename].open("rb") as langfile: # No utf-8 :( stringres.fill_from( read_hd_language_file(langfile, lang, enc="iso-8859-1") ) count += 1 elif srcdir["language.dll"].is_file(): from .pefile import PEFile for name in ["language.dll", "language_x1.dll", "language_x1_p1.dll"]: pefile = PEFile(srcdir[name].open("rb")) stringres.fill_from(pefile.resources().strings) count += 1 if not count: raise FileNotFoundError("could not find any language files") # TODO transform and cleanup the read strings: # convert formatting indicators from HTML to something sensible, etc return stringres
def get_string_resources(args): """reads the (language) string resources""" from .stringresource import StringResource stringres = StringResource() srcdir = args.srcdir count = 0 # AoK:TC uses .DLL PE files for its string resources, # HD uses plaintext files if srcdir["language.dll"].is_file(): from .pefile import PEFile for name in ["language.dll", "language_x1.dll", "language_x1_p1.dll"]: pefile = PEFile(srcdir[name].open("rb")) stringres.fill_from(pefile.resources().strings) count += 1 elif GameVersion.age2_fe in args.game_versions: from .hdlanguagefile import read_hd_language_file for lang in srcdir["resources"].list(): try: if lang == b"_common": continue langfilename = [ "resources", lang.decode(), "strings", "key-value", "key-value-strings-utf8.txt", ] with srcdir[langfilename].open("rb") as langfile: stringres.fill_from(read_hd_language_file(langfile, lang)) count += 1 except FileNotFoundError: # that's fine, there are no language files for every language. pass elif GameVersion.age2_hd_3x in args.game_versions: from .hdlanguagefile import read_hd_language_file # HD Edition 3.x and below store language .txt files in the Bin/ folder. # Specific language strings are in Bin/$LANG/*.txt. for lang in srcdir["bin"].list(): dirname = ["bin", lang.decode()] # There are some .txt files immediately in bin/, but they don't seem # to contain anything useful. (Everything is overridden by files in # Bin/$LANG/.) if not srcdir[dirname].is_dir(): continue for basename in srcdir[dirname].list(): langfilename = ["bin", lang.decode(), basename] with srcdir[langfilename].open("rb") as langfile: # No utf-8 :( stringres.fill_from( read_hd_language_file(langfile, lang, enc="iso-8859-1") ) count += 1 if not count: raise FileNotFoundError("could not find any language files") # TODO transform and cleanup the read strings: # convert formatting indicators from HTML to something sensible, etc return stringres
https://github.com/SFTtech/openage/issues/461
$ make run ./run game INFO [py] No converted assets have been found media conversion is required. please provide your AoE II installation dir: /media/niklas/E4DE307EDE304AD6/Program Files (x86)/Steam/SteamApps/common/Age2HD INFO [py] Game version(s) detected: Age of Empires 2: HD Edition (Version 3.x); Forgotten Empires; Age of Empires 2: The Conquerors, Patch 1.0c INFO [py] converting metadata INFO [py] [0] palette INFO [py] [1] empires.dat INFO [py] [2] blendomatic.dat INFO [py] blending masks successfully exported INFO [py] [3] player color palette INFO [py] [4] terminal color palette INFO [py] [5] string resources Traceback (most recent call last): File "run.py", line 15, in init run (/home/niklas/Projekte/openage/run.cpp:832) main() File "/home/niklas/Projekte/openage/openage/__main__.py", line 94, in main return args.entrypoint(args, cli.error) File "/home/niklas/Projekte/openage/openage/game/main.py", line 33, in main if not convert_assets(assets, args): File "/home/niklas/Projekte/openage/openage/convert/main.py", line 125, in convert_assets for current_item in convert(args): File "/home/niklas/Projekte/openage/openage/convert/driver.py", line 126, in convert yield from convert_metadata(args) File "/home/niklas/Projekte/openage/openage/convert/driver.py", line 179, in convert_metadata stringres = get_string_resources(args) File "/home/niklas/Projekte/openage/openage/convert/driver.py", line 37, in get_string_resources pefile = PEFile(srcdir[name].open('rb')) File "/home/niklas/Projekte/openage/openage/convert/pefile.py", line 191, in __init__ raise Exception("Invalid section name: " + section.name) Exception: Invalid section name: CODE Makefile:22: recipe for target 'run' failed make: *** [run] Error 1
Exception
def get_domain_mx_list(domain): """Return a list of MX IP address for domain.""" result = [] logger = logging.getLogger("modoboa.admin") dns_server = param_tools.get_global_parameter("custom_dns_server") if dns_server: resolver = dns.resolver.Resolver() resolver.nameservers = [dns_server] else: resolver = dns.resolver try: dns_answers = resolver.query(domain, "MX") except dns.resolver.NXDOMAIN as e: logger.error(_("No DNS records found for %s") % domain, exc_info=e) except dns.resolver.NoAnswer as e: logger.error(_("No MX record for %s") % domain, exc_info=e) except dns.resolver.NoNameservers as e: logger.error(_("No working name servers found"), exc_info=e) except dns.resolver.Timeout as e: logger.warning( _("DNS resolution timeout, unable to query %s at the moment") % domain, exc_info=e, ) else: for dns_answer in dns_answers: for rtype in ["A", "AAAA"]: try: mx_domain = dns_answer.exchange.to_unicode( omit_final_dot=True, idna_codec=IDNA_2008_UTS_46 ) ip_answers = resolver.query(mx_domain, rtype) except dns.resolver.NXDOMAIN as e: logger.error( _("No {type} record found for MX {mx}").format( type=rtype, mx=domain ), exc_info=e, ) except dns.resolver.NoAnswer: pass else: for ip_answer in ip_answers: try: address_smart = smart_text(ip_answer.address) mx_ip = ipaddress.ip_address(address_smart) except ValueError as e: logger.warning( _( "Invalid IP address format for {domain}; {addr}" ).format( domain=mx_domain, addr=smart_text(ip_answer.address) ), exc_info=e, ) else: result.append((mx_domain, mx_ip)) return result
def get_domain_mx_list(domain): """Return a list of MX IP address for domain.""" result = [] logger = logging.getLogger("modoboa.admin") dns_server = param_tools.get_global_parameter("custom_dns_server") if dns_server: resolver = dns.resolver.Resolver() resolver.nameservers = [dns_server] else: resolver = dns.resolver try: dns_answers = resolver.query(domain, "MX") except dns.resolver.NXDOMAIN as e: logger.error(_("No DNS records found for %s") % domain, exc_info=e) except dns.resolver.NoAnswer as e: logger.error(_("No MX record for %s") % domain, exc_info=e) except dns.resolver.NoNameservers as e: logger.error(_("No working name servers found"), exc_info=e) except dns.resolver.Timeout as e: logger.warning( _("DNS resolution timeout, unable to query %s at the moment") % domain, exc_info=e, ) else: for dns_answer in dns_answers: for rtype in ["A", "AAAA"]: try: mx_domain = dns_answer.exchange.to_unicode( omit_final_dot=True, idna_codec=IDNA_2008_UTS_46 ) ip_answers = resolver.query(mx_domain, rtype) except dns.resolver.NXDOMAIN as e: logger.error( _("No {type} record found for MX {mx}").format( type=rtype, mx=domain ), exc_info=e, ) else: for ip_answer in ip_answers: try: address_smart = smart_text(ip_answer.address) mx_ip = ipaddress.ip_address(address_smart) except ValueError as e: logger.warning( _( "Invalid IP address format for {domain}; {addr}" ).format( domain=mx_domain, addr=smart_text(ip_answer.address) ), exc_info=e, ) else: result.append((mx_domain, mx_ip)) return result
https://github.com/modoboa/modoboa/issues/1596
Traceback (most recent call last): File "/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py", line 215, in __init__ rdclass, rdtype) File "/srv/modoboa/env3/lib/python3.5/site-packages/dns/message.py", line 352, in find_rrset raise KeyError KeyError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py", line 225, in __init__ dns.rdatatype.CNAME) File "/srv/modoboa/env3/lib/python3.5/site-packages/dns/message.py", line 352, in find_rrset raise KeyError KeyError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/srv/modoboa/instance/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/srv/modoboa/env3/lib/python3.5/site-packages/subcommand/base.py", line 53, in run_from_argv return super(SubcommandCommand, self).run_from_argv(argv) File "/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/srv/modoboa/env3/lib/python3.5/site-packages/subcommand/base.py", line 84, in handle return command.run_from_argv(argv) File "/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/srv/modoboa/env3/lib/python3.5/site-packages/modoboa/admin/management/commands/subcommands/_mx.py", line 244, in handle self.check_domain(domain, **options) File "/srv/modoboa/env3/lib/python3.5/site-packages/modoboa/admin/management/commands/subcommands/_mx.py", line 191, in check_domain models.MXRecord.objects.get_or_create_for_domain(domain, ttl)) File "/srv/modoboa/env3/lib/python3.5/site-packages/modoboa/admin/models/mxrecord.py", line 47, in get_or_create_for_domain domain_mxs = lib.get_domain_mx_list(domain.name) File "/srv/modoboa/env3/lib/python3.5/site-packages/modoboa/admin/lib.py", line 202, in get_domain_mx_list ip_answers = resolver.query(mx_domain, rtype) File "/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py", line 1132, in query raise_on_no_answer, source_port) File "/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py", line 1053, in query raise_on_no_answer) File "/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py", line 234, in __init__ raise NoAnswer(response=response) dns.resolver.NoAnswer: The DNS response does not contain an answer to the question: mail.toto.com. IN AAAA
KeyError
def authenticate(self, request, username=None, password=None): """Check the username/password and return a User.""" host = getattr(settings, "AUTH_SMTP_SERVER_ADDRESS", "localhost") port = getattr(settings, "AUTH_SMTP_SERVER_PORT", 25) secured_mode = getattr(settings, "AUTH_SMTP_SECURED_MODE", None) if secured_mode == "ssl": smtp = smtplib.SMTP_SSL(host, port) else: smtp = smtplib.SMTP(host, port) if secured_mode == "starttls": smtp.starttls() try: smtp.login(username, password) except smtplib.SMTPException: return None return self.get_or_build_user(username)
def authenticate(self, username=None, password=None): """Check the username/password and return a User.""" host = getattr(settings, "AUTH_SMTP_SERVER_ADDRESS", "localhost") port = getattr(settings, "AUTH_SMTP_SERVER_PORT", 25) secured_mode = getattr(settings, "AUTH_SMTP_SECURED_MODE", None) if secured_mode == "ssl": smtp = smtplib.SMTP_SSL(host, port) else: smtp = smtplib.SMTP(host, port) if secured_mode == "starttls": smtp.starttls() try: smtp.login(username, password) except smtplib.SMTPException: return None return self.get_or_build_user(username)
https://github.com/modoboa/modoboa/issues/1510
Internal Server Error: /accounts/login/ Traceback (most recent call last): File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/modoboa/env/lib/python2.7/site-packages/django/utils/decorators.py", line 185, in inner return func(*args, **kwargs) File "/srv/modoboa/env/lib/python2.7/site-packages/django/utils/decorators.py", line 185, in inner return func(*args, **kwargs) File "/srv/modoboa/env/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/srv/modoboa/env/lib/python2.7/site-packages/modoboa/core/views/auth.py", line 34, in dologin password=form.cleaned_data["password"]) File "/srv/modoboa/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 70, in authenticate user = _authenticate_with_backend(backend, backend_path, request, credentials) File "/srv/modoboa/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 116, in _authenticate_with_backend return backend.authenticate(*args, **credentials) File "/srv/modoboa/env/lib/python2.7/site-packages/modoboa/lib/authbackends.py", line 119, in authenticate username=username, password=password) TypeError: authenticate() takes at least 2 arguments (3 given)
TypeError
def authenticate(self, *args, **kwargs): if self.global_params["authentication_type"] == "ldap": return super(LDAPBackend, self).authenticate(*args, **kwargs) return None
def authenticate(self, username, password): if self.global_params["authentication_type"] == "ldap": return super(LDAPBackend, self).authenticate( username=username, password=password ) return None
https://github.com/modoboa/modoboa/issues/1510
Internal Server Error: /accounts/login/ Traceback (most recent call last): File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/modoboa/env/lib/python2.7/site-packages/django/utils/decorators.py", line 185, in inner return func(*args, **kwargs) File "/srv/modoboa/env/lib/python2.7/site-packages/django/utils/decorators.py", line 185, in inner return func(*args, **kwargs) File "/srv/modoboa/env/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/srv/modoboa/env/lib/python2.7/site-packages/modoboa/core/views/auth.py", line 34, in dologin password=form.cleaned_data["password"]) File "/srv/modoboa/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 70, in authenticate user = _authenticate_with_backend(backend, backend_path, request, credentials) File "/srv/modoboa/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 116, in _authenticate_with_backend return backend.authenticate(*args, **credentials) File "/srv/modoboa/env/lib/python2.7/site-packages/modoboa/lib/authbackends.py", line 119, in authenticate username=username, password=password) TypeError: authenticate() takes at least 2 arguments (3 given)
TypeError
def handle(self, *args, **options): exts_pool.load_all() self.csvwriter = csv.writer(self.stdout, delimiter=smart_text(options["sepchar"])) getattr(self, "export_{}".format(options["objtype"]))()
def handle(self, *args, **options): exts_pool.load_all() self.csvwriter = csv.writer(sys.stdout, delimiter=options["sepchar"]) getattr(self, "export_{}".format(options["objtype"]))()
https://github.com/modoboa/modoboa/issues/1483
Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/srv/modoboa/env/local/lib/python2.7/site-packages/subcommand/base.py", line 53, in run_from_argv return super(SubcommandCommand, self).run_from_argv(argv) File "/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/srv/modoboa/env/local/lib/python2.7/site-packages/subcommand/base.py", line 84, in handle return command.run_from_argv(argv) File "/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_export.py", line 64, in handle self.csvwriter = csv.writer(sys.stdout, delimiter=options["sepchar"]) File "/srv/modoboa/env/local/lib/python2.7/site-packages/backports/csv.py", line 185, in __init__ raise TypeError(*e.args) TypeError: "delimiter" must be string, not bytes
TypeError
def ready(self): load_core_settings() # Import these to force registration of checks and signals from . import checks # noqa:F401 from . import handlers signals.post_migrate.connect(handlers.create_local_config, sender=self)
def ready(self): load_core_settings() from . import handlers signals.post_migrate.connect(handlers.create_local_config, sender=self)
https://github.com/modoboa/modoboa/issues/1086
Traceback (most recent call last): File "/srv/modoboa/instance/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/srv/modoboa/env/local/lib/python2.7/site-packages/django_subcommand2-0.1.1-py2.7.egg/subcommand/base.py", line 53, in run_from_argv return super(SubcommandCommand, self).run_from_argv(argv) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/srv/modoboa/env/local/lib/python2.7/site-packages/django_subcommand2-0.1.1-py2.7.egg/subcommand/base.py", line 84, in handle return command.run_from_argv(argv) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py", line 262, in handle self.check_domain(domain, **options) File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py", line 218, in check_domain mx_list = list(self.get_mx_records_for_domain(domain, ttl=ttl)) File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py", line 109, in get_mx_records_for_domain updated=now + delta) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/manager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/query.py", line 401, in create obj.save(force_insert=True, using=self.db) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/base.py", line 708, in save force_update=force_update, update_fields=update_fields) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/base.py", line 736, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/base.py", line 820, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/base.py", line 859, in _do_insert using=using, raw=raw) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/manager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/query.py", line 1039, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/sql/compiler.py", line 1059, in execute_sql for sql, params in self.as_sql(): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/sql/compiler.py", line 1019, in as_sql for obj in self.query.objs File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/sql/compiler.py", line 958, in prepare_value value = field.get_db_prep_save(value, connection=self.connection) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/fields/__init__.py", line 728, in get_db_prep_save prepared=False) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/fields/__init__.py", line 1461, in get_db_prep_value value = self.get_prep_value(value) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/fields/__init__.py", line 1455, in get_prep_value value = timezone.make_aware(value, default_timezone) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/utils/timezone.py", line 364, in make_aware return timezone.localize(value, is_dst=is_dst) File "/srv/modoboa/env/local/lib/python2.7/site-packages/pytz/tzinfo.py", line 327, in localize raise NonExistentTimeError(dt) pytz.exceptions.NonExistentTimeError: 2017-03-26 02:30:01.875287
pytz.exceptions.NonExistentTimeError
def store_dnsbl_result(self, domain, provider, results, **options): """Store DNSBL provider results for domain.""" alerts = {} to_create = [] for mx, result in list(results.items()): if not result: result = "" dnsbl_result = models.DNSBLResult.objects.filter( domain=domain, provider=provider, mx=mx ).first() trigger = False if dnsbl_result is None: to_create.append( models.DNSBLResult( domain=domain, provider=provider, mx=mx, status=result ) ) if result: trigger = True else: dnsbl_result.status = result dnsbl_result.save() if not dnsbl_result.status and result: trigger = True if trigger: if domain not in alerts: alerts[domain] = [] alerts[domain].append((provider, mx)) models.DNSBLResult.objects.bulk_create(to_create) if not alerts: return emails = list(options["email"]) if not options["skip_admin_emails"]: emails.extend( domain.admins.exclude(mailbox__isnull=True).values_list("email", flat=True) ) if not len(emails): return with mail.get_connection() as connection: for domain, providers in list(alerts.items()): content = render_to_string( "admin/notifications/domain_in_dnsbl.html", {"domain": domain, "alerts": providers}, ) subject = _("[modoboa] DNSBL issue(s) for domain {}").format(domain.name) msg = EmailMessage( subject, content.strip(), self.sender, emails, connection=connection ) msg.send()
def store_dnsbl_result(self, domain, provider, results, **options): """Store DNSBL provider results for domain.""" alerts = {} to_create = [] for mx in results.keys(): result = "" if not results[mx] else results[mx] dnsbl_result = models.DNSBLResult.objects.filter( domain=domain, provider=provider, mx=mx ).first() trigger = False if dnsbl_result is None: to_create.append( models.DNSBLResult( domain=domain, provider=provider, mx=mx, status=result ) ) if result: trigger = True else: dnsbl_result.status = result dnsbl_result.save() if not dnsbl_result.status and result: trigger = True if trigger: if domain not in alerts: alerts[domain] = [] alerts[domain].append((provider, mx)) models.DNSBLResult.objects.bulk_create(to_create) if not alerts: return emails = list(options["email"]) if not options["skip_admin_emails"]: emails.extend( domain.admins.exclude(mailbox__isnull=True).values_list("email", flat=True) ) if not len(emails): return with mail.get_connection() as connection: for domain, providers in list(alerts.items()): content = render_to_string( "admin/notifications/domain_in_dnsbl.html", {"domain": domain, "alerts": providers}, ) subject = _("[modoboa] DNSBL issue(s) for domain {}").format(domain.name) msg = EmailMessage( subject, content.strip(), self.sender, emails, connection=connection ) msg.send()
https://github.com/modoboa/modoboa/issues/1243
Traceback (most recent call last): File "/srv/modoboa/instance/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/srv/modoboa/env/lib/python2.7/site-packages/subcommand/base.py", line 53, in run_from_argv return super(SubcommandCommand, self).run_from_argv(argv) File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/srv/modoboa/env/lib/python2.7/site-packages/subcommand/base.py", line 84, in handle return command.run_from_argv(argv) File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/srv/modoboa/env/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py", line 225, in handle self.check_domain(domain, **options) File "/srv/modoboa/env/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py", line 198, in check_domain self.store_dnsbl_result(domain, provider, results, **options) File "/srv/modoboa/env/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py", line 107, in store_dnsbl_result models.DNSBLResult.objects.bulk_create(to_create) File "/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/query.py", line 452, in bulk_create ids = self._batched_insert(objs_without_pk, fields, batch_size) File "/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/query.py", line 1062, in _batched_insert inserted_id = self._insert(item, fields=fields, using=self.db, return_id=True) File "/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/query.py", line 1045, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1054, in execute_sql cursor.execute(sql, params) File "/srv/modoboa/env/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/srv/modoboa/env/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/srv/modoboa/env/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.IntegrityError: duplicate key value violates unique constraint "admin_dnsblresult_domain_id_9710ce0d_uniq" DETAIL: Key (domain_id, provider, mx_id)=(1, aspews.ext.sorbs.net, 55) already exists.```
django.db.utils.IntegrityError
def on_mailbox_modified(mailbox): """Update amavis records if address has changed.""" if ( parameters.get_admin("MANUAL_LEARNING") == "no" or not hasattr(mailbox, "old_full_address") or mailbox.full_address == mailbox.old_full_address ): return user = Users.objects.select_related().get(email=mailbox.old_full_address) full_address = mailbox.full_address user.email = full_address user.policy.policy_name = full_address[:32] user.policy.sa_username = full_address user.policy.save() user.save()
def on_mailbox_modified(mailbox): """Update amavis records if address has changed.""" if ( parameters.get_admin("MANUAL_LEARNING") == "no" or not hasattr(mailbox, "old_full_address") or mailbox.full_address == mailbox.old_full_address ): return user = Users.objects.select_related.get(email=mailbox.old_full_address) full_address = mailbox.full_address user.email = full_address user.policy.policy_name = full_address[:32] user.policy.sa_username = full_address user.policy.save() user.save()
https://github.com/modoboa/modoboa/issues/701
Traceback (most recent call last): File "/srv/python-envs/service/lib/python2.7/site-packages/django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/python-envs/service/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view return view_func(request, *args, **kwargs) File "/srv/python-envs/service/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view return view_func(request, *args, **kwargs) File "/srv/python-envs/service/lib/python2.7/site-packages/reversion/revisions.py", line 297, in do_revision_context return func(*args, **kwargs) File "/srv/python-envs/service/lib/python2.7/site-packages/modoboa/extensions/admin/views/identity.py", line 177, in editaccount return AccountForm(request, instances=instances).process() File "/srv/python-envs/service/lib/python2.7/site-packages/modoboa/lib/formutils.py", line 315, in process self.save() File "/srv/python-envs/service/lib/python2.7/site-packages/modoboa/extensions/admin/forms/account.py", line 427, in save self.forms[1]["instance"].save(self.user, self.account) File "/srv/python-envs/service/lib/python2.7/site-packages/modoboa/extensions/admin/forms/account.py", line 305, in save self.update_mailbox(user, account) File "/srv/python-envs/service/lib/python2.7/site-packages/modoboa/extensions/admin/forms/account.py", line 257, in update_mailbox events.raiseEvent('MailboxModified', self.mb) File "/srv/python-envs/service/lib/python2.7/site-packages/modoboa/lib/events.py", line 145, in raiseEvent callback(*args, **kwargs) File "/srv/python-envs/service/lib/python2.7/site-packages/modoboa/lib/events.py", line 98, in wrapped_f return f(*args, **kwargs) File "/srv/python-envs/service/lib/python2.7/site-packages/modoboa/extensions/amavis/general_callbacks.py", line 67, in on_mailbox_modified user = Users.objects.select_related.get(email=mailbox.old_full_address) AttributeError: 'function' object has no attribute 'get'
AttributeError
def get_mail_content(self, mailid): """Retrieve the content of a message.""" content = "".join( [str(qmail.mail_text) for qmail in Quarantine.objects.filter(mail=mailid)] ) if isinstance(content, unicode): content = content.encode("utf-8") return content
def get_mail_content(self, mailid): """Retrieve the content of a message.""" return Quarantine.objects.filter(mail=mailid)
https://github.com/modoboa/modoboa/issues/677
Traceback (most recent call last): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py", line 36, in wrapped_f return f(request, *args, **kwargs) File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 135, in getmailcontent mail = SQLemail(mail_id, mformat="plain", links="0") File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py", line 23, in __init__ {"name": label, "value": self.get_header(self.msg, f)} File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py", line 44, in msg mail_text = "".join([qm.mail_text for qm in qmails]) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 96, in __iter__ self._fetch_all() File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 857, in _fetch_all self._result_cache = list(self.iterator()) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 220, in iterator for row in compiler.results_iter(): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 713, in results_iter for rows in self.execute_sql(MULTI): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 786, in execute_sql cursor.execute(sql, params) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py", line 53, in execute return self.cursor.execute(sql, params) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py", line 99, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py", line 53, in execute return self.cursor.execute(sql, params) DataError: invalid byte sequence for encoding "UTF8": 0xb3
DataError
def get_mail_content(self, mailid): """Retrieve the content of a message.""" content = "".join( [str(qmail.mail_text) for qmail in Quarantine.objects.filter(mail=mailid)] ) if isinstance(content, unicode): content = content.encode("utf-8") return content
def get_mail_content(self, mailid): """Retrieve the content of a message.""" return Quarantine.objects.filter(mail=mailid).extra( select={"mail_text": "convert_from(mail_text, 'UTF8')"} )
https://github.com/modoboa/modoboa/issues/677
Traceback (most recent call last): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py", line 36, in wrapped_f return f(request, *args, **kwargs) File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 135, in getmailcontent mail = SQLemail(mail_id, mformat="plain", links="0") File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py", line 23, in __init__ {"name": label, "value": self.get_header(self.msg, f)} File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py", line 44, in msg mail_text = "".join([qm.mail_text for qm in qmails]) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 96, in __iter__ self._fetch_all() File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 857, in _fetch_all self._result_cache = list(self.iterator()) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 220, in iterator for row in compiler.results_iter(): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 713, in results_iter for rows in self.execute_sql(MULTI): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 786, in execute_sql cursor.execute(sql, params) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py", line 53, in execute return self.cursor.execute(sql, params) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py", line 99, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py", line 53, in execute return self.cursor.execute(sql, params) DataError: invalid byte sequence for encoding "UTF8": 0xb3
DataError
def msg(self): """Get message's content.""" import email if self._msg is None: mail_text = get_connector().get_mail_content(self.mailid) self._msg = email.message_from_string(mail_text) self._parse(self._msg) return self._msg
def msg(self): """Get message's content.""" import email if self._msg is None: qmails = get_connector().get_mail_content(self.mailid) mail_text = "".join([qm.mail_text for qm in qmails]) if type(mail_text) is unicode: mail_text = mail_text.encode("utf-8") self._msg = email.message_from_string(mail_text) self._parse(self._msg) return self._msg
https://github.com/modoboa/modoboa/issues/677
Traceback (most recent call last): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py", line 36, in wrapped_f return f(request, *args, **kwargs) File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 135, in getmailcontent mail = SQLemail(mail_id, mformat="plain", links="0") File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py", line 23, in __init__ {"name": label, "value": self.get_header(self.msg, f)} File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py", line 44, in msg mail_text = "".join([qm.mail_text for qm in qmails]) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 96, in __iter__ self._fetch_all() File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 857, in _fetch_all self._result_cache = list(self.iterator()) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 220, in iterator for row in compiler.results_iter(): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 713, in results_iter for rows in self.execute_sql(MULTI): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 786, in execute_sql cursor.execute(sql, params) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py", line 53, in execute return self.cursor.execute(sql, params) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py", line 99, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py", line 53, in execute return self.cursor.execute(sql, params) DataError: invalid byte sequence for encoding "UTF8": 0xb3
DataError
def viewheaders(request, mail_id): """Display message headers.""" content = get_connector().get_mail_content(mail_id) msg = email.message_from_string(content) headers = [] for name, value in msg.items(): if value: result = chardet.detect(value) if result["encoding"] is not None: value = value.decode(result["encoding"]) headers += [(name, value)] return render(request, "amavis/viewheader.html", {"headers": headers})
def viewheaders(request, mail_id): """Display message headers.""" content = "" for qm in get_connector().get_mail_content(mail_id): content += qm.mail_text if type(content) is unicode: content = content.encode("utf-8") msg = email.message_from_string(content) headers = [] for name, value in msg.items(): if value: result = chardet.detect(value) if result["encoding"] is not None: value = value.decode(result["encoding"]) headers += [(name, value)] return render(request, "amavis/viewheader.html", {"headers": headers})
https://github.com/modoboa/modoboa/issues/677
Traceback (most recent call last): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py", line 36, in wrapped_f return f(request, *args, **kwargs) File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 135, in getmailcontent mail = SQLemail(mail_id, mformat="plain", links="0") File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py", line 23, in __init__ {"name": label, "value": self.get_header(self.msg, f)} File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py", line 44, in msg mail_text = "".join([qm.mail_text for qm in qmails]) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 96, in __iter__ self._fetch_all() File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 857, in _fetch_all self._result_cache = list(self.iterator()) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 220, in iterator for row in compiler.results_iter(): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 713, in results_iter for rows in self.execute_sql(MULTI): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 786, in execute_sql cursor.execute(sql, params) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py", line 53, in execute return self.cursor.execute(sql, params) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py", line 99, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py", line 53, in execute return self.cursor.execute(sql, params) DataError: invalid byte sequence for encoding "UTF8": 0xb3
DataError
def mark_messages(request, selection, mtype, recipient_db=None): """Mark a selection of messages as spam. :param str selection: message unique identifier :param str mtype: type of marking (spam or ham) """ if not manual_learning_enabled(request.user): return render_to_json_response({"status": "ok"}) if recipient_db is None: recipient_db = "user" if request.user.group == "SimpleUsers" else "global" selection = check_mail_id(request, selection) connector = get_connector() saclient = SpamassassinClient(request.user, recipient_db) for item in selection: rcpt, mail_id = item.split() content = connector.get_mail_content(mail_id) result = ( saclient.learn_spam(rcpt, content) if mtype == "spam" else saclient.learn_ham(rcpt, content) ) if not result: break connector.set_msgrcpt_status(rcpt, mail_id, mtype[0].upper()) if saclient.error is None: saclient.done() message = ungettext( "%(count)d message processed successfully", "%(count)d messages processed successfully", len(selection), ) % {"count": len(selection)} else: message = saclient.error status = 400 if saclient.error else 200 return render_to_json_response({"message": message, "reload": True}, status=status)
def mark_messages(request, selection, mtype, recipient_db=None): """Mark a selection of messages as spam. :param str selection: message unique identifier :param str mtype: type of marking (spam or ham) """ if not manual_learning_enabled(request.user): return render_to_json_response({"status": "ok"}) if recipient_db is None: recipient_db = "user" if request.user.group == "SimpleUsers" else "global" selection = check_mail_id(request, selection) connector = get_connector() saclient = SpamassassinClient(request.user, recipient_db) for item in selection: rcpt, mail_id = item.split() content = "".join( [msg.mail_text for msg in connector.get_mail_content(mail_id)] ) result = ( saclient.learn_spam(rcpt, content) if mtype == "spam" else saclient.learn_ham(rcpt, content) ) if not result: break connector.set_msgrcpt_status(rcpt, mail_id, mtype[0].upper()) if saclient.error is None: saclient.done() message = ungettext( "%(count)d message processed successfully", "%(count)d messages processed successfully", len(selection), ) % {"count": len(selection)} else: message = saclient.error status = 400 if saclient.error else 200 return render_to_json_response({"message": message, "reload": True}, status=status)
https://github.com/modoboa/modoboa/issues/677
Traceback (most recent call last): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py", line 36, in wrapped_f return f(request, *args, **kwargs) File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 135, in getmailcontent mail = SQLemail(mail_id, mformat="plain", links="0") File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py", line 23, in __init__ {"name": label, "value": self.get_header(self.msg, f)} File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py", line 44, in msg mail_text = "".join([qm.mail_text for qm in qmails]) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 96, in __iter__ self._fetch_all() File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 857, in _fetch_all self._result_cache = list(self.iterator()) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 220, in iterator for row in compiler.results_iter(): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 713, in results_iter for rows in self.execute_sql(MULTI): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 786, in execute_sql cursor.execute(sql, params) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py", line 53, in execute return self.cursor.execute(sql, params) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py", line 99, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py", line 53, in execute return self.cursor.execute(sql, params) DataError: invalid byte sequence for encoding "UTF8": 0xb3
DataError
def list_quotas(request): from modoboa.lib.dbutils import db_type sort_order, sort_dir = get_sort_order(request.GET, "address") mboxes = Mailbox.objects.get_for_admin( request.user, request.GET.get("searchquery", None) ) mboxes = mboxes.exclude(quota=0) if sort_order in ["address", "quota"]: mboxes = mboxes.order_by("%s%s" % (sort_dir, sort_order)) elif sort_order == "quota_value__bytes": where = "admin_mailbox.address||'@'||admin_domain.name" mboxes = mboxes.extra( select={"quota_value__bytes": "admin_quota.bytes"}, where=["admin_quota.username=%s" % where], tables=["admin_quota", "admin_domain"], order_by=["%s%s" % (sort_dir, sort_order)], ) elif sort_order == "quota_usage": where = "admin_mailbox.address||'@'||admin_domain.name" db_type = db_type() if db_type == "postgres": select = "(admin_quota.bytes::float / (CAST(admin_mailbox.quota AS BIGINT) * 1048576)) * 100" else: select = "admin_quota.bytes / (admin_mailbox.quota * 1048576) * 100" if db_type == "mysql": where = "CONCAT(admin_mailbox.address,'@',admin_domain.name)" mboxes = mboxes.extra( select={"quota_usage": select}, where=["admin_quota.username=%s" % where], tables=["admin_quota", "admin_domain"], order_by=["%s%s" % (sort_dir, sort_order)], ) else: raise BadRequest(_("Invalid request")) page = get_listing_page(mboxes, request.GET.get("page", 1)) context = {"headers": _render_to_string(request, "admin/quota_headers.html", {})} if page is None: context["length"] = 0 else: context["rows"] = _render_to_string( request, "admin/quotas.html", {"mboxes": page} ) context["pages"] = [page.number] return render_to_json_response(context)
def list_quotas(request): from modoboa.lib.dbutils import db_type sort_order, sort_dir = get_sort_order(request.GET, "address") mboxes = Mailbox.objects.get_for_admin( request.user, request.GET.get("searchquery", None) ) mboxes = mboxes.exclude(quota=0) if sort_order in ["address", "quota", "quota_value__bytes"]: mboxes = mboxes.order_by("%s%s" % (sort_dir, sort_order)) elif sort_order == "quota_usage": where = "admin_mailbox.address||'@'||admin_domain.name" db_type = db_type() if db_type == "postgres": select = "(admin_quota.bytes::float / (CAST(admin_mailbox.quota AS BIGINT) * 1048576)) * 100" else: select = "admin_quota.bytes / (admin_mailbox.quota * 1048576) * 100" if db_type == "mysql": where = "CONCAT(admin_mailbox.address,'@',admin_domain.name)" mboxes = mboxes.extra( select={"quota_usage": select}, where=["admin_quota.username=%s" % where], tables=["admin_quota", "admin_domain"], order_by=["%s%s" % (sort_dir, sort_order)], ) else: raise BadRequest(_("Invalid request")) page = get_listing_page(mboxes, request.GET.get("page", 1)) context = {"headers": _render_to_string(request, "admin/quota_headers.html", {})} if page is None: context["length"] = 0 else: context["rows"] = _render_to_string( request, "admin/quotas.html", {"mboxes": page} ) context["pages"] = [page.number] return render_to_json_response(context)
https://github.com/modoboa/modoboa/issues/679
Traceback (most recent call last): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/contrib/auth/decorators.py", line 22, in _wrapped_view return view_func(request, *args, **kwargs) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/contrib/auth/decorators.py", line 22, in _wrapped_view return view_func(request, *args, **kwargs) File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/admin/views/identity.py", line 107, in list_quotas "mboxes": page File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/lib/webutils.py", line 25, in _render_to_string context_instance=template.RequestContext(request)) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/loader.py", line 169, in render_to_string return t.render(context_instance) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/base.py", line 140, in render return self._render(context) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/base.py", line 134, in _render return self.nodelist.render(context) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/base.py", line 840, in render bit = self.render_node(node, context) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/base.py", line 854, in render_node return node.render(context) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/defaulttags.py", line 156, in render len_values = len(values) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/paginator.py", line 117, in __len__ return len(self.object_list) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 77, in __len__ self._fetch_all() File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 857, in _fetch_all self._result_cache = list(self.iterator()) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 220, in iterator for row in compiler.results_iter(): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 713, in results_iter for rows in self.execute_sql(MULTI): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 776, in execute_sql sql, params = self.as_sql() File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 84, in as_sql ordering, o_params, ordering_group_by = self.get_ordering() File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 403, in get_ordering self.query.get_meta(), default_order=asc): File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 437, in find_ordering_name field, cols, alias, joins, opts = self._setup_joins(pieces, opts, alias) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 470, in _setup_joins pieces, opts, alias) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/query.py", line 1363, in setup_joins names, opts, allow_many, allow_explicit_fk) File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/query.py", line 1283, in names_to_path "Choices are: %s" % (name, ", ".join(available))) FieldError: Cannot resolve keyword u'quota_value' into field. Choices are: accessrule, address, alias, armessage, dates, domain, id, mailboxoperation, migration, quota, use_domain_quota, user, usercalendar
FieldError
def messages_count(self, **kwargs): if self.count is None: filter = Q(chunk_ind=1) if self.mail_ids is not None: filter &= Q(mail__in=self.mail_ids) if self.filter: filter &= self.filter self.messages = Quarantine.objects.filter(filter).values( "mail__from_addr", "mail__msgrcpt__rid__email", "mail__subject", "mail__mail_id", "mail__time_num", "mail__msgrcpt__content", "mail__msgrcpt__bspam_level", "mail__msgrcpt__rs", ) if "order" in kwargs: order = kwargs["order"] sign = "" if order[0] == "-": sign = "-" order = order[1:] order = self.order_translation_table[order] self.messages = self.messages.order_by(sign + order) self.count = self.messages.count() return self.count
def messages_count(self, **kwargs): if self.count is None: filter = Q(chunk_ind=1) if self.mail_ids is not None: filter &= Q(mail__in=self.mail_ids) if self.filter: filter &= self.filter self.messages = Quarantine.objects.filter(filter).values( "mail__from_addr", "mail__msgrcpt__rid__email", "mail__subject", "mail__mail_id", "mail__time_num", "mail__msgrcpt__content", "mail__msgrcpt__bspam_level", "mail__msgrcpt__rs", ) if "order" in kwargs: order = kwargs["order"] sign = "" if order[0] == "-": sign = "-" order = order[1:] order = self.order_translation_table[order] self.messages = self.messages.order_by(sign + order) self.count = len(self.messages) return self.count
https://github.com/modoboa/modoboa/issues/534
Internal Server Error: /quarantine/process/ Traceback (most recent call last): File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view return view_func(request, *args, **kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 307, in process return release(request, ids) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py", line 30, in wrapped_f return f(request, *args, **kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 282, in release rcpt.save() File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py", line 546, in save force_update=force_update, update_fields=update_fields) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py", line 626, in save_base rows = manager.using(using).filter(pk=pk_val)._update(values) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py", line 605, in _update return query.get_compiler(self.db).execute_sql(None) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1020, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 846, in execute_sql cursor.execute(sql, params) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py", line 41, in execute return self.cursor.execute(sql, params) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 122, in execute six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 120, in execute return self.cursor.execute(query, args) File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue IntegrityError: (1062, "Duplicate entry '0-NTFOxSLhytYl-1' for key 'PRIMARY'")
IntegrityError
def fetch(self, start=None, stop=None, **kwargs): emails = [] for qm in self.messages[start - 1 : stop]: m = { "from": qm["mail__from_addr"], "to": qm["mail__msgrcpt__rid__email"], "subject": qm["mail__subject"], "mailid": qm["mail__mail_id"], "date": qm["mail__time_num"], "type": qm["mail__msgrcpt__content"], "score": qm["mail__msgrcpt__bspam_level"], } rs = qm["mail__msgrcpt__rs"] if rs == "D": continue elif rs == "": m["class"] = "unseen" elif rs == "R": m["img_rstatus"] = static_url("pics/release.png") elif rs == "p": m["class"] = "pending" emails.append(m) return emails
def fetch(self, start=None, stop=None, **kwargs): emails = [] for qm in self.messages[start - 1 : stop]: m = { "from": qm["mail__from_addr"], "to": qm["mail__msgrcpt__rid__email"], "subject": qm["mail__subject"], "mailid": qm["mail__mail_id"], "date": qm["mail__time_num"], "type": qm["mail__msgrcpt__content"], "score": qm["mail__msgrcpt__bspam_level"], } rs = qm["mail__msgrcpt__rs"] if rs == "": m["class"] = "unseen" elif rs == "R": m["img_rstatus"] = static_url("pics/release.png") elif rs == "p": m["class"] = "pending" emails.append(m) return emails
https://github.com/modoboa/modoboa/issues/534
Internal Server Error: /quarantine/process/ Traceback (most recent call last): File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view return view_func(request, *args, **kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 307, in process return release(request, ids) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py", line 30, in wrapped_f return f(request, *args, **kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 282, in release rcpt.save() File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py", line 546, in save force_update=force_update, update_fields=update_fields) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py", line 626, in save_base rows = manager.using(using).filter(pk=pk_val)._update(values) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py", line 605, in _update return query.get_compiler(self.db).execute_sql(None) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1020, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 846, in execute_sql cursor.execute(sql, params) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py", line 41, in execute return self.cursor.execute(sql, params) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 122, in execute six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 120, in execute return self.cursor.execute(query, args) File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue IntegrityError: (1062, "Duplicate entry '0-NTFOxSLhytYl-1' for key 'PRIMARY'")
IntegrityError
def viewmail(request, mail_id): rcpt = request.GET["rcpt"] if request.user.mailbox_set.count(): mb = Mailbox.objects.get(user=request.user) if rcpt in mb.alias_addresses: get_wrapper().set_msgrcpt_status(rcpt, mail_id, "V") content = Template(""" <iframe src="{{ url }}" id="mailcontent"></iframe> """).render(Context({"url": reverse(getmailcontent, args=[mail_id])})) menu = viewm_menu(mail_id, rcpt) ctx = getctx("ok", menu=menu, listing=content) request.session["location"] = "viewmail" return render_to_json_response(ctx)
def viewmail(request, mail_id): rcpt = request.GET["rcpt"] if request.user.mailbox_set.count(): mb = Mailbox.objects.get(user=request.user) if rcpt in mb.alias_addresses: msgrcpt = get_wrapper().get_recipient_message(rcpt, mail_id) msgrcpt.rs = "V" msgrcpt.save() content = Template(""" <iframe src="{{ url }}" id="mailcontent"></iframe> """).render(Context({"url": reverse(getmailcontent, args=[mail_id])})) menu = viewm_menu(mail_id, rcpt) ctx = getctx("ok", menu=menu, listing=content) request.session["location"] = "viewmail" return render_to_json_response(ctx)
https://github.com/modoboa/modoboa/issues/534
Internal Server Error: /quarantine/process/ Traceback (most recent call last): File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view return view_func(request, *args, **kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 307, in process return release(request, ids) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py", line 30, in wrapped_f return f(request, *args, **kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 282, in release rcpt.save() File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py", line 546, in save force_update=force_update, update_fields=update_fields) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py", line 626, in save_base rows = manager.using(using).filter(pk=pk_val)._update(values) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py", line 605, in _update return query.get_compiler(self.db).execute_sql(None) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1020, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 846, in execute_sql cursor.execute(sql, params) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py", line 41, in execute return self.cursor.execute(sql, params) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 122, in execute six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 120, in execute return self.cursor.execute(query, args) File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue IntegrityError: (1062, "Duplicate entry '0-NTFOxSLhytYl-1' for key 'PRIMARY'")
IntegrityError
def delete_selfservice(request, mail_id): rcpt = request.GET.get("rcpt", None) if rcpt is None: raise BadRequest(_("Invalid request")) try: get_wrapper().set_msgrcpt_status(rcpt, mail_id, "D") except Msgrcpt.DoesNotExist: raise BadRequest(_("Invalid request")) return render_to_json_response(_("Message deleted"))
def delete_selfservice(request, mail_id): rcpt = request.GET.get("rcpt", None) if rcpt is None: raise BadRequest(_("Invalid request")) try: msgrcpt = get_wrapper().get_recipient_message(rcpt, mail_id) msgrcpt.rs = "D" msgrcpt.save() except Msgrcpt.DoesNotExist: raise BadRequest(_("Invalid request")) return render_to_json_response(_("Message deleted"))
https://github.com/modoboa/modoboa/issues/534
Internal Server Error: /quarantine/process/ Traceback (most recent call last): File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view return view_func(request, *args, **kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 307, in process return release(request, ids) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py", line 30, in wrapped_f return f(request, *args, **kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 282, in release rcpt.save() File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py", line 546, in save force_update=force_update, update_fields=update_fields) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py", line 626, in save_base rows = manager.using(using).filter(pk=pk_val)._update(values) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py", line 605, in _update return query.get_compiler(self.db).execute_sql(None) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1020, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 846, in execute_sql cursor.execute(sql, params) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py", line 41, in execute return self.cursor.execute(sql, params) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 122, in execute six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 120, in execute return self.cursor.execute(query, args) File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue IntegrityError: (1062, "Duplicate entry '0-NTFOxSLhytYl-1' for key 'PRIMARY'")
IntegrityError
def delete(request, mail_id): """Delete message selection. :param str mail_id: message unique identifier """ mail_id = check_mail_id(request, mail_id) wrapper = get_wrapper() mb = ( Mailbox.objects.get(user=request.user) if request.user.group == "SimpleUsers" else None ) for mid in mail_id: r, i = mid.split() if mb is not None and r != mb.full_address and not r in mb.alias_addresses: continue wrapper.set_msgrcpt_status(r, i, "D") message = ungettext( "%(count)d message deleted successfully", "%(count)d messages deleted successfully", len(mail_id), ) % {"count": len(mail_id)} return ajax_response( request, respmsg=message, url=QuarantineNavigationParameters(request).back_to_listing(), )
def delete(request, mail_id): """Delete message selection. :param str mail_id: message unique identifier """ mail_id = check_mail_id(request, mail_id) wrapper = get_wrapper() mb = ( Mailbox.objects.get(user=request.user) if request.user.group == "SimpleUsers" else None ) for mid in mail_id: r, i = mid.split() if mb is not None and r != mb.full_address and not r in mb.alias_addresses: continue msgrcpt = wrapper.get_recipient_message(r, i) msgrcpt.rs = "D" msgrcpt.save() message = ungettext( "%(count)d message deleted successfully", "%(count)d messages deleted successfully", len(mail_id), ) % {"count": len(mail_id)} return ajax_response( request, respmsg=message, url=QuarantineNavigationParameters(request).back_to_listing(), )
https://github.com/modoboa/modoboa/issues/534
Internal Server Error: /quarantine/process/ Traceback (most recent call last): File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view return view_func(request, *args, **kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 307, in process return release(request, ids) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py", line 30, in wrapped_f return f(request, *args, **kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 282, in release rcpt.save() File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py", line 546, in save force_update=force_update, update_fields=update_fields) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py", line 626, in save_base rows = manager.using(using).filter(pk=pk_val)._update(values) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py", line 605, in _update return query.get_compiler(self.db).execute_sql(None) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1020, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 846, in execute_sql cursor.execute(sql, params) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py", line 41, in execute return self.cursor.execute(sql, params) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 122, in execute six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 120, in execute return self.cursor.execute(query, args) File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue IntegrityError: (1062, "Duplicate entry '0-NTFOxSLhytYl-1' for key 'PRIMARY'")
IntegrityError
def release_selfservice(request, mail_id): rcpt = request.GET.get("rcpt", None) secret_id = request.GET.get("secret_id", None) if rcpt is None or secret_id is None: raise BadRequest(_("Invalid request")) wrapper = get_wrapper() try: msgrcpt = wrapper.get_recipient_message(rcpt, mail_id) except Msgrcpt.DoesNotExist: raise BadRequest(_("Invalid request")) if secret_id != msgrcpt.mail.secret_id: raise BadRequest(_("Invalid request")) if parameters.get_admin("USER_CAN_RELEASE") == "no": wrapper.set_msgrcpt_status(rcpt, mail_id, "p") msg = _("Request sent") else: amr = AMrelease() result = amr.sendreq(mail_id, secret_id, rcpt) if result: wrapper.set_msgrcpt_status(rcpt, mail_id, "R") msg = _("Message released") else: raise BadRequest(result) return render_to_json_response(msg)
def release_selfservice(request, mail_id): rcpt = request.GET.get("rcpt", None) secret_id = request.GET.get("secret_id", None) if rcpt is None or secret_id is None: raise BadRequest(_("Invalid request")) try: msgrcpt = get_wrapper().get_recipient_message(rcpt, mail_id) except Msgrcpt.DoesNotExist: raise BadRequest(_("Invalid request")) if secret_id != msgrcpt.mail.secret_id: raise BadRequest(_("Invalid request")) if parameters.get_admin("USER_CAN_RELEASE") == "no": msgrcpt.rs = "p" msg = _("Request sent") else: amr = AMrelease() result = amr.sendreq(mail_id, secret_id, rcpt) if result: rcpt.rs = "R" msg = _("Message released") else: raise BadRequest(result) msgrcpt.save() return render_to_json_response(msg)
https://github.com/modoboa/modoboa/issues/534
Internal Server Error: /quarantine/process/ Traceback (most recent call last): File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view return view_func(request, *args, **kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 307, in process return release(request, ids) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py", line 30, in wrapped_f return f(request, *args, **kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 282, in release rcpt.save() File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py", line 546, in save force_update=force_update, update_fields=update_fields) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py", line 626, in save_base rows = manager.using(using).filter(pk=pk_val)._update(values) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py", line 605, in _update return query.get_compiler(self.db).execute_sql(None) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1020, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 846, in execute_sql cursor.execute(sql, params) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py", line 41, in execute return self.cursor.execute(sql, params) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 122, in execute six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 120, in execute return self.cursor.execute(query, args) File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue IntegrityError: (1062, "Duplicate entry '0-NTFOxSLhytYl-1' for key 'PRIMARY'")
IntegrityError
def release(request, mail_id): """Release message selection. :param str mail_id: message unique identifier """ mail_id = check_mail_id(request, mail_id) msgrcpts = [] wrapper = get_wrapper() mb = ( Mailbox.objects.get(user=request.user) if request.user.group == "SimpleUsers" else None ) for mid in mail_id: r, i = mid.split() if mb is not None and r != mb.full_address and not r in mb.alias_addresses: continue msgrcpts += [wrapper.get_recipient_message(r, i)] if mb is not None and parameters.get_admin("USER_CAN_RELEASE") == "no": for msgrcpt in msgrcpts: wrapper.set_msgrcpt_status(msgrcpt.rid.email, msgrcpt.mail.mail_id, "p") message = ungettext( "%(count)d request sent", "%(count)d requests sent", len(mail_id) ) % {"count": len(mail_id)} return ajax_response( request, "ok", respmsg=message, url=QuarantineNavigationParameters(request).back_to_listing(), ) amr = AMrelease() error = None for rcpt in msgrcpts: result = amr.sendreq(rcpt.mail.mail_id, rcpt.mail.secret_id, rcpt.rid.email) if result: wrapper.set_msgrcpt_status(rcpt.rid.email, rcpt.mail.mail_id, "R") else: error = result break if not error: message = ungettext( "%(count)d message released successfully", "%(count)d messages released successfully", len(mail_id), ) % {"count": len(mail_id)} else: message = error return ajax_response( request, "ko" if error else "ok", respmsg=message, url=QuarantineNavigationParameters(request).back_to_listing(), )
def release(request, mail_id): """Release message selection. :param str mail_id: message unique identifier """ mail_id = check_mail_id(request, mail_id) msgrcpts = [] wrapper = get_wrapper() mb = ( Mailbox.objects.get(user=request.user) if request.user.group == "SimpleUsers" else None ) for mid in mail_id: r, i = mid.split() if mb is not None and r != mb.full_address and not r in mb.alias_addresses: continue msgrcpts += [wrapper.get_recipient_message(r, i)] if mb is not None and parameters.get_admin("USER_CAN_RELEASE") == "no": # FIXME : can't use this syntax because extra SQL (using # .extra() for postgres) is not propagated (the 'tables' # parameter is lost somewhere...) # # msgrcpts.update(rs='p') for msgrcpt in msgrcpts: msgrcpt.rs = "p" msgrcpt.save() message = ungettext( "%(count)d request sent", "%(count)d requests sent", len(mail_id) ) % {"count": len(mail_id)} return ajax_response( request, "ok", respmsg=message, url=QuarantineNavigationParameters(request).back_to_listing(), ) amr = AMrelease() error = None for rcpt in msgrcpts: result = amr.sendreq(rcpt.mail.mail_id, rcpt.mail.secret_id, rcpt.rid.email) if result: rcpt.rs = "R" rcpt.save() else: error = result break if not error: message = ungettext( "%(count)d message released successfully", "%(count)d messages released successfully", len(mail_id), ) % {"count": len(mail_id)} else: message = error return ajax_response( request, "ko" if error else "ok", respmsg=message, url=QuarantineNavigationParameters(request).back_to_listing(), )
https://github.com/modoboa/modoboa/issues/534
Internal Server Error: /quarantine/process/ Traceback (most recent call last): File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view return view_func(request, *args, **kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 307, in process return release(request, ids) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py", line 30, in wrapped_f return f(request, *args, **kwargs) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 282, in release rcpt.save() File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py", line 546, in save force_update=force_update, update_fields=update_fields) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py", line 626, in save_base rows = manager.using(using).filter(pk=pk_val)._update(values) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py", line 605, in _update return query.get_compiler(self.db).execute_sql(None) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1020, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 846, in execute_sql cursor.execute(sql, params) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py", line 41, in execute return self.cursor.execute(sql, params) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 122, in execute six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) File "/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 120, in execute return self.cursor.execute(query, args) File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue IntegrityError: (1062, "Duplicate entry '0-NTFOxSLhytYl-1' for key 'PRIMARY'")
IntegrityError
def get_password_hasher(scheme): """Retrieve the hasher corresponding to :keyword:`scheme`. If no class is found, `PLAINHasher` is returned. :param str scheme: a valid scheme name :rtype: PasswordHasher sub class :return: The hasher class """ try: scheme = scheme.replace("-", "") hasher = globals()["%sHasher" % scheme.upper()] except KeyError: hasher = PLAINHasher return hasher
def get_password_hasher(scheme): """Retrieve the hasher corresponding to :keyword:`scheme`. If no class is found, `PLAINHasher` is returned. :param str scheme: a valid scheme name :rtype: PasswordHasher sub class :return: The hasher class """ try: scheme = scheme.replace("-", "") hasher = globals()["%sHasher" % scheme] except AttributeError: hasher = PLAINHasher return hasher
https://github.com/modoboa/modoboa/issues/514
Traceback (most recent call last): File "/srv/python-envs/service/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/srv/python-envs/service/lib/python2.7/site-packages/django/views/decorators/cache.py", line 89, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/srv/python-envs/service/lib/python2.7/site-packages/modoboa-1.1.0-py2.7.egg/modoboa/core/views/auth.py", line 20, in dologin password=form.cleaned_data["password"]) File "/srv/python-envs/service/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 60, in authenticate user = backend.authenticate(**credentials) File "/srv/python-envs/service/lib/python2.7/site-packages/modoboa-1.1.0-py2.7.egg/modoboa/lib/authbackends.py", line 14, in authenticate if not user.check_password(password): File "/srv/python-envs/service/lib/python2.7/site-packages/modoboa-1.1.0-py2.7.egg/modoboa/core/models.py", line 134, in check_password hasher = get_password_hasher(scheme) File "/srv/python-envs/service/lib/python2.7/site-packages/modoboa-1.1.0-py2.7.egg/modoboa/core/password_hashers/__init__.py", line 23, in get_password_hasher hasher = globals()['%sHasher' % scheme] KeyError: u'plainHasher'
KeyError
def print_summary(samples, prob=0.9, group_by_chain=True): """ Prints a summary table displaying diagnostics of ``samples`` from the posterior. The diagnostics displayed are mean, standard deviation, median, the 90% Credibility Interval, :func:`~pyro.ops.stats.effective_sample_size`, :func:`~pyro.ops.stats.split_gelman_rubin`. :param dict samples: dictionary of samples keyed by site name. :param float prob: the probability mass of samples within the credibility interval. :param bool group_by_chain: If True, each variable in `samples` will be treated as having shape `num_chains x num_samples x sample_shape`. Otherwise, the corresponding shape will be `num_samples x sample_shape` (i.e. without chain dimension). """ if len(samples) == 0: return summary_dict = summary(samples, prob, group_by_chain) row_names = { k: k + "[" + ",".join(map(lambda x: str(x - 1), v.shape[2:])) + "]" for k, v in samples.items() } max_len = max(max(map(lambda x: len(x), row_names.values())), 10) name_format = "{:>" + str(max_len) + "}" header_format = name_format + " {:>9}" * 7 columns = [""] + list(list(summary_dict.values())[0].keys()) print() print(header_format.format(*columns)) row_format = name_format + " {:>9.2f}" * 7 for name, stats_dict in summary_dict.items(): shape = stats_dict["mean"].shape if len(shape) == 0: print(row_format.format(name, *stats_dict.values())) else: for idx in product(*map(range, shape)): idx_str = "[{}]".format(",".join(map(str, idx))) print( row_format.format( name + idx_str, *[v[idx] for v in stats_dict.values()] ) ) print()
def print_summary(samples, prob=0.9, group_by_chain=True): """ Prints a summary table displaying diagnostics of ``samples`` from the posterior. The diagnostics displayed are mean, standard deviation, median, the 90% Credibility Interval, :func:`~pyro.ops.stats.effective_sample_size`, :func:`~pyro.ops.stats.split_gelman_rubin`. :param dict samples: dictionary of samples keyed by site name. :param float prob: the probability mass of samples within the credibility interval. :param bool group_by_chain: If True, each variable in `samples` will be treated as having shape `num_chains x num_samples x sample_shape`. Otherwise, the corresponding shape will be `num_samples x sample_shape` (i.e. without chain dimension). """ summary_dict = summary(samples, prob, group_by_chain) row_names = { k: k + "[" + ",".join(map(lambda x: str(x - 1), v.shape[2:])) + "]" for k, v in samples.items() } max_len = max(max(map(lambda x: len(x), row_names.values())), 10) name_format = "{:>" + str(max_len) + "}" header_format = name_format + " {:>9}" * 7 columns = [""] + list(list(summary_dict.values())[0].keys()) print() print(header_format.format(*columns)) row_format = name_format + " {:>9.2f}" * 7 for name, stats_dict in summary_dict.items(): shape = stats_dict["mean"].shape if len(shape) == 0: print(row_format.format(name, *stats_dict.values())) else: for idx in product(*map(range, shape)): idx_str = "[{}]".format(",".join(map(str, idx))) print( row_format.format( name + idx_str, *[v[idx] for v in stats_dict.values()] ) ) print()
https://github.com/pyro-ppl/pyro/issues/2607
Sample: 100%|██████████| 15/15 [00:00, 1853.70it/s, step size=1.00e+00, acc. prob=1.000] prior: tensor([0.2000, 0.2000, 0.2000, 0.2000, 0.2000]) Num elves: tensor(4) Rocks: 16, Logs: 24 Rocks obs: 4, Logs obs: 6 prior: tensor([0.2000, 0.2000, 0.2000, 0.2000, 0.2000]) Num elves: tensor([0, 1, 2, 3, 4]) Rocks: tensor([ 0, 4, 8, 12, 16]), Logs: tensor([ 0, 6, 12, 18, 24]) Rocks obs: 4, Logs obs: 6 prior: tensor([0.2000, 0.2000, 0.2000, 0.2000, 0.2000]) Num elves: tensor([0, 1, 2, 3, 4]) Rocks: tensor([ 0, 4, 8, 12, 16]), Logs: tensor([ 0, 6, 12, 18, 24]) Rocks obs: 4, Logs obs: 6 Traceback (most recent call last): File "/Users/jmugan/Dropbox/code/python_examples/jwm_pyro/elves.py", line 75, in <module> mcmc.summary(prob=.5) File "/Users/jmugan/anaconda3/lib/python3.7/site-packages/pyro/infer/mcmc/api.py", line 485, in summary print_summary(self._samples, prob=prob) File "/Users/jmugan/anaconda3/lib/python3.7/site-packages/pyro/infer/mcmc/util.py", line 522, in print_summary max_len = max(max(map(lambda x: len(x), row_names.values())), 10) ValueError: max() arg is an empty sequence Process finished with exit code 1
ValueError
def get_dependent_plate_dims(sites): """ Return a list of dims for plates that are not common to all sites. """ plate_sets = [ site["cond_indep_stack"] for site in sites if site["type"] == "sample" ] all_plates = set().union(*plate_sets) common_plates = all_plates.intersection(*plate_sets) sum_plates = all_plates - common_plates sum_dims = list(sorted(f.dim for f in sum_plates if f.dim is not None)) return sum_dims
def get_dependent_plate_dims(sites): """ Return a list of dims for plates that are not common to all sites. """ plate_sets = [ site["cond_indep_stack"] for site in sites if site["type"] == "sample" ] all_plates = set().union(*plate_sets) common_plates = all_plates.intersection(*plate_sets) sum_plates = all_plates - common_plates sum_dims = list(sorted(f.dim for f in sum_plates)) return sum_dims
https://github.com/pyro-ppl/pyro/issues/2361
3.8.1 (default, Jan 8 2020, 16:15:59) [Clang 4.0.1 (tags/RELEASE_401/final)] 1.4.0 1.3.0 2.4235687255859375 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-6865281f40fd> in <module> 15 16 elbo = pyro.infer.RenyiELBO() ---> 17 print(elbo.loss(model, guide, torch.randn([3]))) ~/miniconda3/envs/pDCM-dev/lib/python3.8/site-packages/torch/autograd/grad_mode.py in decorate_no_grad(*args, **kwargs) 47 def decorate_no_grad(*args, **kwargs): 48 with self: ---> 49 return func(*args, **kwargs) 50 return decorate_no_grad 51 ~/miniconda3/envs/pDCM-dev/lib/python3.8/site-packages/pyro/infer/renyi_elbo.py in loss(self, model, guide, *args, **kwargs) 96 for model_trace, guide_trace in self._get_traces(model, guide, args, kwargs): 97 elbo_particle = 0. ---> 98 sum_dims = get_dependent_plate_dims(model_trace.nodes.values()) 99 100 # compute elbo ~/miniconda3/envs/pDCM-dev/lib/python3.8/site-packages/pyro/infer/util.py in get_dependent_plate_dims(sites) 114 common_plates = all_plates.intersection(*plate_sets) 115 sum_plates = all_plates - common_plates --> 116 sum_dims = list(sorted(f.dim for f in sum_plates)) 117 return sum_dims 118 TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'
TypeError
def run(self, *args, **kwargs): self._args, self._kwargs = args, kwargs num_samples = [0] * self.num_chains z_flat_acc = [[] for _ in range(self.num_chains)] with pyro.validation_enabled(not self.disable_validation): for x, chain_id in self.sampler.run(*args, **kwargs): if num_samples[chain_id] == 0: num_samples[chain_id] += 1 z_structure = x elif num_samples[chain_id] == self.num_samples + 1: self._diagnostics[chain_id] = x else: num_samples[chain_id] += 1 if self.num_chains > 1: x_cloned = x.clone() del x else: x_cloned = x z_flat_acc[chain_id].append(x_cloned) z_flat_acc = torch.stack([torch.stack(l) for l in z_flat_acc]) # unpack latent pos = 0 z_acc = z_structure.copy() for k in sorted(z_structure): shape = z_structure[k] next_pos = pos + shape.numel() z_acc[k] = z_flat_acc[:, :, pos:next_pos].reshape( (self.num_chains, self.num_samples) + shape ) pos = next_pos assert pos == z_flat_acc.shape[-1] # If transforms is not explicitly provided, infer automatically using # model args, kwargs. if self.transforms is None: # Use `kernel.transforms` when available if hasattr(self.kernel, "transforms") and self.kernel.transforms is not None: self.transforms = self.kernel.transforms # Else, get transforms from model (e.g. in multiprocessing). elif self.kernel.model: _, _, self.transforms, _ = initialize_model( self.kernel.model, model_args=args, model_kwargs=kwargs ) # Assign default value else: self.transforms = {} # transform samples back to constrained space for name, transform in self.transforms.items(): z_acc[name] = transform.inv(z_acc[name]) self._samples = z_acc # terminate the sampler (shut down worker processes) self.sampler.terminate(True)
def run(self, *args, **kwargs): self._args, self._kwargs = args, kwargs num_samples = [0] * self.num_chains z_flat_acc = [[] for _ in range(self.num_chains)] with pyro.validation_enabled(not self.disable_validation): for x, chain_id in self.sampler.run(*args, **kwargs): if num_samples[chain_id] == 0: num_samples[chain_id] += 1 z_structure = x elif num_samples[chain_id] == self.num_samples + 1: self._diagnostics[chain_id] = x else: num_samples[chain_id] += 1 if self.num_chains > 1: x_cloned = x.clone() del x else: x_cloned = x z_flat_acc[chain_id].append(x_cloned) z_flat_acc = torch.stack([torch.stack(l) for l in z_flat_acc]) # unpack latent pos = 0 z_acc = z_structure.copy() for k in sorted(z_structure): shape = z_structure[k] next_pos = pos + shape.numel() z_acc[k] = z_flat_acc[:, :, pos:next_pos].reshape( (self.num_chains, self.num_samples) + shape ) pos = next_pos assert pos == z_flat_acc.shape[-1] # If transforms is not explicitly provided, infer automatically using # model args, kwargs. if self.transforms is None: if hasattr(self.kernel, "transforms"): if self.kernel.transforms is not None: self.transforms = self.kernel.transforms elif self.kernel.model: _, _, self.transforms, _ = initialize_model( self.kernel.model, model_args=args, model_kwargs=kwargs ) else: self.transforms = {} # transform samples back to constrained space for name, transform in self.transforms.items(): z_acc[name] = transform.inv(z_acc[name]) self._samples = z_acc # terminate the sampler (shut down worker processes) self.sampler.terminate(True)
https://github.com/pyro-ppl/pyro/issues/2272
AttributeError Traceback (most recent call last) <ipython-input-13-5a1da811afef> in <module>() 8 mcmc = MCMC(nuts_kernel, num_samples=25, warmup_steps=100, num_chains=cpu_count) 9 ---> 10 mcmc.run(y) ~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/pyro/poutine/messenger.py in _context_wrap(context, fn, *args, **kwargs) 9 def _context_wrap(context, fn, *args, **kwargs): 10 with context: ---> 11 return fn(*args, **kwargs) 12 13 ~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/pyro/infer/mcmc/api.py in run(self, *args, **kwargs) 397 398 # transform samples back to constrained space --> 399 for name, transform in self.transforms.items(): 400 z_acc[name] = transform.inv(z_acc[name]) 401 self._samples = z_acc AttributeError: 'NoneType' object has no attribute 'items'
AttributeError
def get_posterior(self, *args, **kwargs): """ Returns a MultivariateNormal posterior distribution. """ loc = pyro.param("{}_loc".format(self.prefix), self._init_loc) scale_tril = pyro.param( "{}_scale_tril".format(self.prefix), lambda: eye_like(loc, self.latent_dim), constraint=constraints.lower_cholesky, ) return dist.MultivariateNormal(loc, scale_tril=scale_tril)
def get_posterior(self, *args, **kwargs): """ Returns a MultivariateNormal posterior distribution. """ loc = pyro.param("{}_loc".format(self.prefix), lambda: torch.zeros(self.latent_dim)) scale_tril = pyro.param( "{}_scale_tril".format(self.prefix), lambda: torch.eye(self.latent_dim), constraint=constraints.lower_cholesky, ) return dist.MultivariateNormal(loc, scale_tril=scale_tril)
https://github.com/pyro-ppl/pyro/issues/1850
Traceback (most recent call last): File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\IPython\core\interactiveshell.py", line 3265, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-6-68d49e4377f9>", line 26, in <module> train() File "<ipython-input-6-68d49e4377f9>", line 23, in train svi.step(xs, prior_loc, prior_scale) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\svi.py", line 99, in step loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\trace_elbo.py", line 136, in loss_and_grads surrogate_loss_particle.backward(retain_graph=self.retain_graph) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\tensor.py", line 107, in backward torch.autograd.backward(self, gradient, retain_graph, create_graph) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\autograd\__init__.py", line 93, in backward allow_unreachable=True) # allow_unreachable flag RuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor
RuntimeError
def get_posterior(self, *args, **kwargs): """ Returns a diagonal Normal posterior distribution. """ loc = pyro.param("{}_loc".format(self.prefix), self._init_loc) scale = pyro.param( "{}_scale".format(self.prefix), lambda: loc.new_ones(self.latent_dim), constraint=constraints.positive, ) return dist.Normal(loc, scale).to_event(1)
def get_posterior(self, *args, **kwargs): """ Returns a diagonal Normal posterior distribution. """ loc = pyro.param("{}_loc".format(self.prefix), lambda: torch.zeros(self.latent_dim)) scale = pyro.param( "{}_scale".format(self.prefix), lambda: torch.ones(self.latent_dim), constraint=constraints.positive, ) return dist.Normal(loc, scale).to_event(1)
https://github.com/pyro-ppl/pyro/issues/1850
Traceback (most recent call last): File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\IPython\core\interactiveshell.py", line 3265, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-6-68d49e4377f9>", line 26, in <module> train() File "<ipython-input-6-68d49e4377f9>", line 23, in train svi.step(xs, prior_loc, prior_scale) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\svi.py", line 99, in step loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\trace_elbo.py", line 136, in loss_and_grads surrogate_loss_particle.backward(retain_graph=self.retain_graph) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\tensor.py", line 107, in backward torch.autograd.backward(self, gradient, retain_graph, create_graph) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\autograd\__init__.py", line 93, in backward allow_unreachable=True) # allow_unreachable flag RuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor
RuntimeError
def __init__(self, model, prefix="auto", init_loc_fn=init_to_median, rank=1): if not isinstance(rank, numbers.Number) or not rank > 0: raise ValueError("Expected rank > 0 but got {}".format(rank)) self.rank = rank super(AutoLowRankMultivariateNormal, self).__init__( model, prefix=prefix, init_loc_fn=init_loc_fn )
def __init__(self, model, prefix="auto", rank=1): if not isinstance(rank, numbers.Number) or not rank > 0: raise ValueError("Expected rank > 0 but got {}".format(rank)) self.rank = rank super(AutoLowRankMultivariateNormal, self).__init__(model, prefix)
https://github.com/pyro-ppl/pyro/issues/1850
Traceback (most recent call last): File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\IPython\core\interactiveshell.py", line 3265, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-6-68d49e4377f9>", line 26, in <module> train() File "<ipython-input-6-68d49e4377f9>", line 23, in train svi.step(xs, prior_loc, prior_scale) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\svi.py", line 99, in step loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\trace_elbo.py", line 136, in loss_and_grads surrogate_loss_particle.backward(retain_graph=self.retain_graph) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\tensor.py", line 107, in backward torch.autograd.backward(self, gradient, retain_graph, create_graph) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\autograd\__init__.py", line 93, in backward allow_unreachable=True) # allow_unreachable flag RuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor
RuntimeError
def get_posterior(self, *args, **kwargs): """ Returns a LowRankMultivariateNormal posterior distribution. """ loc = pyro.param("{}_loc".format(self.prefix), self._init_loc) factor = pyro.param( "{}_cov_factor".format(self.prefix), lambda: loc.new_empty(self.latent_dim, self.rank).normal_( 0, (0.5 / self.rank) ** 0.5 ), ) diagonal = pyro.param( "{}_cov_diag".format(self.prefix), lambda: loc.new_full((self.latent_dim,), 0.5), constraint=constraints.positive, ) return dist.LowRankMultivariateNormal(loc, factor, diagonal)
def get_posterior(self, *args, **kwargs): """ Returns a LowRankMultivariateNormal posterior distribution. """ loc = pyro.param("{}_loc".format(self.prefix), lambda: torch.zeros(self.latent_dim)) factor = pyro.param( "{}_cov_factor".format(self.prefix), lambda: torch.randn(self.latent_dim, self.rank) * (0.5 / self.rank) ** 0.5, ) diagonal = pyro.param( "{}_cov_diag".format(self.prefix), lambda: torch.ones(self.latent_dim) * 0.5, constraint=constraints.positive, ) return dist.LowRankMultivariateNormal(loc, factor, diagonal)
https://github.com/pyro-ppl/pyro/issues/1850
Traceback (most recent call last): File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\IPython\core\interactiveshell.py", line 3265, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-6-68d49e4377f9>", line 26, in <module> train() File "<ipython-input-6-68d49e4377f9>", line 23, in train svi.step(xs, prior_loc, prior_scale) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\svi.py", line 99, in step loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\trace_elbo.py", line 136, in loss_and_grads surrogate_loss_particle.backward(retain_graph=self.retain_graph) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\tensor.py", line 107, in backward torch.autograd.backward(self, gradient, retain_graph, create_graph) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\autograd\__init__.py", line 93, in backward allow_unreachable=True) # allow_unreachable flag RuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor
RuntimeError
def __init__(self, model, hidden_dim=None, prefix="auto", init_loc_fn=init_to_median): self.hidden_dim = hidden_dim self.arn = None super(AutoIAFNormal, self).__init__(model, prefix=prefix, init_loc_fn=init_loc_fn)
def __init__(self, model, hidden_dim=None, prefix="auto"): self.hidden_dim = hidden_dim self.arn = None super(AutoIAFNormal, self).__init__(model, prefix)
https://github.com/pyro-ppl/pyro/issues/1850
Traceback (most recent call last): File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\IPython\core\interactiveshell.py", line 3265, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-6-68d49e4377f9>", line 26, in <module> train() File "<ipython-input-6-68d49e4377f9>", line 23, in train svi.step(xs, prior_loc, prior_scale) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\svi.py", line 99, in step loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\trace_elbo.py", line 136, in loss_and_grads surrogate_loss_particle.backward(retain_graph=self.retain_graph) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\tensor.py", line 107, in backward torch.autograd.backward(self, gradient, retain_graph, create_graph) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\autograd\__init__.py", line 93, in backward allow_unreachable=True) # allow_unreachable flag RuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor
RuntimeError
def get_posterior(self, *args, **kwargs): """ Returns a Delta posterior distribution for MAP inference. """ loc = pyro.param("{}_loc".format(self.prefix), self._init_loc) return dist.Delta(loc).to_event(1)
def get_posterior(self, *args, **kwargs): """ Returns a Delta posterior distribution for MAP inference. """ loc = pyro.param("{}_loc".format(self.prefix), lambda: torch.zeros(self.latent_dim)) return dist.Delta(loc).to_event(1)
https://github.com/pyro-ppl/pyro/issues/1850
Traceback (most recent call last): File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\IPython\core\interactiveshell.py", line 3265, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-6-68d49e4377f9>", line 26, in <module> train() File "<ipython-input-6-68d49e4377f9>", line 23, in train svi.step(xs, prior_loc, prior_scale) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\svi.py", line 99, in step loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\trace_elbo.py", line 136, in loss_and_grads surrogate_loss_particle.backward(retain_graph=self.retain_graph) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\tensor.py", line 107, in backward torch.autograd.backward(self, gradient, retain_graph, create_graph) File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\autograd\__init__.py", line 93, in backward allow_unreachable=True) # allow_unreachable flag RuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor
RuntimeError
def main(args): baseball_dataset = pd.read_csv(DATA_URL, "\t") train, _, player_names = train_test_split(baseball_dataset) at_bats, hits = train[:, 0], train[:, 1] nuts_kernel = NUTS(conditioned_model) logging.info("Original Dataset:") logging.info(baseball_dataset) # (1) Full Pooling Model posterior_fully_pooled = MCMC( nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps ).run(fully_pooled, at_bats, hits) logging.info("\nModel: Fully Pooled") logging.info("===================") logging.info("\nphi:") logging.info( summary(posterior_fully_pooled, sites=["phi"], player_names=player_names)["phi"] ) posterior_predictive = TracePredictive( fully_pooled, posterior_fully_pooled, num_samples=args.num_samples ) sample_posterior_predictive(posterior_predictive, baseball_dataset) evaluate_log_predictive_density( fully_pooled, posterior_fully_pooled, baseball_dataset ) # (2) No Pooling Model posterior_not_pooled = MCMC( nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps ).run(not_pooled, at_bats, hits) logging.info("\nModel: Not Pooled") logging.info("=================") logging.info("\nphi:") logging.info( summary(posterior_not_pooled, sites=["phi"], player_names=player_names)["phi"] ) posterior_predictive = TracePredictive( not_pooled, posterior_not_pooled, num_samples=args.num_samples ) sample_posterior_predictive(posterior_predictive, baseball_dataset) evaluate_log_predictive_density(not_pooled, posterior_not_pooled, baseball_dataset) # (3) Partially Pooled Model # TODO: remove once htps://github.com/uber/pyro/issues/1458 is resolved if "CI" not in os.environ: posterior_partially_pooled = MCMC( nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps ).run(partially_pooled, at_bats, hits) logging.info("\nModel: Partially Pooled") logging.info("=======================") logging.info("\nphi:") logging.info( summary( posterior_partially_pooled, sites=["phi"], player_names=player_names )["phi"] ) posterior_predictive = TracePredictive( partially_pooled, posterior_partially_pooled, num_samples=args.num_samples ) sample_posterior_predictive(posterior_predictive, baseball_dataset) evaluate_log_predictive_density( partially_pooled, posterior_partially_pooled, baseball_dataset ) # (4) Partially Pooled with Logit Model posterior_partially_pooled_with_logit = MCMC( nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps ).run(partially_pooled_with_logit, at_bats, hits) logging.info("\nModel: Partially Pooled with Logit") logging.info("==================================") logging.info("\nSigmoid(alpha):") logging.info( summary( posterior_partially_pooled_with_logit, sites=["alpha"], player_names=player_names, transforms={"alpha": lambda x: 1.0 / (1 + np.exp(-x))}, )["alpha"] ) posterior_predictive = TracePredictive( partially_pooled_with_logit, posterior_partially_pooled_with_logit, num_samples=args.num_samples, ) sample_posterior_predictive(posterior_predictive, baseball_dataset) evaluate_log_predictive_density( partially_pooled_with_logit, posterior_partially_pooled_with_logit, baseball_dataset, )
def main(args): baseball_dataset = pd.read_csv(DATA_URL, "\t") train, _, player_names = train_test_split(baseball_dataset) at_bats, hits = train[:, 0], train[:, 1] nuts_kernel = NUTS(conditioned_model) logging.info("Original Dataset:") logging.info(baseball_dataset) # (1) Full Pooling Model posterior_fully_pooled = MCMC( nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps ).run(fully_pooled, at_bats, hits) logging.info("\nModel: Fully Pooled") logging.info("===================") logging.info("\nphi:") logging.info( summary(posterior_fully_pooled, sites=["phi"], player_names=player_names)["phi"] ) posterior_predictive = TracePredictive( fully_pooled, posterior_fully_pooled, num_samples=args.num_samples ) sample_posterior_predictive(posterior_predictive, baseball_dataset) evaluate_log_predictive_density( fully_pooled, posterior_fully_pooled, baseball_dataset ) # (2) No Pooling Model posterior_not_pooled = MCMC( nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps ).run(not_pooled, at_bats, hits) logging.info("\nModel: Not Pooled") logging.info("=================") logging.info("\nphi:") logging.info( summary(posterior_not_pooled, sites=["phi"], player_names=player_names)["phi"] ) posterior_predictive = TracePredictive( not_pooled, posterior_not_pooled, num_samples=args.num_samples ) sample_posterior_predictive(posterior_predictive, baseball_dataset) evaluate_log_predictive_density(not_pooled, posterior_not_pooled, baseball_dataset) # (3) Partially Pooled Model posterior_partially_pooled = MCMC( nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps ).run(partially_pooled, at_bats, hits) logging.info("\nModel: Partially Pooled") logging.info("=======================") logging.info("\nphi:") logging.info( summary(posterior_partially_pooled, sites=["phi"], player_names=player_names)[ "phi" ] ) posterior_predictive = TracePredictive( partially_pooled, posterior_partially_pooled, num_samples=args.num_samples ) sample_posterior_predictive(posterior_predictive, baseball_dataset) evaluate_log_predictive_density( partially_pooled, posterior_partially_pooled, baseball_dataset ) # (4) Partially Pooled with Logit Model posterior_partially_pooled_with_logit = MCMC( nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps ).run(partially_pooled_with_logit, at_bats, hits) logging.info("\nModel: Partially Pooled with Logit") logging.info("==================================") logging.info("\nSigmoid(alpha):") logging.info( summary( posterior_partially_pooled_with_logit, sites=["alpha"], player_names=player_names, transforms={"alpha": lambda x: 1.0 / (1 + np.exp(-x))}, )["alpha"] ) posterior_predictive = TracePredictive( partially_pooled_with_logit, posterior_partially_pooled_with_logit, num_samples=args.num_samples, ) sample_posterior_predictive(posterior_predictive, baseball_dataset) evaluate_log_predictive_density( partially_pooled_with_logit, posterior_partially_pooled_with_logit, baseball_dataset, )
https://github.com/pyro-ppl/pyro/issues/1458
Traceback (most recent call last): File "/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py", line 128, in log_prob_sum log_p = site["log_prob_sum"] KeyError: 'log_prob_sum' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/travis/build/uber/pyro/examples/baseball.py", line 309, in <module> main(args) File "/home/travis/build/uber/pyro/examples/baseball.py", line 272, in main .run(partially_pooled, at_bats, hits) File "/home/travis/build/uber/pyro/pyro/infer/abstract_infer.py", line 84, in run for tr, logit in self._traces(*args, **kwargs): File "/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py", line 51, in _traces for trace in self._gen_samples(self.num_samples, trace): File "/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py", line 35, in _gen_samples trace = self.kernel.sample(trace) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 276, in sample direction, tree_depth, energy_current) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 159, in _build_tree direction, tree_depth-1, energy_current) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 178, in _build_tree direction, tree_depth-1, energy_current) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 178, in _build_tree direction, tree_depth-1, energy_current) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 155, in _build_tree return self._build_basetree(z, r, z_grads, log_slice, direction, energy_current) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 130, in _build_basetree z, r, self._potential_energy, self._inverse_mass_matrix, step_size, z_grads=z_grads) File "/home/travis/build/uber/pyro/pyro/ops/integrator.py", line 68, in single_step_velocity_verlet z_grads, potential_energy = _potential_grad(potential_fn, z_next) File "/home/travis/build/uber/pyro/pyro/ops/integrator.py", line 79, in _potential_grad potential_energy = potential_fn(z) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py", line 170, in _potential_energy potential_energy = -self._compute_trace_log_prob(trace) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py", line 154, in _compute_trace_log_prob return self._trace_prob_evaluator.log_prob(model_trace) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/util.py", line 132, in log_prob return model_trace.log_prob_sum() File "/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py", line 130, in log_prob_sum log_p = site["fn"].log_prob(site["value"], *site["args"], **site["kwargs"]) File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/transformed_distribution.py", line 86, in log_prob log_prob += _sum_rightmost(self.base_dist.log_prob(y), File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/exponential.py", line 51, in log_prob self._validate_sample(value) File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/distribution.py", line 221, in _validate_sample raise ValueError('The value argument must be within the support')
KeyError
def main(args): pyro.set_rng_seed(args.rng_seed) baseball_dataset = pd.read_csv(DATA_URL, "\t") train, _, player_names = train_test_split(baseball_dataset) at_bats, hits = train[:, 0], train[:, 1] nuts_kernel = NUTS(conditioned_model) logging.info("Original Dataset:") logging.info(baseball_dataset) # (1) Full Pooling Model posterior_fully_pooled = MCMC( nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps ).run(fully_pooled, at_bats, hits) logging.info("\nModel: Fully Pooled") logging.info("===================") logging.info("\nphi:") logging.info( summary(posterior_fully_pooled, sites=["phi"], player_names=player_names)["phi"] ) posterior_predictive = TracePredictive( fully_pooled, posterior_fully_pooled, num_samples=args.num_samples ) sample_posterior_predictive(posterior_predictive, baseball_dataset) evaluate_log_predictive_density( fully_pooled, posterior_fully_pooled, baseball_dataset ) # (2) No Pooling Model posterior_not_pooled = MCMC( nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps ).run(not_pooled, at_bats, hits) logging.info("\nModel: Not Pooled") logging.info("=================") logging.info("\nphi:") logging.info( summary(posterior_not_pooled, sites=["phi"], player_names=player_names)["phi"] ) posterior_predictive = TracePredictive( not_pooled, posterior_not_pooled, num_samples=args.num_samples ) sample_posterior_predictive(posterior_predictive, baseball_dataset) evaluate_log_predictive_density(not_pooled, posterior_not_pooled, baseball_dataset) # (3) Partially Pooled Model # TODO: remove once htps://github.com/uber/pyro/issues/1458 is resolved if "CI" not in os.environ: posterior_partially_pooled = MCMC( nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps ).run(partially_pooled, at_bats, hits) logging.info("\nModel: Partially Pooled") logging.info("=======================") logging.info("\nphi:") logging.info( summary( posterior_partially_pooled, sites=["phi"], player_names=player_names )["phi"] ) posterior_predictive = TracePredictive( partially_pooled, posterior_partially_pooled, num_samples=args.num_samples ) sample_posterior_predictive(posterior_predictive, baseball_dataset) evaluate_log_predictive_density( partially_pooled, posterior_partially_pooled, baseball_dataset ) # (4) Partially Pooled with Logit Model posterior_partially_pooled_with_logit = MCMC( nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps ).run(partially_pooled_with_logit, at_bats, hits) logging.info("\nModel: Partially Pooled with Logit") logging.info("==================================") logging.info("\nSigmoid(alpha):") logging.info( summary( posterior_partially_pooled_with_logit, sites=["alpha"], player_names=player_names, transforms={"alpha": lambda x: 1.0 / (1 + np.exp(-x))}, )["alpha"] ) posterior_predictive = TracePredictive( partially_pooled_with_logit, posterior_partially_pooled_with_logit, num_samples=args.num_samples, ) sample_posterior_predictive(posterior_predictive, baseball_dataset) evaluate_log_predictive_density( partially_pooled_with_logit, posterior_partially_pooled_with_logit, baseball_dataset, )
def main(args): baseball_dataset = pd.read_csv(DATA_URL, "\t") train, _, player_names = train_test_split(baseball_dataset) at_bats, hits = train[:, 0], train[:, 1] nuts_kernel = NUTS(conditioned_model) logging.info("Original Dataset:") logging.info(baseball_dataset) # (1) Full Pooling Model posterior_fully_pooled = MCMC( nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps ).run(fully_pooled, at_bats, hits) logging.info("\nModel: Fully Pooled") logging.info("===================") logging.info("\nphi:") logging.info( summary(posterior_fully_pooled, sites=["phi"], player_names=player_names)["phi"] ) posterior_predictive = TracePredictive( fully_pooled, posterior_fully_pooled, num_samples=args.num_samples ) sample_posterior_predictive(posterior_predictive, baseball_dataset) evaluate_log_predictive_density( fully_pooled, posterior_fully_pooled, baseball_dataset ) # (2) No Pooling Model posterior_not_pooled = MCMC( nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps ).run(not_pooled, at_bats, hits) logging.info("\nModel: Not Pooled") logging.info("=================") logging.info("\nphi:") logging.info( summary(posterior_not_pooled, sites=["phi"], player_names=player_names)["phi"] ) posterior_predictive = TracePredictive( not_pooled, posterior_not_pooled, num_samples=args.num_samples ) sample_posterior_predictive(posterior_predictive, baseball_dataset) evaluate_log_predictive_density(not_pooled, posterior_not_pooled, baseball_dataset) # (3) Partially Pooled Model # TODO: remove once htps://github.com/uber/pyro/issues/1458 is resolved if "CI" not in os.environ: posterior_partially_pooled = MCMC( nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps ).run(partially_pooled, at_bats, hits) logging.info("\nModel: Partially Pooled") logging.info("=======================") logging.info("\nphi:") logging.info( summary( posterior_partially_pooled, sites=["phi"], player_names=player_names )["phi"] ) posterior_predictive = TracePredictive( partially_pooled, posterior_partially_pooled, num_samples=args.num_samples ) sample_posterior_predictive(posterior_predictive, baseball_dataset) evaluate_log_predictive_density( partially_pooled, posterior_partially_pooled, baseball_dataset ) # (4) Partially Pooled with Logit Model posterior_partially_pooled_with_logit = MCMC( nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps ).run(partially_pooled_with_logit, at_bats, hits) logging.info("\nModel: Partially Pooled with Logit") logging.info("==================================") logging.info("\nSigmoid(alpha):") logging.info( summary( posterior_partially_pooled_with_logit, sites=["alpha"], player_names=player_names, transforms={"alpha": lambda x: 1.0 / (1 + np.exp(-x))}, )["alpha"] ) posterior_predictive = TracePredictive( partially_pooled_with_logit, posterior_partially_pooled_with_logit, num_samples=args.num_samples, ) sample_posterior_predictive(posterior_predictive, baseball_dataset) evaluate_log_predictive_density( partially_pooled_with_logit, posterior_partially_pooled_with_logit, baseball_dataset, )
https://github.com/pyro-ppl/pyro/issues/1458
Traceback (most recent call last): File "/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py", line 128, in log_prob_sum log_p = site["log_prob_sum"] KeyError: 'log_prob_sum' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/travis/build/uber/pyro/examples/baseball.py", line 309, in <module> main(args) File "/home/travis/build/uber/pyro/examples/baseball.py", line 272, in main .run(partially_pooled, at_bats, hits) File "/home/travis/build/uber/pyro/pyro/infer/abstract_infer.py", line 84, in run for tr, logit in self._traces(*args, **kwargs): File "/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py", line 51, in _traces for trace in self._gen_samples(self.num_samples, trace): File "/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py", line 35, in _gen_samples trace = self.kernel.sample(trace) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 276, in sample direction, tree_depth, energy_current) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 159, in _build_tree direction, tree_depth-1, energy_current) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 178, in _build_tree direction, tree_depth-1, energy_current) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 178, in _build_tree direction, tree_depth-1, energy_current) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 155, in _build_tree return self._build_basetree(z, r, z_grads, log_slice, direction, energy_current) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 130, in _build_basetree z, r, self._potential_energy, self._inverse_mass_matrix, step_size, z_grads=z_grads) File "/home/travis/build/uber/pyro/pyro/ops/integrator.py", line 68, in single_step_velocity_verlet z_grads, potential_energy = _potential_grad(potential_fn, z_next) File "/home/travis/build/uber/pyro/pyro/ops/integrator.py", line 79, in _potential_grad potential_energy = potential_fn(z) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py", line 170, in _potential_energy potential_energy = -self._compute_trace_log_prob(trace) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py", line 154, in _compute_trace_log_prob return self._trace_prob_evaluator.log_prob(model_trace) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/util.py", line 132, in log_prob return model_trace.log_prob_sum() File "/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py", line 130, in log_prob_sum log_p = site["fn"].log_prob(site["value"], *site["args"], **site["kwargs"]) File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/transformed_distribution.py", line 86, in log_prob log_prob += _sum_rightmost(self.base_dist.log_prob(y), File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/exponential.py", line 51, in log_prob self._validate_sample(value) File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/distribution.py", line 221, in _validate_sample raise ValueError('The value argument must be within the support')
KeyError
def _kinetic_energy(self, r): # TODO: revert to `torch.dot` in pytorch==1.0 # See: https://github.com/uber/pyro/issues/1458 r_flat = torch.cat([r[site_name].reshape(-1) for site_name in sorted(r)]) if self.full_mass: return 0.5 * (r_flat * (self._inverse_mass_matrix.matmul(r_flat))).sum() else: return 0.5 * (self._inverse_mass_matrix * (r_flat**2)).sum()
def _kinetic_energy(self, r): r_flat = torch.cat([r[site_name].reshape(-1) for site_name in sorted(r)]) if self.full_mass: return 0.5 * r_flat.dot(self._inverse_mass_matrix.matmul(r_flat)) else: return 0.5 * self._inverse_mass_matrix.dot(r_flat**2)
https://github.com/pyro-ppl/pyro/issues/1458
Traceback (most recent call last): File "/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py", line 128, in log_prob_sum log_p = site["log_prob_sum"] KeyError: 'log_prob_sum' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/travis/build/uber/pyro/examples/baseball.py", line 309, in <module> main(args) File "/home/travis/build/uber/pyro/examples/baseball.py", line 272, in main .run(partially_pooled, at_bats, hits) File "/home/travis/build/uber/pyro/pyro/infer/abstract_infer.py", line 84, in run for tr, logit in self._traces(*args, **kwargs): File "/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py", line 51, in _traces for trace in self._gen_samples(self.num_samples, trace): File "/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py", line 35, in _gen_samples trace = self.kernel.sample(trace) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 276, in sample direction, tree_depth, energy_current) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 159, in _build_tree direction, tree_depth-1, energy_current) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 178, in _build_tree direction, tree_depth-1, energy_current) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 178, in _build_tree direction, tree_depth-1, energy_current) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 155, in _build_tree return self._build_basetree(z, r, z_grads, log_slice, direction, energy_current) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py", line 130, in _build_basetree z, r, self._potential_energy, self._inverse_mass_matrix, step_size, z_grads=z_grads) File "/home/travis/build/uber/pyro/pyro/ops/integrator.py", line 68, in single_step_velocity_verlet z_grads, potential_energy = _potential_grad(potential_fn, z_next) File "/home/travis/build/uber/pyro/pyro/ops/integrator.py", line 79, in _potential_grad potential_energy = potential_fn(z) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py", line 170, in _potential_energy potential_energy = -self._compute_trace_log_prob(trace) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py", line 154, in _compute_trace_log_prob return self._trace_prob_evaluator.log_prob(model_trace) File "/home/travis/build/uber/pyro/pyro/infer/mcmc/util.py", line 132, in log_prob return model_trace.log_prob_sum() File "/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py", line 130, in log_prob_sum log_p = site["fn"].log_prob(site["value"], *site["args"], **site["kwargs"]) File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/transformed_distribution.py", line 86, in log_prob log_prob += _sum_rightmost(self.base_dist.log_prob(y), File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/exponential.py", line 51, in log_prob self._validate_sample(value) File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/distribution.py", line 221, in _validate_sample raise ValueError('The value argument must be within the support')
KeyError
def model(self, xs, ys=None): """ The model corresponds to the following generative process: p(z) = normal(0,I) # handwriting style (latent) p(y|x) = categorical(I/10.) # which digit (semi-supervised) p(x|y,z) = bernoulli(mu(y,z)) # an image mu is given by a neural network `decoder` :param xs: a batch of scaled vectors of pixels from an image :param ys: (optional) a batch of the class labels i.e. the digit corresponding to the image(s) :return: None """ # register this pytorch module and all of its sub-modules with pyro pyro.module("ss_vae", self) batch_size = xs.size(0) with pyro.iarange("independent"): # sample the handwriting style from the constant prior distribution prior_mu = Variable(torch.zeros([batch_size, self.z_dim])) prior_sigma = Variable(torch.ones([batch_size, self.z_dim])) zs = pyro.sample("z", dist.normal, prior_mu, prior_sigma, extra_event_dims=1) # if the label y (which digit to write) is supervised, sample from the # constant prior, otherwise, observe the value (i.e. score it against the constant prior) alpha_prior = Variable( torch.ones([batch_size, self.output_size]) / (1.0 * self.output_size) ) if ys is None: ys = pyro.sample("y", dist.one_hot_categorical, alpha_prior) else: pyro.sample("y", dist.one_hot_categorical, alpha_prior, obs=ys) # finally, score the image (x) using the handwriting style (z) and # the class label y (which digit to write) against the # parametrized distribution p(x|y,z) = bernoulli(decoder(y,z)) # where `decoder` is a neural network mu = self.decoder.forward([zs, ys]) pyro.sample("x", dist.bernoulli, mu, extra_event_dims=1, obs=xs)
def model(self, xs, ys=None): """ The model corresponds to the following generative process: p(z) = normal(0,I) # handwriting style (latent) p(y|x) = categorical(I/10.) # which digit (semi-supervised) p(x|y,z) = bernoulli(mu(y,z)) # an image mu is given by a neural network `decoder` :param xs: a batch of scaled vectors of pixels from an image :param ys: (optional) a batch of the class labels i.e. the digit corresponding to the image(s) :return: None """ # register this pytorch module and all of its sub-modules with pyro pyro.module("ss_vae", self) batch_size = xs.size(0) with pyro.iarange("independent"): # sample the handwriting style from the constant prior distribution prior_mu = Variable(torch.zeros([batch_size, self.z_dim])) prior_sigma = Variable(torch.ones([batch_size, self.z_dim])) zs = pyro.sample("z", dist.normal, prior_mu, prior_sigma) # if the label y (which digit to write) is supervised, sample from the # constant prior, otherwise, observe the value (i.e. score it against the constant prior) alpha_prior = Variable( torch.ones([batch_size, self.output_size]) / (1.0 * self.output_size) ) if ys is None: ys = pyro.sample("y", dist.one_hot_categorical, alpha_prior) else: pyro.sample("y", dist.one_hot_categorical, alpha_prior, obs=ys) # finally, score the image (x) using the handwriting style (z) and # the class label y (which digit to write) against the # parametrized distribution p(x|y,z) = bernoulli(decoder(y,z)) # where `decoder` is a neural network mu = self.decoder.forward([zs, ys]) pyro.sample("x", dist.bernoulli, mu, obs=xs)
https://github.com/pyro-ppl/pyro/issues/725
$ python ss_vae_M2.py -enum Traceback (most recent call last): File "ss_vae_M2.py", line 464, in <module> run_inference_ss_vae(args) File "ss_vae_M2.py", line 371, in run_inference_ss_vae run_inference_for_epoch(data_loaders, losses, periodic_interval_batches) File "ss_vae_M2.py", line 268, in run_inference_for_epoch new_loss = losses[loss_id].step(xs) File "/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/svi.py", line 98, in step loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) File "/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/elbo.py", line 65, in loss_and_grads return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs) File "/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py", line 146, in loss_and_grads for weight, model_trace, guide_trace, log_r in self._get_traces(model, guide, *args, **kwargs): File "/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py", line 79, in _get_traces check_enum_discrete_can_run(model_trace, guide_trace) File "/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py", line 45, in check_enum_discrete_can_run for shape, (source, name) in sorted(shapes.items())]))) NotImplementedError: enum_discrete does not support mixture of batched and un-batched variables. Try rewriting your model to avoid batching or running with enum_discrete=False. Found the following variables of different batch shapes: guide y: shape = (200,) guide z: shape = (200, 50) model x: shape = (200, 784)
NotImplementedError
def guide(self, xs, ys=None): """ The guide corresponds to the following: q(y|x) = categorical(alpha(x)) # infer digit from an image q(z|x,y) = normal(mu(x,y),sigma(x,y)) # infer handwriting style from an image and the digit mu, sigma are given by a neural network `encoder_z` alpha is given by a neural network `encoder_y` :param xs: a batch of scaled vectors of pixels from an image :param ys: (optional) a batch of the class labels i.e. the digit corresponding to the image(s) :return: None """ # inform Pyro that the variables in the batch of xs, ys are conditionally independent with pyro.iarange("independent"): # if the class label (the digit) is not supervised, sample # (and score) the digit with the variational distribution # q(y|x) = categorical(alpha(x)) if ys is None: alpha = self.encoder_y.forward(xs) ys = pyro.sample("y", dist.one_hot_categorical, alpha) # sample (and score) the latent handwriting-style with the variational # distribution q(z|x,y) = normal(mu(x,y),sigma(x,y)) mu, sigma = self.encoder_z.forward([xs, ys]) pyro.sample("z", dist.normal, mu, sigma, extra_event_dims=1)
def guide(self, xs, ys=None): """ The guide corresponds to the following: q(y|x) = categorical(alpha(x)) # infer digit from an image q(z|x,y) = normal(mu(x,y),sigma(x,y)) # infer handwriting style from an image and the digit mu, sigma are given by a neural network `encoder_z` alpha is given by a neural network `encoder_y` :param xs: a batch of scaled vectors of pixels from an image :param ys: (optional) a batch of the class labels i.e. the digit corresponding to the image(s) :return: None """ # inform Pyro that the variables in the batch of xs, ys are conditionally independent with pyro.iarange("independent"): # if the class label (the digit) is not supervised, sample # (and score) the digit with the variational distribution # q(y|x) = categorical(alpha(x)) if ys is None: alpha = self.encoder_y.forward(xs) ys = pyro.sample("y", dist.one_hot_categorical, alpha) # sample (and score) the latent handwriting-style with the variational # distribution q(z|x,y) = normal(mu(x,y),sigma(x,y)) mu, sigma = self.encoder_z.forward([xs, ys]) zs = pyro.sample("z", dist.normal, mu, sigma) # noqa: F841
https://github.com/pyro-ppl/pyro/issues/725
$ python ss_vae_M2.py -enum Traceback (most recent call last): File "ss_vae_M2.py", line 464, in <module> run_inference_ss_vae(args) File "ss_vae_M2.py", line 371, in run_inference_ss_vae run_inference_for_epoch(data_loaders, losses, periodic_interval_batches) File "ss_vae_M2.py", line 268, in run_inference_for_epoch new_loss = losses[loss_id].step(xs) File "/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/svi.py", line 98, in step loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) File "/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/elbo.py", line 65, in loss_and_grads return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs) File "/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py", line 146, in loss_and_grads for weight, model_trace, guide_trace, log_r in self._get_traces(model, guide, *args, **kwargs): File "/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py", line 79, in _get_traces check_enum_discrete_can_run(model_trace, guide_trace) File "/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py", line 45, in check_enum_discrete_can_run for shape, (source, name) in sorted(shapes.items())]))) NotImplementedError: enum_discrete does not support mixture of batched and un-batched variables. Try rewriting your model to avoid batching or running with enum_discrete=False. Found the following variables of different batch shapes: guide y: shape = (200,) guide z: shape = (200, 50) model x: shape = (200, 784)
NotImplementedError
def model_sample(self, ys, batch_size=1): # sample the handwriting style from the constant prior distribution prior_mu = Variable(torch.zeros([batch_size, self.z_dim])) prior_sigma = Variable(torch.ones([batch_size, self.z_dim])) zs = pyro.sample("z", dist.normal, prior_mu, prior_sigma, extra_event_dims=1) # sample an image using the decoder mu = self.decoder.forward([zs, ys]) xs = pyro.sample("sample", dist.bernoulli, mu, extra_event_dims=1) return xs, mu
def model_sample(self, ys, batch_size=1): # sample the handwriting style from the constant prior distribution prior_mu = Variable(torch.zeros([batch_size, self.z_dim])) prior_sigma = Variable(torch.ones([batch_size, self.z_dim])) zs = pyro.sample("z", dist.normal, prior_mu, prior_sigma) # sample an image using the decoder mu = self.decoder.forward([zs, ys]) xs = pyro.sample("sample", dist.bernoulli, mu) return xs, mu
https://github.com/pyro-ppl/pyro/issues/725
$ python ss_vae_M2.py -enum Traceback (most recent call last): File "ss_vae_M2.py", line 464, in <module> run_inference_ss_vae(args) File "ss_vae_M2.py", line 371, in run_inference_ss_vae run_inference_for_epoch(data_loaders, losses, periodic_interval_batches) File "ss_vae_M2.py", line 268, in run_inference_for_epoch new_loss = losses[loss_id].step(xs) File "/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/svi.py", line 98, in step loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) File "/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/elbo.py", line 65, in loss_and_grads return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs) File "/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py", line 146, in loss_and_grads for weight, model_trace, guide_trace, log_r in self._get_traces(model, guide, *args, **kwargs): File "/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py", line 79, in _get_traces check_enum_discrete_can_run(model_trace, guide_trace) File "/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py", line 45, in check_enum_discrete_can_run for shape, (source, name) in sorted(shapes.items())]))) NotImplementedError: enum_discrete does not support mixture of batched and un-batched variables. Try rewriting your model to avoid batching or running with enum_discrete=False. Found the following variables of different batch shapes: guide y: shape = (200,) guide z: shape = (200, 50) model x: shape = (200, 784)
NotImplementedError
def torch_multinomial(input, num_samples, replacement=False): """ Like `torch.multinomial()` but works with cuda tensors. Does not support keyword argument `out`. """ if input.is_cuda: return torch.multinomial(input.cpu(), num_samples, replacement).cuda( input.get_device() ) else: return torch.multinomial(input, num_samples, replacement)
def torch_multinomial(input, num_samples, replacement=False): """ Like `torch.multinomial()` but works with cuda tensors. Does not support keyword argument `out`. """ if input.is_cuda: return torch_multinomial(input.cpu(), num_samples, replacement).cuda() else: return torch.multinomial(input, num_samples, replacement)
https://github.com/pyro-ppl/pyro/issues/668
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-31-93fd337a0d5c> in <module>() ----> 1 train() <ipython-input-30-98110a9a9720> in train() 33 34 # Train and score ---> 35 train_loss += svi.step(input_batch, target_batch) 36 37 # Store history /home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/svi.pyc in step(self, *args, **kwargs) 96 """ 97 # get loss and compute gradients ---> 98 loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) 99 100 # get active params /home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs) 63 :rtype: float 64 """ ---> 65 return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs) /home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/trace_elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs) 149 guide_site = guide_trace.nodes[name] 150 lp_lq = model_site[log_pdf] - guide_site[log_pdf] --> 151 elbo_particle += lp_lq 152 if guide_site["fn"].reparameterized: 153 surrogate_elbo_particle += lp_lq RuntimeError: Expected object of type Variable[torch.FloatTensor] but found type Variable[torch.cuda.FloatTensor] for argument #1 'other'
RuntimeError
def iter_discrete_traces(graph_type, fn, *args, **kwargs): """ Iterate over all discrete choices of a stochastic function. When sampling continuous random variables, this behaves like `fn`. When sampling discrete random variables, this iterates over all choices. This yields `(scale, trace)` pairs, where `scale` is the probability of the discrete choices made in the `trace`. :param str graph_type: The type of the graph, e.g. "flat" or "dense". :param callable fn: A stochastic function. :returns: An iterator over (scale, trace) pairs. """ queue = LifoQueue() queue.put(Trace()) while not queue.empty(): partial_trace = queue.get() escape_fn = functools.partial(util.discrete_escape, partial_trace) traced_fn = poutine.trace( poutine.escape(poutine.replay(fn, partial_trace), escape_fn), graph_type=graph_type, ) try: full_trace = traced_fn.get_trace(*args, **kwargs) except util.NonlocalExit as e: for extended_trace in util.enum_extend(traced_fn.trace.copy(), e.site): queue.put(extended_trace) continue # Scale trace by probability of discrete choices. log_pdf = full_trace.batch_log_pdf(site_filter=site_is_discrete) if isinstance(log_pdf, Variable): scale = torch.exp(log_pdf.detach()) else: scale = math.exp(log_pdf) yield scale, full_trace
def iter_discrete_traces(graph_type, fn, *args, **kwargs): """ Iterate over all discrete choices of a stochastic function. When sampling continuous random variables, this behaves like `fn`. When sampling discrete random variables, this iterates over all choices. This yields `(scale, trace)` pairs, where `scale` is the probability of the discrete choices made in the `trace`. :param str graph_type: The type of the graph, e.g. "flat" or "dense". :param callable fn: A stochastic function. :returns: An iterator over (scale, trace) pairs. """ queue = LifoQueue() queue.put(Trace()) while not queue.empty(): partial_trace = queue.get() escape_fn = functools.partial(util.discrete_escape, partial_trace) traced_fn = poutine.trace( poutine.escape(poutine.replay(fn, partial_trace), escape_fn), graph_type=graph_type, ) try: full_trace = traced_fn.get_trace(*args, **kwargs) except util.NonlocalExit as e: for extended_trace in util.enum_extend(traced_fn.trace.copy(), e.site): queue.put(extended_trace) continue # Scale trace by probability of discrete choices. log_pdf = full_trace.batch_log_pdf(site_filter=site_is_discrete) if isinstance(log_pdf, float): log_pdf = torch.Tensor([log_pdf]) if isinstance(log_pdf, torch.Tensor): log_pdf = Variable(log_pdf) scale = torch.exp(log_pdf.detach()) yield scale, full_trace
https://github.com/pyro-ppl/pyro/issues/668
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-31-93fd337a0d5c> in <module>() ----> 1 train() <ipython-input-30-98110a9a9720> in train() 33 34 # Train and score ---> 35 train_loss += svi.step(input_batch, target_batch) 36 37 # Store history /home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/svi.pyc in step(self, *args, **kwargs) 96 """ 97 # get loss and compute gradients ---> 98 loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) 99 100 # get active params /home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs) 63 :rtype: float 64 """ ---> 65 return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs) /home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/trace_elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs) 149 guide_site = guide_trace.nodes[name] 150 lp_lq = model_site[log_pdf] - guide_site[log_pdf] --> 151 elbo_particle += lp_lq 152 if guide_site["fn"].reparameterized: 153 surrogate_elbo_particle += lp_lq RuntimeError: Expected object of type Variable[torch.FloatTensor] but found type Variable[torch.cuda.FloatTensor] for argument #1 'other'
RuntimeError
def loss(self, model, guide, *args, **kwargs): """ :returns: returns an estimate of the ELBO :rtype: float Evaluates the ELBO with an estimator that uses num_particles many samples/particles. """ elbo = 0.0 for weight, model_trace, guide_trace, log_r in self._get_traces( model, guide, *args, **kwargs ): elbo_particle = weight * 0 if self.enum_discrete and isinstance(weight, Variable) and weight.size(0) > 1: log_pdf = "batch_log_pdf" else: log_pdf = "log_pdf" for name in model_trace.nodes.keys(): if model_trace.nodes[name]["type"] == "sample": if model_trace.nodes[name]["is_observed"]: elbo_particle += model_trace.nodes[name][log_pdf] else: elbo_particle += model_trace.nodes[name][log_pdf] elbo_particle -= guide_trace.nodes[name][log_pdf] # drop terms of weight zero to avoid nans if isinstance(weight, numbers.Number): if weight == 0.0: elbo_particle = torch_zeros_like(elbo_particle) else: elbo_particle[weight == 0] = 0.0 elbo += torch_data_sum(weight * elbo_particle) loss = -elbo if np.isnan(loss): warnings.warn("Encountered NAN loss") return loss
def loss(self, model, guide, *args, **kwargs): """ :returns: returns an estimate of the ELBO :rtype: float Evaluates the ELBO with an estimator that uses num_particles many samples/particles. """ elbo = 0.0 for weight, model_trace, guide_trace, log_r in self._get_traces( model, guide, *args, **kwargs ): elbo_particle = weight * 0 log_pdf = ( "batch_log_pdf" if (self.enum_discrete and weight.size(0) > 1) else "log_pdf" ) for name in model_trace.nodes.keys(): if model_trace.nodes[name]["type"] == "sample": if model_trace.nodes[name]["is_observed"]: elbo_particle += model_trace.nodes[name][log_pdf] else: elbo_particle += model_trace.nodes[name][log_pdf] elbo_particle -= guide_trace.nodes[name][log_pdf] # drop terms of weight zero to avoid nans if isinstance(weight, numbers.Number): if weight == 0.0: elbo_particle = torch_zeros_like(elbo_particle) else: elbo_particle[weight == 0] = 0.0 elbo += torch_data_sum(weight * elbo_particle) loss = -elbo if np.isnan(loss): warnings.warn("Encountered NAN loss") return loss
https://github.com/pyro-ppl/pyro/issues/668
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-31-93fd337a0d5c> in <module>() ----> 1 train() <ipython-input-30-98110a9a9720> in train() 33 34 # Train and score ---> 35 train_loss += svi.step(input_batch, target_batch) 36 37 # Store history /home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/svi.pyc in step(self, *args, **kwargs) 96 """ 97 # get loss and compute gradients ---> 98 loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) 99 100 # get active params /home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs) 63 :rtype: float 64 """ ---> 65 return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs) /home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/trace_elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs) 149 guide_site = guide_trace.nodes[name] 150 lp_lq = model_site[log_pdf] - guide_site[log_pdf] --> 151 elbo_particle += lp_lq 152 if guide_site["fn"].reparameterized: 153 surrogate_elbo_particle += lp_lq RuntimeError: Expected object of type Variable[torch.FloatTensor] but found type Variable[torch.cuda.FloatTensor] for argument #1 'other'
RuntimeError
def loss_and_grads(self, model, guide, *args, **kwargs): """ :returns: returns an estimate of the ELBO :rtype: float Computes the ELBO as well as the surrogate ELBO that is used to form the gradient estimator. Performs backward on the latter. Num_particle many samples are used to form the estimators. """ elbo = 0.0 # grab a trace from the generator for weight, model_trace, guide_trace, log_r in self._get_traces( model, guide, *args, **kwargs ): elbo_particle = weight * 0 surrogate_elbo_particle = weight * 0 # compute elbo and surrogate elbo if self.enum_discrete and isinstance(weight, Variable) and weight.size(0) > 1: log_pdf = "batch_log_pdf" else: log_pdf = "log_pdf" for name, model_site in model_trace.nodes.items(): if model_site["type"] == "sample": if model_site["is_observed"]: elbo_particle += model_site[log_pdf] surrogate_elbo_particle += model_site[log_pdf] else: guide_site = guide_trace.nodes[name] lp_lq = model_site[log_pdf] - guide_site[log_pdf] elbo_particle += lp_lq if guide_site["fn"].reparameterized: surrogate_elbo_particle += lp_lq else: # XXX should the user be able to control inclusion of the -logq term below? guide_log_pdf = ( guide_site[log_pdf] / guide_site["scale"] ) # not scaled by subsampling surrogate_elbo_particle += ( model_site[log_pdf] + log_r.detach() * guide_log_pdf ) # drop terms of weight zero to avoid nans if isinstance(weight, numbers.Number): if weight == 0.0: elbo_particle = torch_zeros_like(elbo_particle) surrogate_elbo_particle = torch_zeros_like(surrogate_elbo_particle) else: weight_eq_zero = weight == 0 elbo_particle[weight_eq_zero] = 0.0 surrogate_elbo_particle[weight_eq_zero] = 0.0 elbo += torch_data_sum(weight * elbo_particle) surrogate_elbo_particle = torch_sum(weight * surrogate_elbo_particle) # collect parameters to train from model and guide trainable_params = set( site["value"] for trace in (model_trace, guide_trace) for site in trace.nodes.values() if site["type"] == "param" ) if trainable_params: surrogate_loss_particle = -surrogate_elbo_particle torch_backward(surrogate_loss_particle) pyro.get_param_store().mark_params_active(trainable_params) loss = -elbo if np.isnan(loss): warnings.warn("Encountered NAN loss") return loss
def loss_and_grads(self, model, guide, *args, **kwargs): """ :returns: returns an estimate of the ELBO :rtype: float Computes the ELBO as well as the surrogate ELBO that is used to form the gradient estimator. Performs backward on the latter. Num_particle many samples are used to form the estimators. """ elbo = 0.0 # grab a trace from the generator for weight, model_trace, guide_trace, log_r in self._get_traces( model, guide, *args, **kwargs ): elbo_particle = weight * 0 surrogate_elbo_particle = weight * 0 # compute elbo and surrogate elbo log_pdf = ( "batch_log_pdf" if (self.enum_discrete and weight.size(0) > 1) else "log_pdf" ) for name, model_site in model_trace.nodes.items(): if model_site["type"] == "sample": if model_site["is_observed"]: elbo_particle += model_site[log_pdf] surrogate_elbo_particle += model_site[log_pdf] else: guide_site = guide_trace.nodes[name] lp_lq = model_site[log_pdf] - guide_site[log_pdf] elbo_particle += lp_lq if guide_site["fn"].reparameterized: surrogate_elbo_particle += lp_lq else: # XXX should the user be able to control inclusion of the -logq term below? guide_log_pdf = ( guide_site[log_pdf] / guide_site["scale"] ) # not scaled by subsampling surrogate_elbo_particle += ( model_site[log_pdf] + log_r.detach() * guide_log_pdf ) # drop terms of weight zero to avoid nans if isinstance(weight, numbers.Number): if weight == 0.0: elbo_particle = torch_zeros_like(elbo_particle) surrogate_elbo_particle = torch_zeros_like(surrogate_elbo_particle) else: weight_eq_zero = weight == 0 elbo_particle[weight_eq_zero] = 0.0 surrogate_elbo_particle[weight_eq_zero] = 0.0 elbo += torch_data_sum(weight * elbo_particle) surrogate_elbo_particle = torch_sum(weight * surrogate_elbo_particle) # collect parameters to train from model and guide trainable_params = set( site["value"] for trace in (model_trace, guide_trace) for site in trace.nodes.values() if site["type"] == "param" ) if trainable_params: surrogate_loss_particle = -surrogate_elbo_particle torch_backward(surrogate_loss_particle) pyro.get_param_store().mark_params_active(trainable_params) loss = -elbo if np.isnan(loss): warnings.warn("Encountered NAN loss") return loss
https://github.com/pyro-ppl/pyro/issues/668
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-31-93fd337a0d5c> in <module>() ----> 1 train() <ipython-input-30-98110a9a9720> in train() 33 34 # Train and score ---> 35 train_loss += svi.step(input_batch, target_batch) 36 37 # Store history /home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/svi.pyc in step(self, *args, **kwargs) 96 """ 97 # get loss and compute gradients ---> 98 loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) 99 100 # get active params /home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs) 63 :rtype: float 64 """ ---> 65 return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs) /home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/trace_elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs) 149 guide_site = guide_trace.nodes[name] 150 lp_lq = model_site[log_pdf] - guide_site[log_pdf] --> 151 elbo_particle += lp_lq 152 if guide_site["fn"].reparameterized: 153 surrogate_elbo_particle += lp_lq RuntimeError: Expected object of type Variable[torch.FloatTensor] but found type Variable[torch.cuda.FloatTensor] for argument #1 'other'
RuntimeError
def resolve_is_lower_case(tokenizer): if isinstance(tokenizer, transformers.BertTokenizer): return tokenizer.basic_tokenizer.do_lower_case if isinstance(tokenizer, transformers.AlbertTokenizer): return tokenizer.do_lower_case else: return False
def resolve_is_lower_case(tokenizer): if isinstance( tokenizer, (transformers.BertTokenizer, transformers.AlbertTokenizer) ): return tokenizer.basic_tokenizer.do_lower_case else: return False
https://github.com/nyu-mll/jiant/issues/1200
Traceback (most recent call last): File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py", line 214, in <module> main(args=RunConfiguration.run_cli_json_prepend()) File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py", line 168, in main args=args, File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py", line 53, in chunk_and_save args=args, File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py", line 129, in iter_chunk_and_save recorder_callback=max_valid_length_recorder, File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/shared/caching.py", line 91, in iter_chunk_and_save for datum in data: File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/preprocessing.py", line 145, in iter_chunk_convert_examples_to_dataset verbose=verbose, File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/preprocessing.py", line 216, in iter_chunk_tokenize_and_featurize yield example.tokenize(tokenizer).featurize(tokenizer, feat_spec) File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/tasks/lib/templates/span_prediction.py", line 38, in tokenize self.answer_char_span[0], self.answer_char_span[1], inclusive=True File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/utils/retokenize.py", line 276, in project_char_to_token_span mat=self.source_char_idx_to_target_token_idx, start=start, end=end, inclusive=inclusive File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/utils/retokenize.py", line 192, in _project_span raise ValueError(f"Project {(start, end)} into empty span in target sequence") ValueError: Project (0, 2) into empty span in target sequence
ValueError
def tokenize(self, tokenizer): passage = ( self.passage.lower() if model_resolution.resolve_is_lower_case(tokenizer=tokenizer) else self.passage ) passage_tokens = tokenizer.tokenize(passage) token_aligner = TokenAligner(source=passage, target=passage_tokens) answer_token_span = token_aligner.project_char_to_token_span( self.answer_char_span[0], self.answer_char_span[1], inclusive=True ) return TokenizedExample( guid=self.guid, passage=passage_tokens, question=tokenizer.tokenize(self.question), answer_str=self.answer, passage_str=passage, answer_token_span=answer_token_span, token_idx_to_char_idx_map=token_aligner.source_char_idx_to_target_token_idx.T, )
def tokenize(self, tokenizer): passage = ( self.passage.lower() if resolve_is_lower_case(tokenizer=tokenizer) else self.passage ) passage_tokens = tokenizer.tokenize(passage) token_aligner = TokenAligner(source=passage, target=passage_tokens) answer_token_span = token_aligner.project_char_to_token_span( self.answer_char_span[0], self.answer_char_span[1], inclusive=True ) return TokenizedExample( guid=self.guid, passage=passage_tokens, question=tokenizer.tokenize(self.question), answer_str=self.answer, passage_str=passage, answer_token_span=answer_token_span, token_idx_to_char_idx_map=token_aligner.source_char_idx_to_target_token_idx.T, )
https://github.com/nyu-mll/jiant/issues/1200
Traceback (most recent call last): File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py", line 214, in <module> main(args=RunConfiguration.run_cli_json_prepend()) File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py", line 168, in main args=args, File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py", line 53, in chunk_and_save args=args, File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py", line 129, in iter_chunk_and_save recorder_callback=max_valid_length_recorder, File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/shared/caching.py", line 91, in iter_chunk_and_save for datum in data: File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/preprocessing.py", line 145, in iter_chunk_convert_examples_to_dataset verbose=verbose, File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/preprocessing.py", line 216, in iter_chunk_tokenize_and_featurize yield example.tokenize(tokenizer).featurize(tokenizer, feat_spec) File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/tasks/lib/templates/span_prediction.py", line 38, in tokenize self.answer_char_span[0], self.answer_char_span[1], inclusive=True File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/utils/retokenize.py", line 276, in project_char_to_token_span mat=self.source_char_idx_to_target_token_idx, start=start, end=end, inclusive=inclusive File "/scratch/pmh330/nyu-mll-jiant/jiant/jiant/utils/retokenize.py", line 192, in _project_span raise ValueError(f"Project {(start, end)} into empty span in target sequence") ValueError: Project (0, 2) into empty span in target sequence
ValueError
def get_task_specific_params(args, task_name): """Search args for parameters specific to task. Args: args: main-program args, a config.Params object task_name: (string) Returns: AllenNLP Params object of task-specific params. """ def _get_task_attr(attr_name, default=None): return config.get_task_attr(args, task_name, attr_name, default) params = {} params["cls_type"] = _get_task_attr("classifier") params["d_hid"] = _get_task_attr("classifier_hid_dim") params["d_proj"] = _get_task_attr("d_proj") params["shared_pair_attn"] = args.shared_pair_attn if args.shared_pair_attn: params["attn"] = args.pair_attn params["d_hid_attn"] = args.d_hid_attn params["dropout"] = args.classifier_dropout else: params["attn"] = _get_task_attr("pair_attn") params["d_hid_attn"] = _get_task_attr("d_hid_attn") params["dropout"] = _get_task_attr("classifier_dropout") # Used for span/edge classification. Other tasks can safely ignore. params["cls_loss_fn"] = _get_task_attr("span_classifier_loss_fn") params["cls_span_pooling"] = _get_task_attr("classifier_span_pooling") params["edgeprobe_cnn_context"] = _get_task_attr("edgeprobe_cnn_context") # For NLI probing tasks, might want to use a classifier trained on # something else (typically 'mnli'). cls_task_name = _get_task_attr("use_classifier") # default to this task params["use_classifier"] = cls_task_name or task_name return Params(params)
def get_task_specific_params(args, task_name): """Search args for parameters specific to task. Args: args: main-program args, a config.Params object task_name: (string) Returns: AllenNLP Params object of task-specific params. """ def _get_task_attr(attr_name, default=None): return config.get_task_attr(args, task_name, attr_name, default) params = {} params["cls_type"] = _get_task_attr("classifier") params["d_hid"] = _get_task_attr("classifier_hid_dim") params["d_proj"] = _get_task_attr("d_proj") params["shared_pair_attn"] = args.shared_pair_attn if args.shared_pair_attn: params["attn"] = args.pair_attn params["d_hid_attn"] = args.d_hid_attn params["dropout"] = args.classifier_dropout else: params["attn"] = _get_task_attr("pair_attn") params["d_hid_attn"] = _get_task_attr("d_hid_attn") params["dropout"] = _get_task_attr("classifier_dropout") # Used for edge probing. Other tasks can safely ignore. params["cls_loss_fn"] = _get_task_attr("classifier_loss_fn") params["cls_span_pooling"] = _get_task_attr("classifier_span_pooling") params["edgeprobe_cnn_context"] = _get_task_attr("edgeprobe_cnn_context") # For NLI probing tasks, might want to use a classifier trained on # something else (typically 'mnli'). cls_task_name = _get_task_attr("use_classifier") # default to this task params["use_classifier"] = cls_task_name or task_name return Params(params)
https://github.com/nyu-mll/jiant/issues/773
Traceback (most recent call last): File "main.py", line 566, in <module> main(sys.argv[1:]) File "main.py", line 534, in main phase="target_train", File "/Users/srbowman/jiant/src/trainer.py", line 594, in train output_dict = self._forward(batch, task=task) File "/Users/srbowman/jiant/src/trainer.py", line 1035, in _forward model_out = self._model.forward(task, tensor_batch) File "/Users/srbowman/jiant/src/models.py", line 830, in forward out = self._span_forward(batch, task, predict) File "/Users/srbowman/jiant/src/models.py", line 917, in _span_forward out = module.forward(batch, sent_embs, sent_mask, task, predict) File "/Users/srbowman/jiant/src/modules/span_modules.py", line 134, in forward out["loss"] = self.compute_loss(logits, batch["labels"].squeeze(dim=1), task) File "/Users/srbowman/jiant/src/modules/span_modules.py", line 184, in compute_loss raise ValueError("Unsupported loss type '%s' " "for edge probing." % self.loss_type) ValueError: Unsupported loss type '' for edge probing. Traceback (most recent call last): File "main.py", line 577, in <module> raise e # re-raise exception, in case debugger is attached. File "main.py", line 566, in <module> main(sys.argv[1:]) File "main.py", line 534, in main phase="target_train", File "/Users/srbowman/jiant/src/trainer.py", line 594, in train output_dict = self._forward(batch, task=task) File "/Users/srbowman/jiant/src/trainer.py", line 1035, in _forward model_out = self._model.forward(task, tensor_batch) File "/Users/srbowman/jiant/src/models.py", line 830, in forward out = self._span_forward(batch, task, predict) File "/Users/srbowman/jiant/src/models.py", line 917, in _span_forward out = module.forward(batch, sent_embs, sent_mask, task, predict) File "/Users/srbowman/jiant/src/modules/span_modules.py", line 134, in forward out["loss"] = self.compute_loss(logits, batch["labels"].squeeze(dim=1), task) File "/Users/srbowman/jiant/src/modules/span_modules.py", line 184, in compute_loss raise ValueError("Unsupported loss type '%s' " "for edge probing." % self.loss_type) ValueError: Unsupported loss type '' for edge probing.
ValueError
def update_metrics(self, logits, labels, tagmask=None): logits, labels = logits.detach(), labels.detach() def make_one_hot(batch, depth=2): """ Creates a one-hot embedding of dimension 2. Parameters: batch: list of size batch_size of class predictions Returns: one hot encoding of size [batch_size, 2] """ ones = torch.sparse.torch.eye(depth) if torch.cuda.is_available(): ones = ones.cuda() return ones.index_select(0, batch) binary_preds = make_one_hot(logits, depth=2) # Make label_ints a batch_size list of labels label_ints = torch.argmax(labels, dim=1) self.f1_scorer(binary_preds, label_ints) self.acc_scorer(binary_preds.long(), labels.long())
def update_metrics(self, logits, labels, tagmask=None): logits, labels = logits.detach(), labels.detach() def make_one_hot(batch, depth=2): """ Creates a one-hot embedding of dimension 2. Parameters: batch: list of size batch_size of class predictions Returns: one hot encoding of size [batch_size, 2] """ ones = torch.sparse.torch.eye(depth).cuda() return ones.index_select(0, batch) binary_preds = make_one_hot(logits, depth=2) # Make label_ints a batch_size list of labels label_ints = torch.argmax(labels, dim=1) self.f1_scorer(binary_preds, label_ints) self.acc_scorer(binary_preds.long(), labels.long())
https://github.com/nyu-mll/jiant/issues/773
Traceback (most recent call last): File "main.py", line 566, in <module> main(sys.argv[1:]) File "main.py", line 534, in main phase="target_train", File "/Users/srbowman/jiant/src/trainer.py", line 594, in train output_dict = self._forward(batch, task=task) File "/Users/srbowman/jiant/src/trainer.py", line 1035, in _forward model_out = self._model.forward(task, tensor_batch) File "/Users/srbowman/jiant/src/models.py", line 830, in forward out = self._span_forward(batch, task, predict) File "/Users/srbowman/jiant/src/models.py", line 917, in _span_forward out = module.forward(batch, sent_embs, sent_mask, task, predict) File "/Users/srbowman/jiant/src/modules/span_modules.py", line 134, in forward out["loss"] = self.compute_loss(logits, batch["labels"].squeeze(dim=1), task) File "/Users/srbowman/jiant/src/modules/span_modules.py", line 184, in compute_loss raise ValueError("Unsupported loss type '%s' " "for edge probing." % self.loss_type) ValueError: Unsupported loss type '' for edge probing. Traceback (most recent call last): File "main.py", line 577, in <module> raise e # re-raise exception, in case debugger is attached. File "main.py", line 566, in <module> main(sys.argv[1:]) File "main.py", line 534, in main phase="target_train", File "/Users/srbowman/jiant/src/trainer.py", line 594, in train output_dict = self._forward(batch, task=task) File "/Users/srbowman/jiant/src/trainer.py", line 1035, in _forward model_out = self._model.forward(task, tensor_batch) File "/Users/srbowman/jiant/src/models.py", line 830, in forward out = self._span_forward(batch, task, predict) File "/Users/srbowman/jiant/src/models.py", line 917, in _span_forward out = module.forward(batch, sent_embs, sent_mask, task, predict) File "/Users/srbowman/jiant/src/modules/span_modules.py", line 134, in forward out["loss"] = self.compute_loss(logits, batch["labels"].squeeze(dim=1), task) File "/Users/srbowman/jiant/src/modules/span_modules.py", line 184, in compute_loss raise ValueError("Unsupported loss type '%s' " "for edge probing." % self.loss_type) ValueError: Unsupported loss type '' for edge probing.
ValueError
def make_one_hot(batch, depth=2): """ Creates a one-hot embedding of dimension 2. Parameters: batch: list of size batch_size of class predictions Returns: one hot encoding of size [batch_size, 2] """ ones = torch.sparse.torch.eye(depth) if torch.cuda.is_available(): ones = ones.cuda() return ones.index_select(0, batch)
def make_one_hot(batch, depth=2): """ Creates a one-hot embedding of dimension 2. Parameters: batch: list of size batch_size of class predictions Returns: one hot encoding of size [batch_size, 2] """ ones = torch.sparse.torch.eye(depth).cuda() return ones.index_select(0, batch)
https://github.com/nyu-mll/jiant/issues/773
Traceback (most recent call last): File "main.py", line 566, in <module> main(sys.argv[1:]) File "main.py", line 534, in main phase="target_train", File "/Users/srbowman/jiant/src/trainer.py", line 594, in train output_dict = self._forward(batch, task=task) File "/Users/srbowman/jiant/src/trainer.py", line 1035, in _forward model_out = self._model.forward(task, tensor_batch) File "/Users/srbowman/jiant/src/models.py", line 830, in forward out = self._span_forward(batch, task, predict) File "/Users/srbowman/jiant/src/models.py", line 917, in _span_forward out = module.forward(batch, sent_embs, sent_mask, task, predict) File "/Users/srbowman/jiant/src/modules/span_modules.py", line 134, in forward out["loss"] = self.compute_loss(logits, batch["labels"].squeeze(dim=1), task) File "/Users/srbowman/jiant/src/modules/span_modules.py", line 184, in compute_loss raise ValueError("Unsupported loss type '%s' " "for edge probing." % self.loss_type) ValueError: Unsupported loss type '' for edge probing. Traceback (most recent call last): File "main.py", line 577, in <module> raise e # re-raise exception, in case debugger is attached. File "main.py", line 566, in <module> main(sys.argv[1:]) File "main.py", line 534, in main phase="target_train", File "/Users/srbowman/jiant/src/trainer.py", line 594, in train output_dict = self._forward(batch, task=task) File "/Users/srbowman/jiant/src/trainer.py", line 1035, in _forward model_out = self._model.forward(task, tensor_batch) File "/Users/srbowman/jiant/src/models.py", line 830, in forward out = self._span_forward(batch, task, predict) File "/Users/srbowman/jiant/src/models.py", line 917, in _span_forward out = module.forward(batch, sent_embs, sent_mask, task, predict) File "/Users/srbowman/jiant/src/modules/span_modules.py", line 134, in forward out["loss"] = self.compute_loss(logits, batch["labels"].squeeze(dim=1), task) File "/Users/srbowman/jiant/src/modules/span_modules.py", line 184, in compute_loss raise ValueError("Unsupported loss type '%s' " "for edge probing." % self.loss_type) ValueError: Unsupported loss type '' for edge probing.
ValueError
def parse(self, file): data = [] file = EncodedIO(file) file = io.TextIOWrapper(file, encoding=file.encoding) # Add check exception field_parsers = { "ne": lambda line, i: conllu.parser.parse_nullable_value(line[i]), } gen_parser = conllu.parse_incr( file, fields=("form", "ne"), field_parsers=field_parsers ) try: for sentence in gen_parser: if not sentence: continue if len(data) >= settings.IMPORT_BATCH_SIZE: yield data data = [] words, labels = [], [] for item in sentence: word = item.get("form") tag = item.get("ne") if tag is not None: char_left = sum(map(len, words)) + len(words) char_right = char_left + len(word) span = [char_left, char_right, tag] labels.append(span) words.append(word) # Create and add JSONL data.append({"text": " ".join(words), "labels": labels}) except conllu.parser.ParseException as e: raise FileParseException(line_num=-1, line=str(e)) if data: yield data
def parse(self, file): data = [] file = io.TextIOWrapper(file, encoding="utf-8") # Add check exception field_parsers = { "ne": lambda line, i: conllu.parser.parse_nullable_value(line[i]), } gen_parser = conllu.parse_incr( file, fields=("form", "ne"), field_parsers=field_parsers ) try: for sentence in gen_parser: if not sentence: continue if len(data) >= settings.IMPORT_BATCH_SIZE: yield data data = [] words, labels = [], [] for item in sentence: word = item.get("form") tag = item.get("ne") if tag is not None: char_left = sum(map(len, words)) + len(words) char_right = char_left + len(word) span = [char_left, char_right, tag] labels.append(span) words.append(word) # Create and add JSONL data.append({"text": " ".join(words), "labels": labels}) except conllu.parser.ParseException as e: raise FileParseException(line_num=-1, line=str(e)) if data: yield data
https://github.com/doccano/doccano/issues/88
Traceback (most recent call last): File "/app/server/views.py", line 121, in post documents = self.csv_to_documents(project, file) File "/app/server/views.py", line 77, in csv_to_documents maybe_header = next(reader) File "/virtualenvs/doccano-HEgudFLz/bin/../lib/python3.6/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
UnicodeDecodeError
def parse(self, file): file = EncodedIO(file) file = io.TextIOWrapper(file, encoding=file.encoding) while True: batch = list(itertools.islice(file, settings.IMPORT_BATCH_SIZE)) if not batch: break yield [{"text": line.strip()} for line in batch]
def parse(self, file): file = io.TextIOWrapper(file, encoding="utf-8") while True: batch = list(itertools.islice(file, settings.IMPORT_BATCH_SIZE)) if not batch: break yield [{"text": line.strip()} for line in batch]
https://github.com/doccano/doccano/issues/88
Traceback (most recent call last): File "/app/server/views.py", line 121, in post documents = self.csv_to_documents(project, file) File "/app/server/views.py", line 77, in csv_to_documents maybe_header = next(reader) File "/virtualenvs/doccano-HEgudFLz/bin/../lib/python3.6/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
UnicodeDecodeError
def parse(self, file): file = EncodedIO(file) file = io.TextIOWrapper(file, encoding=file.encoding) reader = csv.reader(file) yield from ExcelParser.parse_excel_csv_reader(reader)
def parse(self, file): file = io.TextIOWrapper(file, encoding="utf-8") reader = csv.reader(file) yield from ExcelParser.parse_excel_csv_reader(reader)
https://github.com/doccano/doccano/issues/88
Traceback (most recent call last): File "/app/server/views.py", line 121, in post documents = self.csv_to_documents(project, file) File "/app/server/views.py", line 77, in csv_to_documents maybe_header = next(reader) File "/virtualenvs/doccano-HEgudFLz/bin/../lib/python3.6/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
UnicodeDecodeError
def parse(self, file): file = EncodedIO(file) file = io.TextIOWrapper(file, encoding=file.encoding) data = [] for i, line in enumerate(file, start=1): if len(data) >= settings.IMPORT_BATCH_SIZE: yield data data = [] try: j = json.loads(line) j["meta"] = json.dumps(j.get("meta", {})) data.append(j) except json.decoder.JSONDecodeError: raise FileParseException(line_num=i, line=line) if data: yield data
def parse(self, file): file = io.TextIOWrapper(file, encoding="utf-8") data = [] for i, line in enumerate(file, start=1): if len(data) >= settings.IMPORT_BATCH_SIZE: yield data data = [] try: j = json.loads(line) j["meta"] = json.dumps(j.get("meta", {})) data.append(j) except json.decoder.JSONDecodeError: raise FileParseException(line_num=i, line=line) if data: yield data
https://github.com/doccano/doccano/issues/88
Traceback (most recent call last): File "/app/server/views.py", line 121, in post documents = self.csv_to_documents(project, file) File "/app/server/views.py", line 77, in csv_to_documents maybe_header = next(reader) File "/virtualenvs/doccano-HEgudFLz/bin/../lib/python3.6/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
UnicodeDecodeError
def label_per_data(self, project): annotation_class = project.get_annotation_class() return annotation_class.objects.get_label_per_data(project=project)
def label_per_data(self, project): label_count = Counter() user_count = Counter() annotation_class = project.get_annotation_class() docs = project.documents.all() annotations = annotation_class.objects.filter(document_id__in=docs.all()) for d in annotations.values("label__text", "user__username").annotate( Count("label"), Count("user") ): label_count[d["label__text"]] += d["label__count"] user_count[d["user__username"]] += d["user__count"] return label_count, user_count
https://github.com/doccano/doccano/issues/268
Internal Server Error: /v1/projects/4/statistics Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch response = handler(request, *args, **kwargs) File "/doccano/app/api/views.py", line 70, in get label_count, user_count = self.label_per_data(p) File "/doccano/app/api/views.py", line 94, in label_per_data for d in annotations.values('label__text', 'user__username').annotate(Count('label'), Count('user')): File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 750, in values clone = self._values(*fields, **expressions) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 745, in _values clone.query.set_values(fields) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1987, in set_values self.add_fields(field_names, True) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1735, in add_fields join_info = self.setup_joins(name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1473, in setup_joins names[:pivot], opts, allow_many, fail_on_missing=True, File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1389, in names_to_path "Choices are: %s" % (name, ", ".join(available))) django.core.exceptions.FieldError: Cannot resolve keyword 'label' into field. Choices are: created_at, document, document_id, id, manual, prob, text, updated_at, user, user_id
django.core.exceptions.FieldError
def get(cls, language): try: if PYCOUNTRY: lang = ( languages.get(alpha_2=language) or languages.get(alpha_3=language) or languages.get(bibliographic=language) or languages.get(name=language) ) if not lang: raise KeyError(language) return Language( # some languages don't have an alpha_2 code getattr(lang, "alpha_2", ""), lang.alpha_3, lang.name, getattr(lang, "bibliographic", ""), ) else: lang = None if len(language) == 2: lang = languages.get(alpha2=language) elif len(language) == 3: for code_type in ["part2b", "part2t", "part3"]: try: lang = languages.get(**{code_type: language}) break except KeyError: pass if not lang: raise KeyError(language) else: raise KeyError(language) return Language( lang.alpha2, lang.part3, lang.name, lang.part2b or lang.part2t ) except (LookupError, KeyError): raise LookupError("Invalid language code: {0}".format(language))
def get(cls, language): try: if PYCOUNTRY: # lookup workaround for alpha_2 language codes lang = ( languages.get(alpha_2=language) if re.match(r"^[a-z]{2}$", language) else languages.lookup(language) ) return Language( lang.alpha_2, lang.alpha_3, lang.name, getattr(lang, "bibliographic", None), ) else: lang = None if len(language) == 2: lang = languages.get(alpha2=language) elif len(language) == 3: for code_type in ["part2b", "part2t", "part3"]: try: lang = languages.get(**{code_type: language}) break except KeyError: pass if not lang: raise KeyError(language) else: raise KeyError(language) return Language( lang.alpha2, lang.part3, lang.name, lang.part2b or lang.part2t ) except (LookupError, KeyError): raise LookupError("Invalid language code: {0}".format(language))
https://github.com/streamlink/streamlink/issues/3517
$ streamlink --loglevel debug https://www.raiplay.it/dirette/rai1 [cli][debug] OS: Linux-5.4.80-gentoo-r1-2-x86_64-Intel-R-_Core-TM-2_Duo_CPU_E8400_@_3.00GHz-with-glibc2.2.5 [cli][debug] Python: 3.8.7 [cli][debug] Streamlink: 2.0.0+25.g7a74e18 [cli][debug] Requests(2.25.1), Socks(1.7.1), Websocket(0.57.0) [cli][info] Found matching plugin raiplay for URL https://www.raiplay.it/dirette/rai1 [plugins.raiplay][debug] Found JSON URL: https://www.raiplay.it/dirette/rai1.json [plugins.raiplay][debug] Found stream URL: https://mediapolis.rai.it/relinker/relinkerServlet.htm?cont=2606803 [utils.l10n][debug] Language code: en_US Traceback (most recent call last): File "/usr/bin/streamlink", line 33, in <module> sys.exit(load_entry_point('streamlink==2.0.0+25.g7a74e18', 'console_scripts', 'streamlink')()) File "/usr/lib/python3.8/site-packages/streamlink_cli/main.py", line 1052, in main handle_url() File "/usr/lib/python3.8/site-packages/streamlink_cli/main.py", line 580, in handle_url streams = fetch_streams(plugin) File "/usr/lib/python3.8/site-packages/streamlink_cli/main.py", line 459, in fetch_streams return plugin.streams(stream_types=args.stream_types, File "/usr/lib/python3.8/site-packages/streamlink/plugin/plugin.py", line 323, in streams ostreams = list(ostreams) File "/usr/lib/python3.8/site-packages/streamlink/plugins/raiplay.py", line 49, in _get_streams yield from HLSStream.parse_variant_playlist(self.session, stream_url).items() File "/usr/lib/python3.8/site-packages/streamlink/stream/hls.py", line 494, in parse_variant_playlist if not default_audio and (media.autoselect and locale.equivalent(language=media.language)): File "/usr/lib/python3.8/site-packages/streamlink/utils/l10n.py", line 155, in equivalent equivalent = equivalent and (not language or self.language == self.get_language(language)) File "/usr/lib/python3.8/site-packages/streamlink/utils/l10n.py", line 169, in get_language return Language.get(language) File "/usr/lib/python3.8/site-packages/streamlink/utils/l10n.py", line 73, in get return Language(lang.alpha_2, lang.alpha_3, lang.name, getattr(lang, "bibliographic", None)) File "/usr/lib/python3.8/site-packages/pycountry/db.py", line 19, in __getattr__ raise AttributeError AttributeError
AttributeError
def close(self): if self.closed: return log.debug("Closing ffmpeg thread") if self.process: # kill ffmpeg self.process.kill() self.process.stdout.close() # close the streams for stream in self.streams: if hasattr(stream, "close") and callable(stream.close): stream.close() log.debug("Closed all the substreams") if self.close_errorlog: self.errorlog.close() self.errorlog = None super().close()
def close(self): log.debug("Closing ffmpeg thread") if self.process: # kill ffmpeg self.process.kill() self.process.stdout.close() # close the streams for stream in self.streams: if hasattr(stream, "close"): stream.close() log.debug("Closed all the substreams") if self.close_errorlog: self.errorlog.close() self.errorlog = None
https://github.com/streamlink/streamlink/issues/3357
$ streamlink "https://www.youtube.com/watch?v=VaU6GR8OHNU" -l trace [16:51:11.763092][cli][debug] OS: Linux-5.8.0-29-generic-x86_64-with-glibc2.32 [16:51:11.763170][cli][debug] Python: 3.8.6 [16:51:11.763193][cli][debug] Streamlink: 1.7.0+21.g70dc809 [16:51:11.763212][cli][debug] Requests(2.25.0), Socks(1.7.1), Websocket(0.57.0) [16:51:11.763245][cli][info] Found matching plugin youtube for URL https://www.youtube.com/watch?v=VaU6GR8OHNU [16:51:11.763275][plugin.youtube][debug] Video ID from URL [16:51:11.763295][plugin.youtube][debug] Using video ID: VaU6GR8OHNU [16:51:12.669559][plugin.youtube][debug] get_video_info - 1: Found data [16:51:12.670741][plugin.youtube][debug] MuxedStream: v 135 a 251 = 480p [16:51:12.670780][plugin.youtube][debug] MuxedStream: v 133 a 251 = 240p [16:51:12.670804][plugin.youtube][debug] MuxedStream: v 160 a 251 = 144p [16:51:12.671317][cli][info] Available streams: audio_mp4a, audio_opus, 144p (worst), 240p, 360p, 480p (best) [16:51:12.671355][cli][info] Opening stream: 480p (muxed-stream) [16:51:12.671386][stream.ffmpegmux][debug] Opening http substream [16:51:12.750200][stream.ffmpegmux][debug] Opening http substream [16:51:12.813040][stream.ffmpegmux][debug] ffmpeg command: /usr/bin/ffmpeg -nostats -y -i /tmp/ffmpeg-9607-784 -i /tmp/ffmpeg-9607-270 -c:v copy -c:a copy -map 0 -map 1 -f matroska pipe:1 [16:51:12.813226][stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-9607-784 [16:51:12.813344][stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-9607-270 [16:51:12.815867][cli][debug] Pre-buffering 8192 bytes [16:51:12.875782][cli][info] Starting player: /usr/bin/mpv [16:51:12.876152][cli.output][debug] Opening subprocess: /usr/bin/mpv "--title=Christmas Music 2020 🎅 Top Christmas Songs Playlist 2020 🎄 Best Christmas Songs Ever" - [16:51:13.378673][cli][debug] Writing stream to output [16:51:19.777326][cli][info] Player closed [16:51:19.777459][stream.ffmpegmux][debug] Closing ffmpeg thread [16:51:19.779916][stream.ffmpegmux][error] Pipe copy aborted: /tmp/ffmpeg-9607-270 [16:51:19.780000][stream.ffmpegmux][error] Pipe copy aborted: /tmp/ffmpeg-9607-784 [16:51:26.824121][stream.ffmpegmux][debug] Closed all the substreams [16:51:26.824246][cli][info] Stream ended [16:51:26.824434][cli][info] Closing currently open stream... [16:51:26.824477][stream.ffmpegmux][debug] Closing ffmpeg thread [16:51:26.824539][stream.ffmpegmux][debug] Closed all the substreams --- Logging error --- Traceback (most recent call last): File "/usr/lib/python3.8/logging/__init__.py", line 1081, in emit msg = self.format(record) File "/usr/lib/python3.8/logging/__init__.py", line 925, in format return fmt.format(record) File "venv3/lib/python3.8/site-packages/streamlink/logger.py", line 54, in format return super().format(record) File "/usr/lib/python3.8/logging/__init__.py", line 666, in format record.asctime = self.formatTime(record, self.datefmt) File "venv3/lib/python3.8/site-packages/streamlink/logger.py", line 41, in formatTime return tdt.strftime(datefmt or self.default_time_format) ImportError: sys.meta_path is None, Python is likely shutting down Call stack: File "venv3/lib/python3.8/site-packages/streamlink/stream/ffmpegmux.py", line 158, in close log.debug("Closing ffmpeg thread") Message: 'Closing ffmpeg thread' Arguments: () --- Logging error --- Traceback (most recent call last): File "/usr/lib/python3.8/logging/__init__.py", line 1081, in emit msg = self.format(record) File "/usr/lib/python3.8/logging/__init__.py", line 925, in format return fmt.format(record) File "venv3/lib/python3.8/site-packages/streamlink/logger.py", line 54, in format return super().format(record) File "/usr/lib/python3.8/logging/__init__.py", line 666, in format record.asctime = self.formatTime(record, self.datefmt) File "venv3/lib/python3.8/site-packages/streamlink/logger.py", line 41, in formatTime return tdt.strftime(datefmt or self.default_time_format) ImportError: sys.meta_path is None, Python is likely shutting down Call stack: File "venv3/lib/python3.8/site-packages/streamlink/stream/ffmpegmux.py", line 169, in close log.debug("Closed all the substreams") Message: 'Closed all the substreams' Arguments: ()
ImportError
def authenticate(self): try: data = self._api_call("authenticate", {"auth": self.auth}, schema=_login_schema) except CrunchyrollAPIError: self.auth = None self.cache.set("auth", None, expires_at=0) log.warning("Saved credentials have expired") return log.debug("Credentials expire at: {}".format(data["expires"])) self.cache.set("auth", self.auth, expires_at=data["expires"]) return data
def authenticate(self): data = self._api_call("authenticate", {"auth": self.auth}, schema=_login_schema) self.auth = data["auth"] self.cache.set("auth", data["auth"], expires_at=data["expires"]) return data
https://github.com/streamlink/streamlink/issues/3148
Traceback (most recent call last): File "runpy.py", line 193, in _run_module_as_main File "runpy.py", line 85, in _run_code File "C:\Users\kg\AppData\Local\Streamlink\bin\streamlink.exe\__main__.py", line 18, in <module> File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink_cli\main.py", line 1024, in main handle_url() File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink_cli\main.py", line 585, in handle_url streams = fetch_streams(plugin) File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink_cli\main.py", line 465, in fetch_streams sorting_excludes=args.stream_sorting_excludes) File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink\plugin\plugin.py", line 317, in streams ostreams = self._get_streams() File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink\plugins\crunchyroll.py", line 306, in _get_streams api = self._create_api() File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink\plugins\crunchyroll.py", line 369, in _create_api login = api.authenticate() File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink\plugins\crunchyroll.py", line 217, in authenticate data = self._api_call("authenticate", {"auth": self.auth}, schema=_login_schema) File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink\plugins\crunchyroll.py", line 173, in _api_call raise CrunchyrollAPIError(err_msg, err_code) streamlink.plugin.crunchyroll.CrunchyrollAPIError: User could not be found.
streamlink.plugin.crunchyroll.CrunchyrollAPIError
def _get_streams(self): api = self._create_api() match = _url_re.match(self.url) media_id = int(match.group("media_id")) try: # the media.stream_data field is required, no stream data is returned otherwise info = api.get_info( media_id, fields=["media.stream_data"], schema=_media_schema ) except CrunchyrollAPIError as err: raise PluginError("Media lookup error: {0}".format(err.msg)) if not info: return streams = {} # The adaptive quality stream sometimes a subset of all the other streams listed, ultra is no included has_adaptive = any([s["quality"] == "adaptive" for s in info["streams"]]) if has_adaptive: log.debug("Loading streams from adaptive playlist") for stream in filter(lambda x: x["quality"] == "adaptive", info["streams"]): for q, s in HLSStream.parse_variant_playlist( self.session, stream["url"] ).items(): # rename the bitrates to low, mid, or high. ultra doesn't seem to appear in the adaptive streams name = STREAM_NAMES.get(q, q) streams[name] = s # If there is no adaptive quality stream then parse each individual result for stream in info["streams"]: if stream["quality"] != "adaptive": # the video_encode_id indicates that the stream is not a variant playlist if "video_encode_id" in stream: streams[stream["quality"]] = HLSStream(self.session, stream["url"]) else: # otherwise the stream url is actually a list of stream qualities for q, s in HLSStream.parse_variant_playlist( self.session, stream["url"] ).items(): # rename the bitrates to low, mid, or high. ultra doesn't seem to appear in the adaptive streams name = STREAM_NAMES.get(q, q) streams[name] = s return streams
def _get_streams(self): api = self._create_api() match = _url_re.match(self.url) media_id = int(match.group("media_id")) try: # the media.stream_data field is required, no stream data is returned otherwise info = api.get_info( media_id, fields=["media.stream_data"], schema=_media_schema ) except CrunchyrollAPIError as err: raise PluginError("Media lookup error: {0}".format(err.msg)) if not info: return streams = {} # The adaptive quality stream sometimes a subset of all the other streams listed, ultra is no included has_adaptive = any([s["quality"] == "adaptive" for s in info["streams"]]) if has_adaptive: self.logger.debug("Loading streams from adaptive playlist") for stream in filter(lambda x: x["quality"] == "adaptive", info["streams"]): for q, s in HLSStream.parse_variant_playlist( self.session, stream["url"] ).items(): # rename the bitrates to low, mid, or high. ultra doesn't seem to appear in the adaptive streams name = STREAM_NAMES.get(q, q) streams[name] = s # If there is no adaptive quality stream then parse each individual result for stream in info["streams"]: if stream["quality"] != "adaptive": # the video_encode_id indicates that the stream is not a variant playlist if "video_encode_id" in stream: streams[stream["quality"]] = HLSStream(self.session, stream["url"]) else: # otherwise the stream url is actually a list of stream qualities for q, s in HLSStream.parse_variant_playlist( self.session, stream["url"] ).items(): # rename the bitrates to low, mid, or high. ultra doesn't seem to appear in the adaptive streams name = STREAM_NAMES.get(q, q) streams[name] = s return streams
https://github.com/streamlink/streamlink/issues/3148
Traceback (most recent call last): File "runpy.py", line 193, in _run_module_as_main File "runpy.py", line 85, in _run_code File "C:\Users\kg\AppData\Local\Streamlink\bin\streamlink.exe\__main__.py", line 18, in <module> File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink_cli\main.py", line 1024, in main handle_url() File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink_cli\main.py", line 585, in handle_url streams = fetch_streams(plugin) File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink_cli\main.py", line 465, in fetch_streams sorting_excludes=args.stream_sorting_excludes) File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink\plugin\plugin.py", line 317, in streams ostreams = self._get_streams() File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink\plugins\crunchyroll.py", line 306, in _get_streams api = self._create_api() File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink\plugins\crunchyroll.py", line 369, in _create_api login = api.authenticate() File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink\plugins\crunchyroll.py", line 217, in authenticate data = self._api_call("authenticate", {"auth": self.auth}, schema=_login_schema) File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink\plugins\crunchyroll.py", line 173, in _api_call raise CrunchyrollAPIError(err_msg, err_code) streamlink.plugin.crunchyroll.CrunchyrollAPIError: User could not be found.
streamlink.plugin.crunchyroll.CrunchyrollAPIError
def _create_api(self): """Creates a new CrunchyrollAPI object, initiates it's session and tries to authenticate it either by using saved credentials or the user's username and password. """ if self.options.get("purge_credentials"): self.cache.set("session_id", None, 0) self.cache.set("auth", None, 0) self.cache.set("session_id", None, 0) # use the crunchyroll locale as an override, for backwards compatibility locale = self.get_option("locale") or self.session.localization.language_code api = CrunchyrollAPI( self.cache, self.session, session_id=self.get_option("session_id"), locale=locale, ) if not self.get_option("session_id"): log.debug("Creating session with locale: {0}", locale) api.start_session() if api.auth: log.debug("Using saved credentials") login = api.authenticate() if login: log.info( "Successfully logged in as '{0}'", login["user"]["username"] or login["user"]["email"], ) if not api.auth and self.options.get("username"): try: log.debug("Attempting to login using username and password") api.login(self.options.get("username"), self.options.get("password")) login = api.authenticate() log.info( "Logged in as '{0}'", login["user"]["username"] or login["user"]["email"], ) except CrunchyrollAPIError as err: raise PluginError("Authentication error: {0}".format(err.msg)) if not api.auth: log.warning( "No authentication provided, you won't be able to access " "premium restricted content" ) return api
def _create_api(self): """Creates a new CrunchyrollAPI object, initiates it's session and tries to authenticate it either by using saved credentials or the user's username and password. """ if self.options.get("purge_credentials"): self.cache.set("session_id", None, 0) self.cache.set("auth", None, 0) self.cache.set("session_id", None, 0) # use the crunchyroll locale as an override, for backwards compatibility locale = self.get_option("locale") or self.session.localization.language_code api = CrunchyrollAPI( self.cache, self.session, session_id=self.get_option("session_id"), locale=locale, ) if not self.get_option("session_id"): self.logger.debug("Creating session with locale: {0}", locale) api.start_session() if api.auth: self.logger.debug("Using saved credentials") login = api.authenticate() self.logger.info( "Successfully logged in as '{0}'", login["user"]["username"] or login["user"]["email"], ) elif self.options.get("username"): try: self.logger.debug("Attempting to login using username and password") api.login(self.options.get("username"), self.options.get("password")) login = api.authenticate() self.logger.info( "Logged in as '{0}'", login["user"]["username"] or login["user"]["email"], ) except CrunchyrollAPIError as err: raise PluginError("Authentication error: {0}".format(err.msg)) else: self.logger.warning( "No authentication provided, you won't be able to access " "premium restricted content" ) return api
https://github.com/streamlink/streamlink/issues/3148
Traceback (most recent call last): File "runpy.py", line 193, in _run_module_as_main File "runpy.py", line 85, in _run_code File "C:\Users\kg\AppData\Local\Streamlink\bin\streamlink.exe\__main__.py", line 18, in <module> File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink_cli\main.py", line 1024, in main handle_url() File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink_cli\main.py", line 585, in handle_url streams = fetch_streams(plugin) File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink_cli\main.py", line 465, in fetch_streams sorting_excludes=args.stream_sorting_excludes) File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink\plugin\plugin.py", line 317, in streams ostreams = self._get_streams() File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink\plugins\crunchyroll.py", line 306, in _get_streams api = self._create_api() File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink\plugins\crunchyroll.py", line 369, in _create_api login = api.authenticate() File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink\plugins\crunchyroll.py", line 217, in authenticate data = self._api_call("authenticate", {"auth": self.auth}, schema=_login_schema) File "C:\Users\kg\AppData\Local\Streamlink\pkgs\streamlink\plugins\crunchyroll.py", line 173, in _api_call raise CrunchyrollAPIError(err_msg, err_code) streamlink.plugin.crunchyroll.CrunchyrollAPIError: User could not be found.
streamlink.plugin.crunchyroll.CrunchyrollAPIError
def create_title(plugin=None): if args.title and plugin: title = LazyFormatter.format( maybe_decode(args.title, get_filesystem_encoding()), title=lambda: plugin.get_title() or DEFAULT_STREAM_METADATA["title"], author=lambda: plugin.get_author() or DEFAULT_STREAM_METADATA["author"], category=lambda: plugin.get_category() or DEFAULT_STREAM_METADATA["category"], game=lambda: plugin.get_category() or DEFAULT_STREAM_METADATA["game"], url=plugin.url, ) else: title = args.url return title
def create_title(plugin=None): if args.title and plugin: title = LazyFormatter.format( maybe_encode(args.title), title=lambda: plugin.get_title() or DEFAULT_STREAM_METADATA["title"], author=lambda: plugin.get_author() or DEFAULT_STREAM_METADATA["author"], category=lambda: plugin.get_category() or DEFAULT_STREAM_METADATA["category"], game=lambda: plugin.get_category() or DEFAULT_STREAM_METADATA["game"], url=plugin.url, ) else: title = args.url return title
https://github.com/streamlink/streamlink/issues/2444
OS: macOS 10.14.2 Python: 2.7.14 Streamlink: 1.1.1 Requests(2.21.0), Socks(1.6.7), Websocket(0.47.0) Found matching plugin twitch for URL twitch.tv/quickybaby Plugin specific arguments: --twitch-oauth-token=******** (oauth_token) --twitch-disable-hosting=True (disable_hosting) --twitch-disable-ads=True (disable_ads) Getting live HLS streams for quickybaby Attempting to authenticate using OAuth token Successfully logged in as DELETE [utils.l10n][debug] Language code: en_US Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best) Opening stream: 1080p60 (hls) Starting player: /Applications/mpv.app/Contents/MacOS/mpv Traceback (most recent call last): File "/usr/local/bin/streamlink", line 11, in <module> load_entry_point('streamlink==1.1.1', 'console_scripts', 'streamlink')() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 1033, in main handle_url() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 594, in handle_url handle_stream(plugin, streams, stream_name) File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 437, in handle_stream success = output_stream_passthrough(plugin, stream) File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 262, in output_stream_passthrough output.open() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 24, in open self._open() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 219, in _open self._open_call() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 234, in _open_call log.debug(u"Calling: {0}".format(fargs)) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 141: ordinal not in range(128)
UnicodeDecodeError
def _create_arguments(self): if self.namedpipe: filename = self.namedpipe.path elif self.filename: filename = self.filename elif self.http: filename = self.http.url else: filename = "-" extra_args = [] if self.title is not None: # vlc if self.player_name == "vlc": # see https://wiki.videolan.org/Documentation:Format_String/, allow escaping with \$ self.title = self.title.replace("$", "$$").replace(r"\$$", "$") extra_args.extend(["--input-title-format", self.title]) # mpv if self.player_name == "mpv": # see https://mpv.io/manual/stable/#property-expansion, allow escaping with \$, respect mpv's $> self.title = self._mpv_title_escape(self.title) extra_args.append("--title={}".format(self.title)) # potplayer if self.player_name == "potplayer": if filename != "-": # PotPlayer - About - Command Line # You can specify titles for URLs by separating them with a backslash (\) at the end of URLs. # eg. "http://...\title of this url" self.title = self.title.replace('"', "") filename = filename[:-1] + "\\" + self.title + filename[-1] args = self.args.format(filename=filename) cmd = self.cmd # player command if is_win32: eargs = maybe_decode(subprocess.list2cmdline(extra_args)) # do not insert and extra " " when there are no extra_args return " ".join([cmd] + ([eargs] if eargs else []) + [args]) return shlex.split(cmd) + extra_args + shlex.split(args)
def _create_arguments(self): if self.namedpipe: filename = self.namedpipe.path elif self.filename: filename = self.filename elif self.http: filename = self.http.url else: filename = "-" extra_args = [] if self.title is not None: # vlc if self.player_name == "vlc": # see https://wiki.videolan.org/Documentation:Format_String/, allow escaping with \$ self.title = self.title.replace("$", "$$").replace(r"\$$", "$") extra_args.extend(["--input-title-format", self.title]) # mpv if self.player_name == "mpv": # see https://mpv.io/manual/stable/#property-expansion, allow escaping with \$, respect mpv's $> self.title = self._mpv_title_escape(self.title) extra_args.append("--title={}".format(self.title)) # potplayer if self.player_name == "potplayer": if filename != "-": # PotPlayer - About - Command Line # You can specify titles for URLs by separating them with a backslash (\) at the end of URLs. # eg. "http://...\title of this url" self.title = self.title.replace('"', "") filename = filename[:-1] + "\\" + self.title + filename[-1] args = self.args.format(filename=filename) cmd = self.cmd # player command if is_win32: eargs = maybe_decode(subprocess.list2cmdline(extra_args)) # do not insert and extra " " when there are no extra_args return maybe_encode( " ".join([cmd] + ([eargs] if eargs else []) + [args]), encoding=get_filesystem_encoding(), ) return shlex.split(cmd) + extra_args + shlex.split(args)
https://github.com/streamlink/streamlink/issues/2444
OS: macOS 10.14.2 Python: 2.7.14 Streamlink: 1.1.1 Requests(2.21.0), Socks(1.6.7), Websocket(0.47.0) Found matching plugin twitch for URL twitch.tv/quickybaby Plugin specific arguments: --twitch-oauth-token=******** (oauth_token) --twitch-disable-hosting=True (disable_hosting) --twitch-disable-ads=True (disable_ads) Getting live HLS streams for quickybaby Attempting to authenticate using OAuth token Successfully logged in as DELETE [utils.l10n][debug] Language code: en_US Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best) Opening stream: 1080p60 (hls) Starting player: /Applications/mpv.app/Contents/MacOS/mpv Traceback (most recent call last): File "/usr/local/bin/streamlink", line 11, in <module> load_entry_point('streamlink==1.1.1', 'console_scripts', 'streamlink')() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 1033, in main handle_url() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 594, in handle_url handle_stream(plugin, streams, stream_name) File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 437, in handle_stream success = output_stream_passthrough(plugin, stream) File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 262, in output_stream_passthrough output.open() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 24, in open self._open() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 219, in _open self._open_call() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 234, in _open_call log.debug(u"Calling: {0}".format(fargs)) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 141: ordinal not in range(128)
UnicodeDecodeError
def _open_call(self): args = self._create_arguments() if is_win32: fargs = args else: fargs = subprocess.list2cmdline(args) log.debug("Calling: {0}".format(fargs)) subprocess.call( maybe_encode(args, get_filesystem_encoding()), stdout=self.stdout, stderr=self.stderr, )
def _open_call(self): args = self._create_arguments() if is_win32: fargs = args else: fargs = subprocess.list2cmdline(args) log.debug("Calling: {0}".format(maybe_decode(fargs))) subprocess.call(args, stdout=self.stdout, stderr=self.stderr)
https://github.com/streamlink/streamlink/issues/2444
OS: macOS 10.14.2 Python: 2.7.14 Streamlink: 1.1.1 Requests(2.21.0), Socks(1.6.7), Websocket(0.47.0) Found matching plugin twitch for URL twitch.tv/quickybaby Plugin specific arguments: --twitch-oauth-token=******** (oauth_token) --twitch-disable-hosting=True (disable_hosting) --twitch-disable-ads=True (disable_ads) Getting live HLS streams for quickybaby Attempting to authenticate using OAuth token Successfully logged in as DELETE [utils.l10n][debug] Language code: en_US Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best) Opening stream: 1080p60 (hls) Starting player: /Applications/mpv.app/Contents/MacOS/mpv Traceback (most recent call last): File "/usr/local/bin/streamlink", line 11, in <module> load_entry_point('streamlink==1.1.1', 'console_scripts', 'streamlink')() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 1033, in main handle_url() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 594, in handle_url handle_stream(plugin, streams, stream_name) File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 437, in handle_stream success = output_stream_passthrough(plugin, stream) File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 262, in output_stream_passthrough output.open() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 24, in open self._open() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 219, in _open self._open_call() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 234, in _open_call log.debug(u"Calling: {0}".format(fargs)) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 141: ordinal not in range(128)
UnicodeDecodeError
def _open_subprocess(self): # Force bufsize=0 on all Python versions to avoid writing the # unflushed buffer when closing a broken input pipe args = self._create_arguments() if is_win32: fargs = args else: fargs = subprocess.list2cmdline(args) log.debug("Opening subprocess: {0}".format(fargs)) self.player = subprocess.Popen( maybe_encode(args, get_filesystem_encoding()), stdin=self.stdin, bufsize=0, stdout=self.stdout, stderr=self.stderr, ) # Wait 0.5 seconds to see if program exited prematurely if not self.running: raise OSError("Process exited prematurely") if self.namedpipe: self.namedpipe.open("wb") elif self.http: self.http.open()
def _open_subprocess(self): # Force bufsize=0 on all Python versions to avoid writing the # unflushed buffer when closing a broken input pipe args = self._create_arguments() if is_win32: fargs = args else: fargs = subprocess.list2cmdline(args) log.debug("Opening subprocess: {0}".format(maybe_decode(fargs))) self.player = subprocess.Popen( args, stdin=self.stdin, bufsize=0, stdout=self.stdout, stderr=self.stderr ) # Wait 0.5 seconds to see if program exited prematurely if not self.running: raise OSError("Process exited prematurely") if self.namedpipe: self.namedpipe.open("wb") elif self.http: self.http.open()
https://github.com/streamlink/streamlink/issues/2444
OS: macOS 10.14.2 Python: 2.7.14 Streamlink: 1.1.1 Requests(2.21.0), Socks(1.6.7), Websocket(0.47.0) Found matching plugin twitch for URL twitch.tv/quickybaby Plugin specific arguments: --twitch-oauth-token=******** (oauth_token) --twitch-disable-hosting=True (disable_hosting) --twitch-disable-ads=True (disable_ads) Getting live HLS streams for quickybaby Attempting to authenticate using OAuth token Successfully logged in as DELETE [utils.l10n][debug] Language code: en_US Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best) Opening stream: 1080p60 (hls) Starting player: /Applications/mpv.app/Contents/MacOS/mpv Traceback (most recent call last): File "/usr/local/bin/streamlink", line 11, in <module> load_entry_point('streamlink==1.1.1', 'console_scripts', 'streamlink')() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 1033, in main handle_url() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 594, in handle_url handle_stream(plugin, streams, stream_name) File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 437, in handle_stream success = output_stream_passthrough(plugin, stream) File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 262, in output_stream_passthrough output.open() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 24, in open self._open() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 219, in _open self._open_call() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 234, in _open_call log.debug(u"Calling: {0}".format(fargs)) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 141: ordinal not in range(128)
UnicodeDecodeError
def maybe_encode(text, encoding="utf8"): if is_py2: if isinstance(text, unicode): return text.encode(encoding) else: return text else: return text
def maybe_encode(text, encoding="utf8"): if is_py2: return text.encode(encoding) else: return text
https://github.com/streamlink/streamlink/issues/2444
OS: macOS 10.14.2 Python: 2.7.14 Streamlink: 1.1.1 Requests(2.21.0), Socks(1.6.7), Websocket(0.47.0) Found matching plugin twitch for URL twitch.tv/quickybaby Plugin specific arguments: --twitch-oauth-token=******** (oauth_token) --twitch-disable-hosting=True (disable_hosting) --twitch-disable-ads=True (disable_ads) Getting live HLS streams for quickybaby Attempting to authenticate using OAuth token Successfully logged in as DELETE [utils.l10n][debug] Language code: en_US Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best) Opening stream: 1080p60 (hls) Starting player: /Applications/mpv.app/Contents/MacOS/mpv Traceback (most recent call last): File "/usr/local/bin/streamlink", line 11, in <module> load_entry_point('streamlink==1.1.1', 'console_scripts', 'streamlink')() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 1033, in main handle_url() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 594, in handle_url handle_stream(plugin, streams, stream_name) File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 437, in handle_stream success = output_stream_passthrough(plugin, stream) File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 262, in output_stream_passthrough output.open() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 24, in open self._open() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 219, in _open self._open_call() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 234, in _open_call log.debug(u"Calling: {0}".format(fargs)) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 141: ordinal not in range(128)
UnicodeDecodeError
def _open_call(self): args = self._create_arguments() if is_win32: fargs = args else: fargs = subprocess.list2cmdline(args) log.debug("Calling: {0}".format(maybe_decode(fargs))) subprocess.call(args, stdout=self.stdout, stderr=self.stderr)
def _open_call(self): args = self._create_arguments() if is_win32: fargs = args else: fargs = subprocess.list2cmdline(args) log.debug("Calling: {0}".format(fargs)) subprocess.call(args, stdout=self.stdout, stderr=self.stderr)
https://github.com/streamlink/streamlink/issues/2444
OS: macOS 10.14.2 Python: 2.7.14 Streamlink: 1.1.1 Requests(2.21.0), Socks(1.6.7), Websocket(0.47.0) Found matching plugin twitch for URL twitch.tv/quickybaby Plugin specific arguments: --twitch-oauth-token=******** (oauth_token) --twitch-disable-hosting=True (disable_hosting) --twitch-disable-ads=True (disable_ads) Getting live HLS streams for quickybaby Attempting to authenticate using OAuth token Successfully logged in as DELETE [utils.l10n][debug] Language code: en_US Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best) Opening stream: 1080p60 (hls) Starting player: /Applications/mpv.app/Contents/MacOS/mpv Traceback (most recent call last): File "/usr/local/bin/streamlink", line 11, in <module> load_entry_point('streamlink==1.1.1', 'console_scripts', 'streamlink')() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 1033, in main handle_url() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 594, in handle_url handle_stream(plugin, streams, stream_name) File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 437, in handle_stream success = output_stream_passthrough(plugin, stream) File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 262, in output_stream_passthrough output.open() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 24, in open self._open() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 219, in _open self._open_call() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 234, in _open_call log.debug(u"Calling: {0}".format(fargs)) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 141: ordinal not in range(128)
UnicodeDecodeError
def _open_subprocess(self): # Force bufsize=0 on all Python versions to avoid writing the # unflushed buffer when closing a broken input pipe args = self._create_arguments() if is_win32: fargs = args else: fargs = subprocess.list2cmdline(args) log.debug("Opening subprocess: {0}".format(maybe_decode(fargs))) self.player = subprocess.Popen( args, stdin=self.stdin, bufsize=0, stdout=self.stdout, stderr=self.stderr ) # Wait 0.5 seconds to see if program exited prematurely if not self.running: raise OSError("Process exited prematurely") if self.namedpipe: self.namedpipe.open("wb") elif self.http: self.http.open()
def _open_subprocess(self): # Force bufsize=0 on all Python versions to avoid writing the # unflushed buffer when closing a broken input pipe args = self._create_arguments() if is_win32: fargs = args else: fargs = subprocess.list2cmdline(args) log.debug("Opening subprocess: {0}".format(fargs)) self.player = subprocess.Popen( args, stdin=self.stdin, bufsize=0, stdout=self.stdout, stderr=self.stderr ) # Wait 0.5 seconds to see if program exited prematurely if not self.running: raise OSError("Process exited prematurely") if self.namedpipe: self.namedpipe.open("wb") elif self.http: self.http.open()
https://github.com/streamlink/streamlink/issues/2444
OS: macOS 10.14.2 Python: 2.7.14 Streamlink: 1.1.1 Requests(2.21.0), Socks(1.6.7), Websocket(0.47.0) Found matching plugin twitch for URL twitch.tv/quickybaby Plugin specific arguments: --twitch-oauth-token=******** (oauth_token) --twitch-disable-hosting=True (disable_hosting) --twitch-disable-ads=True (disable_ads) Getting live HLS streams for quickybaby Attempting to authenticate using OAuth token Successfully logged in as DELETE [utils.l10n][debug] Language code: en_US Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best) Opening stream: 1080p60 (hls) Starting player: /Applications/mpv.app/Contents/MacOS/mpv Traceback (most recent call last): File "/usr/local/bin/streamlink", line 11, in <module> load_entry_point('streamlink==1.1.1', 'console_scripts', 'streamlink')() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 1033, in main handle_url() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 594, in handle_url handle_stream(plugin, streams, stream_name) File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 437, in handle_stream success = output_stream_passthrough(plugin, stream) File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py", line 262, in output_stream_passthrough output.open() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 24, in open self._open() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 219, in _open self._open_call() File "/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py", line 234, in _open_call log.debug(u"Calling: {0}".format(fargs)) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 141: ordinal not in range(128)
UnicodeDecodeError
def fetch(self, segment, retries=None): if self.closed or not retries: return try: request_args = copy.deepcopy(self.reader.stream.args) headers = request_args.pop("headers", {}) now = datetime.datetime.now(tz=utc) if segment.available_at > now: time_to_wait = (segment.available_at - now).total_seconds() fname = os.path.basename(urlparse(segment.url).path) log.debug( "Waiting for segment: {fname} ({wait:.01f}s)".format( fname=fname, wait=time_to_wait ) ) sleep_until(segment.available_at) if segment.range: start, length = segment.range if length: end = start + length - 1 else: end = "" headers["Range"] = "bytes={0}-{1}".format(start, end) return self.session.http.get( segment.url, timeout=self.timeout, exception=StreamError, headers=headers, **request_args, ) except StreamError as err: log.error("Failed to open segment {0}: {1}", segment.url, err) return self.fetch(segment, retries - 1)
def fetch(self, segment, retries=None): if self.closed or not retries: return try: headers = {} now = datetime.datetime.now(tz=utc) if segment.available_at > now: time_to_wait = (segment.available_at - now).total_seconds() fname = os.path.basename(urlparse(segment.url).path) log.debug( "Waiting for segment: {fname} ({wait:.01f}s)".format( fname=fname, wait=time_to_wait ) ) sleep_until(segment.available_at) if segment.range: start, length = segment.range if length: end = start + length - 1 else: end = "" headers["Range"] = "bytes={0}-{1}".format(start, end) return self.session.http.get( segment.url, timeout=self.timeout, exception=StreamError, headers=headers ) except StreamError as err: log.error("Failed to open segment {0}: {1}", segment.url, err) return self.fetch(segment, retries - 1)
https://github.com/streamlink/streamlink/issues/2291
$ streamlink https://www.tf1.fr/lci/direct 576p_dash [cli][debug] OS: Linux [cli][debug] Python: 3.6.7 [cli][debug] Streamlink: 1.0.0+3.g4100688.dirty [cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.54.0) [cli][info] Found matching plugin tf1 for URL https://www.tf1.fr/lci/direct [plugin.tf1][debug] Found channel lci [plugin.tf1][debug] Got dash stream https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&amp;st= [utils.l10n][debug] Language code: en_US [stream.dash][debug] Available languages for DASH audio streams: NONE (using: n/a) [plugin.tf1][debug] Got hls stream https://lci-hls-live-ssl.tf1.fr/lci/1/hls/master_4000000.m3u8?e=&amp;st= [utils.l10n][debug] Language code: en_US [cli][info] Available streams: 234p_dash, 360p_dash, 576p_dash, 234p (worst), 360p, 576p_alt, 576p, 720p (best) [cli][info] Opening stream: 576p_dash (dash) [stream.dash][debug] Opening DASH reader for: live_1828_H264 (video/mp4) [stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live_1828_H264)) [stream.dash][debug] Reloading manifest (live_1828_H264:video/mp4) [stream.dash][debug] Opening DASH reader for: live_2328_AAC (audio/mp4) [stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live_2328_AAC)) [stream.dash][debug] Reloading manifest (live_2328_AAC:audio/mp4) [stream.mp4mux-ffmpeg][debug] ffmpeg command: /usr/bin/ffmpeg -nostats -y -i /tmp/ffmpeg-2811-460 -i /tmp/ffmpeg-2811-532 -c:v copy -c:a copy -copyts -f matroska pipe:1 [stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-2811-460 [stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-2811-532 [cli][debug] Pre-buffering 8192 bytes [stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_1828/init.m4v complete Exception in thread Thread-DASHStreamWorker: Traceback (most recent call last): File "src/streamlink/plugin/api/http_session.py", line 166, in request res.raise_for_status() File "env/lib/python3.6/site-packages/requests/models.py", line 940, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&amp;st= During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "src/streamlink/stream/segmented.py", line 59, in run for segment in self.iter_segments(): File "src/streamlink/stream/dash.py", line 97, in iter_segments if not self.reload(): File "src/streamlink/stream/dash.py", line 111, in reload res = self.session.http.get(self.mpd.url, exception=StreamError) File "env/lib/python3.6/site-packages/requests/sessions.py", line 546, in get return self.request('GET', url, **kwargs) File "src/streamlink/plugin/api/http_session.py", line 175, in request raise err streamlink.exceptions.StreamError: Unable to open URL: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&amp;st= (403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&amp;st=) Exception in thread Thread-DASHStreamWorker: Traceback (most recent call last): File "src/streamlink/plugin/api/http_session.py", line 166, in request res.raise_for_status() File "env/lib/python3.6/site-packages/requests/models.py", line 940, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&amp;st= During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "src/streamlink/stream/segmented.py", line 59, in run for segment in self.iter_segments(): File "src/streamlink/stream/dash.py", line 97, in iter_segments if not self.reload(): File "src/streamlink/stream/dash.py", line 111, in reload res = self.session.http.get(self.mpd.url, exception=StreamError) File "env/lib/python3.6/site-packages/requests/sessions.py", line 546, in get return self.request('GET', url, **kwargs) File "src/streamlink/plugin/api/http_session.py", line 175, in request raise err streamlink.exceptions.StreamError: Unable to open URL: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&amp;st= (403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&amp;st=) [stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/init.m4a complete [stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65796000.m4a complete [stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65800000.m4a complete [stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65804000.m4a complete [stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_1828/65792000.m4v complete
requests.exceptions.HTTPError