GIMP python-fu call function plug_in_beautify 'wrong number of parameters' - pdb

I try to use the great Beautify plugin in python command line and I am unable to call the function the right way!
Here is my code:
import os
from gimpfu import *
inputPath = os.path.join('xxxx', 'fire.png')
if(file.lower().endswith(('.png'))):
image = pdb.file_png_load(inputPath, inputPath)
if(file.lower().endswith(('.jpeg', '.jpg'))):
image = pdb.file_jpeg_load(inputPath, inputPath)
drawable = pdb.gimp_image_get_active_layer(image)
pdb.plug_in_beautify(1,image,drawable,67,100)
# Traceback (most recent call last):
# File "<input>", line 1, in <module>
# TypeError: wrong number of parameters
pdb.plug_in_beautify.nparams # = 5
pdb.plug_in_beautify.params
# ((0, 'run-mode', 'The run mode { RUN-INTERACTIVE (0), RUN-NONINTERACTIVE (1) }'),
# (13, 'image', 'Input image'),
# (16, 'drawable', 'Input drawable'),
# (0, 'effect', 'The effect to apply { SOFT_LIGHT (1), WARM (2), SHARPEN (3), SOFT (4), REMOVE_FOG (5), STRONG_CONTRAST (6), SMART_COLOR (7),... PINK_PURPLE_GRADIENG (80), PINK_BLUE_GRADIENT (81) }'),
# (3, 'opacity', 'The effect opacity (0 <= opacity <= 100)'))
So why my function has 'wrong number of parameters' if it expects 5 and I am putting 5?
Can anyone help me with the right syntax?

IMO the run-mode should not be entered
edit:
enter pdb.plug_in_beautify(image,drawable,67,100)
the run-mode is not used (not required) by python

Related

Allennlp: How to use CPU instead of GPU?

I'm running some code that works when there is GPU. But I'm trying to figure out how to run it locally with CPU. Here's the error:
2022-07-06 17:58:39,042 - INFO - allennlp.common.plugins - Plugin allennlp_models available
Traceback (most recent call last):
File "/Users/xiaoqingwan/opt/miniconda3/envs/absa/bin/allennlp", line 8, in <module>
sys.exit(run())
File "/Users/xiaoqingwan/opt/miniconda3/envs/absa/lib/python3.7/site-packages/allennlp/__main__.py", line 34, in run
main(prog="allennlp")
File "/Users/xiaoqingwan/opt/miniconda3/envs/absa/lib/python3.7/site-packages/allennlp/commands/__init__.py", line 118, in main
args.func(args)
File "/Users/xiaoqingwan/opt/miniconda3/envs/absa/lib/python3.7/site-packages/allennlp/commands/predict.py", line 205, in _predict
predictor = _get_predictor(args)
File "/Users/xiaoqingwan/opt/miniconda3/envs/absa/lib/python3.7/site-packages/allennlp/commands/predict.py", line 105, in _get_predictor
check_for_gpu(args.cuda_device)
File "/Users/xiaoqingwan/opt/miniconda3/envs/absa/lib/python3.7/site-packages/allennlp/common/checks.py", line 131, in check_for_gpu
" 'trainer.cuda_device=-1' in the json config file." + torch_gpu_error
allennlp.common.checks.ConfigurationError: **Experiment specified a GPU but none is available; if you want to run on CPU use the override 'trainer.cuda_device=-1' in the json config file.**
module 'torch.cuda' has no attribute '_check_driver'
Could you give me some guidance on what to do? Where is the config file and what is it called?
Here's the code (originally from: https://colab.research.google.com/drive/1F9zW_nVkwfwIVXTOA_juFDrlPz5TLjpK?usp=sharing):
# Use pretrained SpanModel weights for prediction
import sys
sys.path.append("aste")
from pathlib import Path
from data_utils import Data, Sentence, SplitEnum
from wrapper import SpanModel
def predict_sentence(text: str, model: SpanModel) -> Sentence:
path_in = "temp_in.txt"
path_out = "temp_out.txt"
sent = Sentence(tokens=text.split(), triples=[], pos=[], is_labeled=False, weight=1, id=1)
data = Data(root=Path(), data_split=SplitEnum.test, sentences=[sent])
data.save_to_path(path_in)
model.predict(path_in, path_out)
data = Data.load_from_full_path(path_out)
return data.sentences[0]
text = "Did not enjoy the new Windows 8 and touchscreen functions ."
model = SpanModel(save_dir="pretrained_14lap", random_seed=0)
sent = predict_sentence(text, model)
Try using something like:
device = torch.device("cpu")
model = SpanModel(save_dir="pretrained_14lap", random_seed=0)
model.to(device)
The config file is inside of the model.tar.gz in the pretrained_14lap directory (it is always named config.json). It also contains the param "cuda_device": 0, which may be causing your problem.

BROWNIE ISSUES:NONETYPE

5:31:35 in the video, Typed the codes in exactly the same way and ran it but I keep getting this error
INFO: Could not find files for the given pattern(s).
Brownie v1.18.1 - Python development framework for Ethereum
File "C:\Users\Morounfola\AppData\Local\Programs\Python\Python38\lib\site-packages\brownie_cli_main_.py", line 64, in main
importlib.import_module(f"brownie._cli.{cmd}").main()
File "C:\Users\Morounfola\AppData\Local\Programs\Python\Python38\lib\site-packages\brownie_cli\run.py", line 42, in main
active_project.load_config()
File "C:\Users\Morounfola\AppData\Local\Programs\Python\Python38\lib\site-packages\brownie\project\main.py", line 462, in load_config
_load_project_config(self._path)
File "C:\Users\Morounfola\AppData\Local\Programs\Python\Python38\lib\site-packages\brownie_config.py", line 222, in _load_project_config
and "cmd_settings" in values
TypeError: argument of type 'NoneType' is not iterable
This is the code;
from brownie import FundMe, MockV3Aggregator, network, config
from scripts.helpful_scripts import get_account
def deploy_fund_me():
account = get_account()
# pass the pricefeed address to our fund me contract
# if we are on a persistent address like rinkeby, use the associated address
# otherwise, deploy mocks
if network.show_active != "development":
price_feed_address = config["networks"][network.show_active()][
"eth_usd_price_feed"
]
else:
print(f"The active network is{network.show_active()}")
print("Deploying Mocks...")
mock_aggregator = MockV3Aggregator.deploy(
18, 200000000000000000000, {"from": account}
)
price_feed_address = mock_aggregator.address
print("Mocks Deployed!")
fund_me = FundMe.deploy(price_feed_address, {"from": account}, publish_source=True)
print(f"Contract deployed to {fund_me.address}")
def main():
deploy_fund_me()
I answered this here:
File "brownie/_config.py", line 222, in _load_project_config and "cmd_settings" in values TypeError: argument of type 'NoneType' is not iterable
I had the same exact issue and it was because my brownie-config.yml file was incorrect. You can't have any blank variables in your config file.
Under networks I had:
networks:
rinkeby:
eth_usd_price_feed: "0x8A753747A1Fa494EC906cE90E9f37563A8AF630e"
verify: True
kovan:
mainnet:
having 'kovan' and 'mainnet' set to blank caused the error.
The solution is to either delete those two lines or comment them out like this:
networks:
rinkeby:
eth_usd_price_feed: "0x8A753747A1Fa494EC906cE90E9f37563A8AF630e"
verify: True
# kovan:
# mainnet:

Exporting TFRecords training patches with Google Earth Engine (kernelSize issues)

I've been using GEE to export some training patches from Sentinel-2 to be used in Python.
I could make it work, by following the GEE guide https://developers.google.com/earth-engine/tfrecord, and using the Export.image.toDrive function and then I can parse the exported TFRecord file to reconstruct my tiles.
var image_export_options = {
'patchDimensions': [366, 366],
'maxFileSize': 104857600,
// 'kernelSize': [366, 366],
'compressed': true
}
Export.image.toDrive({
image: clipped_img.select(bands.concat(['classes'])),
description: 'PatchesExport',
fileNamePrefix: 'Oros_1',
scale: 10,
folder: 'myExportFolder',
fileFormat: 'TFRecord',
region: export_area,
formatOptions: image_export_options,
})
However, when I try to specify the kernelSize in the formatOptions (that was supposed to "overlaps adjacent tiles by [kernelSize[0]/2, kernelSize[1]/2]", according to the guide) the files are exported but the '*mixer.json' doesn't reflect the increased number of patches and I am not able to iterate through the patches afterwards. The following command crashes the google colab session:
image_dataset = tf.data.TFRecordDataset(str(path/(file_prefix+'-00000.tfrecord.gz')), compression_type='GZIP')
first = next(iter(image_dataset))
first
The weird is that the problem happens only when I add the kernelSize to the formatOptions.
After some time trying to overcome this issue, I realized a not well documented behavior when one uses the kernel size to export patches from GEE.
Bundled with the exported TFRecord, there exists one xml file called mixer.
It doesn't matter if we use:
'patchDimensions': [184, 184],
'kernelSize': [1, 1], #default for no overlapping
or
'patchDimensions': [184, 184],
'kernelSize': [184, 184], #half patch overlapping
The mixer file remains the same and no mention to the kernel/overlapping size:
{'patchDimensions': [184, 184],
'patchesPerRow': 8,
'projection': {'affine': {'doubleMatrix': [10.0,
0.0,
493460.0,
0.0,
-10.0,
9313540.0]},
'crs': 'EPSG:32724'},
'totalPatches': 40}
In the second case, if we try to parse the patches using tf.io.parse_single_example(example_proto, image_features_dict), where image_features_dict equals something like:
{'B2': FixedLenFeature(shape=[184, 184], dtype=tf.float32, default_value=None),
'B3': FixedLenFeature(shape=[184, 184], dtype=tf.float32, default_value=None),
'B4': FixedLenFeature(shape=[184, 184], dtype=tf.float32, default_value=None)}
it will raise the error:
_FallbackException: This function does not handle the case of the path where all inputs are not already EagerTensors.
Can't parse serialized Example. [Op:ParseExampleV2]
Instead, to parse these records which have kernelSize > 1, we have to consider patchDimentions + kernelSize as the resulting patch size, even though the mixer.xml file says on contraty. In this example, our patchSize would be 368 (original patch size + kernelSize). Be aware that for odd kernel sizes, the number to be added to the original patch size is kernelSize - 1.

AttributeError: 'DataFrame' object has no attribute 'Recovery'

When I tried to filter the data points, it seems like the filtration does not work quite well, and I am really confused cause last time when I used literally the same codes, it worked. Attached below is the filtration part and the error description.
"""------------- Read all the data points in the file ----------------------------------------"""
zeolite_13X_error = pd.read_csv("zeolite_13X_error.csv", delimiter=",") # Used for training set
zeolite_copy = zeolite_13X_error.copy() # Used for test set
"""--------------------------------------------------------------------------------------------"""
"""------------- Filter points, Recovery rate and Purity - Test Set Only ---------------------"""
zeolite_13X_error_testset = zeolite_copy[zeolite_copy.Recovery > 0.7]
zeolite_13X_error_testset = zeolite_13X_error_testset[zeolite_13X_error_testset.Purity > 0.7]
zeolite_13X_error_testset = zeolite_13X_error_testset[zeolite_13X_error_testset.Recovery < 1.0]
*Traceback (most recent call last):
File "C:/Users/julia/Machine Learning Edi/Combination Prediction.py", line 16, in <module>
zeolite_13X_error_testset = zeolite_copy[zeolite_copy.Recovery > 0.7]
File "C:\Users\julia\Anaconda3\envs\Machine Learning Edi\lib\site-packages\pandas\core\generic.py", line 5274, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'Recovery'*

Using tf.app.run() to call main function from a class

The question is simple, I'm trying to use tf.app.run() to call the main function in a class. But, the following code gives me an error. Any help is appreciated.
import tensorflow as tf
import sys
# Where to find data
tf.app.flags.DEFINE_string('f1', '', 'feature 1')
tf.app.flags.DEFINE_string('f2', '', 'feature 2')
FLAGS = tf.app.flags.FLAGS
class Test(object):
def __init__(self):
pass
def main(self, args):
print(FLAGS.__flag.iteritems())
def main(args):
test = Test()
test.main(args)
if __name__ == '__main__':
tf.app.run(main)
And here is the error:
Traceback (most recent call last):
File "test.py", line 21, in <module>
tf.app.run(main)
File "/Users/yaserkeneshloo/anaconda/envs/env27/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 126, in run
_sys.exit(main(argv))
File "test.py", line 18, in main
test.main(args)
File "test.py", line 14, in main
print(FLAGS.__flag.iteritems())
File "/Users/yaserkeneshloo/anaconda/envs/env27/lib/python2.7/site-packages/tensorflow/python/platform/flags.py", line 85, in __getattr__
return wrapped.__getattr__(name)
File "/Users/yaserkeneshloo/anaconda/envs/env27/lib/python2.7/site-packages/absl/flags/_flagvalues.py", line 470, in __getattr__
raise AttributeError(name)
AttributeError: _Test__flag
The issue is that when you try to access a property of FLAGS beginning with double underscore from inside a class, it prefixes the property with the class name. So instead of FLAGS.__flags it tries to find FLAGS._Test__flags which does not exist.
This is true for both setting or getting a value. So if you set the value from outside of the class, you have to prefix it with _Test (because you named your class Test.) If you set the flags inside the class, you don't need to prefix, because it does the prefixing automatically also on assigning a value.
So basically you have no problem at all with your code because your own flags don't start with double underscore, except you cannot use the internal __flags property to print all flags. You can access them individually though.
See the code below for detailed examples. (Also, the default value in the DEFINE line is the second parameter, not the third.)
# Where to find data
tf.app.flags.DEFINE_string('_Test__f1', 'feature 1', 'feature 1')
tf.app.flags.DEFINE_string('__f2', 'feature 2', 'feature 2')
FLAGS = tf.app.flags.FLAGS
print( FLAGS.__f2 ) # prints "feature 2"
class Test(object):
def __init__(self):
pass
def main(self, args):
print( FLAGS.__f1 ) # prints "feature 1"
FLAGS.__f1 = 'foobar' # assignment works the same way
print( FLAGS.__f1 ) # prints "foobar"
print( FLAGS.__f2 ) # AttributeError: _Test__f2
def main(args):
test = Test()
test.main(args)
if __name__ == '__main__':
tf.app.run(main)
The problem is that FLAGS doesn't have an attribute named __flag. If you want to print the string corresponding to the f1 flag, call print(FLAGS.f1).
This will do the trick:
import tensorflow as tf
import sys
# Where to find data
tf.app.flags.DEFINE_string('f1', '', 'feature 1')
tf.app.flags.DEFINE_string('f2', '', 'feature 2')
FLAGS = tf.app.flags.FLAGS
class Test(object):
def __init__(self):
pass
def main(self, args):
flags = getattr(FLAGS,"__flags")
print([(k,v) for (k,v) in flags.iteritems()])
def main(args):
test = Test()
test.main(args)
if __name__ == '__main__':
tf.app.run(main)