id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
28,000
lookup.py
stan-dev_pystan2/pystan/lookup.py
#----------------------------------------------------------------------------- # Copyright (c) 2017, PyStan developers # # This file is licensed under Version 3.0 of the GNU General Public # License. See LICENSE for a text of the license. #----------------------------------------------------------------------------- import numpy as np import re import pkg_resources import io lookuptable = None stanftable = None def lookup(name, min_similarity_ratio=.75): """ Look up for a Stan function with similar functionality to a Python function (or even an R function, see examples). If the function is not present on the lookup table, then attempts to find similar one and prints the results. This function requires package `pandas`. Parameters ----------- name : str Name of the function one wants to look for. min_similarity_ratio : float In case no exact match is found on the lookup table, the function will attempt to find similar names using `difflib.SequenceMatcher.ratio()`, and then results with calculated ratio below `min_similarity_ratio` will be discarded. Examples --------- #Look up for a Stan function similar to scipy.stats.skewnorm lookup("scipy.stats.skewnorm") #Look up for a Stan function similar to R dnorm lookup("R.dnorm") #Look up for a Stan function similar to numpy.hstack lookup("numpy.hstack") #List Stan log probability mass functions lookup("lpmfs") #List Stan log cumulative density functions lookup("lcdfs") Returns --------- A pandas.core.frame.DataFrame if exact or at least one similar result is found, None otherwise. """ if lookuptable is None: build() if name not in lookuptable.keys(): from difflib import SequenceMatcher from operator import itemgetter print("No match for " + name + " in the lookup table.") lkt_keys = list(lookuptable.keys()) mapfunction = lambda x: SequenceMatcher(a=name, b=x).ratio() similars = list(map(mapfunction, lkt_keys)) similars = zip(range(len(similars)), similars) similars = list(filter(lambda x: x[1] >= min_similarity_ratio, similars)) similars = sorted(similars, key=itemgetter(1)) if (len(similars)): print("But the following similar entries were found: ") for i in range(len(similars)): print(lkt_keys[similars[i][0]] + " ===> with similary " "ratio of " + str(round(similars[i][1], 3)) + "") print("Will return results for entry" " " + lkt_keys[similars[i][0]] + " " "(which is the most similar entry found).") return lookup(lkt_keys[similars[i][0]]) else: print("And no similar entry found. You may try to decrease" "the min_similarity_ratio parameter.") return entries = stanftable[lookuptable[name]] if not len(entries): return "Found no equivalent Stan function available for " + name try: import pandas as pd except ImportError: raise ImportError('Package pandas is require to use this ' 'function.') return pd.DataFrame(entries) def build(): def load_table_file(fname): fname = "lookuptable/" + fname fbytes = pkg_resources.resource_string(__name__, fname) return io.BytesIO(fbytes) stanfunctions_file = load_table_file("stan-functions.txt") rfunctions_file = load_table_file("R.txt") pythontb_file = load_table_file("python.txt") stanftb = np.genfromtxt(stanfunctions_file, delimiter=';', names=True, skip_header=True, dtype=['<U200','<U200','<U200' ,"int"]) rpl_textbar = np.vectorize(lambda x: x.replace("\\textbar \\", "|")) stanftb['Arguments'] = rpl_textbar(stanftb['Arguments']) StanFunction = stanftb["StanFunction"] #Auto-extract R functions rmatches = [re.findall(r'(' '(?<=RFunction\[StanFunction == \").+?(?=\")' '|(?<=grepl\(").+?(?=", StanFunction\))' '|(?<= \<\- ").+?(?="\)))' '|NA\_character\_', l.decode("utf-8")) for l in rfunctions_file] tomatch = list(filter(lambda x: len(x) == 2, rmatches)) tomatch = np.array(tomatch, dtype=str) tomatch[:, 1] = np.vectorize(lambda x: "R." + x)(tomatch[:,1]) #Get packages lookup table for Python packages pymatches = np.genfromtxt(pythontb_file, delimiter='; ', dtype=str) tomatch = np.vstack((tomatch, pymatches)) lookuptb = dict() for i in range(tomatch.shape[0]): matchedlines = np.vectorize(lambda x: re.match(tomatch[i, 0], x))(StanFunction) lookuptb[tomatch[i, 1]] = np.where(matchedlines)[0] #debug: list of rmatches that got wrong #print(list(filter(lambda x: len(x) != 2 and len(x) != 0, # rmatches))) #debug: list of nodes without matches on lookup table #for k in lookuptb: # if len(lookuptb[k]) == 0: # print(k) global lookuptable global stanftable stanftable = stanftb lookuptable = lookuptb
5,373
Python
.py
122
35.647541
78
0.593881
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,001
test_rstan_stan_args.py
stan-dev_pystan2/pystan/tests/test_rstan_stan_args.py
import unittest import numpy as np import pystan from pystan.tests.helper import get_model # REF: rstan/tests/unitTests/runit.test.stan_args_hpp.R class TestPyStanArgs(unittest.TestCase): def test_stan_args_basic(self): y = np.array([0.70, -0.16, 0.77, -1.37, -1.99, 1.35, 0.08, 0.02, -1.48, -0.08, 0.34, 0.03, -0.42, 0.87, -1.36, 1.43, 0.80, -0.48, -1.61, -1.27]) code = ''' data { int N; real y[N]; } parameters { real mu; real<lower=0> sigma; } model { y ~ normal(mu, sigma); }''' sm = get_model("normal_mu_sigma_model", code) sf = sm.sampling(iter=10, thin=3, data=dict(y=y, N=20)) args = sf.stan_args[0] self.assertEqual(args['iter'], 10) self.assertEqual(args['thin'], 3) self.assertEqual(args['init'], b'random') sampling = args['ctrl']['sampling'] self.assertEqual(sampling['adapt_engaged'], True) self.assertEqual(sampling['adapt_window'], 25) self.assertEqual(sampling['adapt_init_buffer'], 75) self.assertEqual(sampling['adapt_gamma'], 0.05) self.assertEqual(sampling['adapt_delta'], 0.8) self.assertEqual(sampling['adapt_kappa'], 0.75) self.assertEqual(sampling['adapt_t0'], 10) def test_stan_args_optimizing(self): args = pystan.misc._get_valid_stan_args(dict(method="optim")) # default optimizing algorithm is LBFGS self.assertEqual(args['ctrl']['optim']['algorithm'], pystan.constants.optim_algo_t.LBFGS) args = pystan.misc._get_valid_stan_args(dict(iter=100, seed=12345, method='optim')) self.assertEqual(args['random_seed'], 12345) self.assertEqual(args['ctrl']['optim']['algorithm'], pystan.constants.optim_algo_t.LBFGS) args = pystan.misc._get_valid_stan_args(dict(iter=100, seed=12345, method='optim', algorithm='BFGS')) self.assertEqual(args['random_seed'], 12345) self.assertEqual(args['ctrl']['optim']['algorithm'], pystan.constants.optim_algo_t.BFGS) args = pystan.misc._get_valid_stan_args(dict(iter=100, seed=12345, method='optim', algorithm='LBFGS')) self.assertEqual(args['random_seed'], 12345) self.assertEqual(args['ctrl']['optim']['algorithm'], pystan.constants.optim_algo_t.LBFGS) self.assertEqual(args['ctrl']['optim']['history_size'], 5) args = pystan.misc._get_valid_stan_args(dict(iter=100, method='optim', history_size=6)) self.assertEqual(args['ctrl']['optim']['history_size'], 6) def test_stan_args_sampling(self): # defaults are largely controlled by # pystan.misc_get_valid_stan_args # which has an analog in rstan, rstan::stan_args args = pystan.misc._get_valid_stan_args(dict(iter=100, thin=100)) self.assertEqual(args['ctrl']['sampling']['iter'], 100) self.assertEqual(args['ctrl']['sampling']['thin'], 100) args = pystan.misc._get_valid_stan_args(dict(iter=5, thin=3, refresh=-1, seed="12345")) self.assertEqual(args['ctrl']['sampling']['iter'], 5) self.assertEqual(args['ctrl']['sampling']['thin'], 3) self.assertEqual(args['ctrl']['sampling']['refresh'], -1) self.assertEqual(args['random_seed'], '12345') args = pystan.misc._get_valid_stan_args(dict(iter=5, thin=3, refresh=-1, seed="12345", method='test_grad')) self.assertEqual(args['method'], pystan.constants.stan_args_method_t.TEST_GRADIENT) args = pystan.misc._get_valid_stan_args(dict(method='test_grad', epsilon=1.3, error=0.1)) self.assertEqual(args['method'], pystan.constants.stan_args_method_t.TEST_GRADIENT) self.assertEqual(args['ctrl']['test_grad']['epsilon'], 1.3) self.assertEqual(args['ctrl']['test_grad']['error'], 0.1) args = pystan.misc._get_valid_stan_args(dict(iter=100, algorithm='HMC')) self.assertEqual(args['ctrl']['sampling']['algorithm'], pystan.constants.sampling_algo_t.HMC) args = pystan.misc._get_valid_stan_args(dict(algorithm='NUTS')) self.assertEqual(args['ctrl']['sampling']['algorithm'], pystan.constants.sampling_algo_t.NUTS) args = pystan.misc._get_valid_stan_args(dict(algorithm='NUTS', control=dict(stepsize=0.1))) self.assertEqual(args['ctrl']['sampling']['algorithm'], pystan.constants.sampling_algo_t.NUTS) self.assertEqual(args['ctrl']['sampling']['stepsize'], 0.1) args = pystan.misc._get_valid_stan_args(dict(algorithm='NUTS', control=dict(stepsize=0.1, metric='unit_e'))) self.assertEqual(args['ctrl']['sampling']['algorithm'], pystan.constants.sampling_algo_t.NUTS) self.assertEqual(args['ctrl']['sampling']['stepsize'], 0.1) self.assertEqual(args['ctrl']['sampling']['metric'], pystan.constants.sampling_metric_t.UNIT_E) args = pystan.misc._get_valid_stan_args(dict(algorithm='NUTS', control=dict(stepsize=0.1, metric='diag_e'))) self.assertEqual(args['ctrl']['sampling']['algorithm'], pystan.constants.sampling_algo_t.NUTS) self.assertEqual(args['ctrl']['sampling']['stepsize'], 0.1) self.assertEqual(args['ctrl']['sampling']['metric'], pystan.constants.sampling_metric_t.DIAG_E) args = pystan.misc._get_valid_stan_args(dict(algorithm='NUTS', control=dict(stepsize=0.1, metric='diag_e', adapt_term_buffer=4, adapt_window=30, adapt_init_buffer=40))) self.assertEqual(args['ctrl']['sampling']['algorithm'], pystan.constants.sampling_algo_t.NUTS) self.assertEqual(args['ctrl']['sampling']['stepsize'], 0.1) self.assertEqual(args['ctrl']['sampling']['metric'], pystan.constants.sampling_metric_t.DIAG_E) self.assertEqual(args['ctrl']['sampling']['adapt_term_buffer'], 4) self.assertEqual(args['ctrl']['sampling']['adapt_window'], 30) self.assertEqual(args['ctrl']['sampling']['adapt_init_buffer'], 40)
6,051
Python
.py
93
55.516129
116
0.637742
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,002
test_basic.py
stan-dev_pystan2/pystan/tests/test_basic.py
from collections import OrderedDict import gc import os import tempfile import unittest import numpy as np import pystan from pystan._compat import PY2 from pystan.tests.helper import get_model class TestNormal(unittest.TestCase): @classmethod def setUpClass(cls): model_code = 'parameters {real y;} model {y ~ normal(0,1);}' cls.model = get_model("standard_normal_model", model_code, model_name="normal1", verbose=True, obfuscate_model_name=False) #cls.model = pystan.StanModel(model_code=model_code, model_name="normal1", # verbose=True, obfuscate_model_name=False) def test_constructor(self): self.assertEqual(self.model.model_name, "normal1") self.assertEqual(self.model.model_cppname, "normal1") def test_log_prob(self): fit = self.model.sampling() extr = fit.extract() y_last, log_prob_last = extr['y'][-1], extr['lp__'][-1] self.assertEqual(fit.log_prob(y_last), log_prob_last) def test_check_diagnostics(self): fit = self.model.sampling(iter=10, chains=1, check_hmc_diagnostics=True) self.assertIsNotNone(fit) fit2 = self.model.sampling(iter=10, chains=1, check_hmc_diagnostics=False) self.assertIsNotNone(fit2) def test_control_stepsize(self): fit = self.model.sampling(control=dict(stepsize=0.001)) self.assertIsNotNone(fit) class TestBernoulli(unittest.TestCase): @classmethod def setUpClass(cls): bernoulli_model_code = """ data { int<lower=0> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { for (n in 1:N) y[n] ~ bernoulli(theta); } """ cls.bernoulli_data = bernoulli_data = {'N': 10, 'y': [0, 1, 0, 0, 0, 0, 0, 0, 0, 1]} cls.model = model = get_model("bernoulli_model", bernoulli_model_code, model_name="bernoulli") #cls.model = model = pystan.StanModel(model_code=bernoulli_model_code, model_name="bernoulli") cls.fit = model.sampling(data=bernoulli_data) def test_bernoulli_constructor(self): model = self.model # obfuscate_model_name is True self.assertNotEqual(model.model_name, "bernoulli") self.assertTrue(model.model_name.startswith("bernoulli")) self.assertTrue(model.model_cppname.startswith("bernoulli")) def test_bernoulli_OrderedDict(self): data = OrderedDict(self.bernoulli_data.items()) self.model.sampling(data=data, iter=2) def test_bernoulli_sampling(self): fit = self.fit self.assertEqual(fit.sim['iter'], 2000) self.assertEqual(fit.sim['pars_oi'], ['theta', 'lp__']) self.assertEqual(len(fit.sim['samples']), 4) assert 0.1 < np.mean(fit.sim['samples'][0]['chains']['theta']) < 0.4 assert 0.1 < np.mean(fit.sim['samples'][1]['chains']['theta']) < 0.4 assert 0.1 < np.mean(fit.sim['samples'][2]['chains']['theta']) < 0.4 assert 0.1 < np.mean(fit.sim['samples'][3]['chains']['theta']) < 0.4 assert 0.01 < np.var(fit.sim['samples'][0]['chains']['theta']) < 0.02 assert 0.01 < np.var(fit.sim['samples'][1]['chains']['theta']) < 0.02 assert 0.01 < np.var(fit.sim['samples'][2]['chains']['theta']) < 0.02 assert 0.01 < np.var(fit.sim['samples'][3]['chains']['theta']) < 0.02 def test_bernoulli_sampling_error(self): bad_data = self.bernoulli_data.copy() del bad_data['N'] assertRaisesRegex = self.assertRaisesRegexp if PY2 else self.assertRaisesRegex with assertRaisesRegex(RuntimeError, 'variable does not exist'): fit = self.model.sampling(data=bad_data) def test_bernoulli_sampling_invalid_argument(self): assertRaisesRegex = self.assertRaisesRegexp if PY2 else self.assertRaisesRegex with assertRaisesRegex(ValueError, 'only integer values allowed'): self.model.sampling(thin=2.0, data=self.bernoulli_data) def test_bernoulli_extract(self): fit = self.fit extr = fit.extract(permuted=True) assert -7.9 < np.mean(extr['lp__']) < -7.0, np.mean(extr['lp__']) assert 0.1 < np.mean(extr['theta']) < 0.4 assert 0.01 < np.var(extr['theta']) < 0.02 # use __getitem__ assert -7.9 < np.mean(fit['lp__']) < -7.0, np.mean(fit['lp__']) assert 0.1 < np.mean(fit['theta']) < 0.4 assert 0.01 < np.var(fit['theta']) < 0.02 # permuted=False extr = fit.extract(permuted=False) self.assertEqual(extr.shape, (1000, 4, 2)) self.assertTrue(0.1 < np.mean(extr[:, 0, 0]) < 0.4) # permuted=True extr = fit.extract('lp__', permuted=True) assert -7.9 < np.mean(extr['lp__']) < -7.0 extr = fit.extract('theta', permuted=True) assert 0.1 < np.mean(extr['theta']) < 0.4 assert 0.01 < np.var(extr['theta']) < 0.02 extr = fit.extract('theta', permuted=False) assert extr['theta'].shape == (1000, 4) assert 0.1 < np.mean(extr['theta'][:, 0]) < 0.4 def test_bernoulli_random_seed_consistency(self): thetas = [] for _ in range(2): fit = self.model.sampling(data=self.bernoulli_data, seed=42) thetas.append(fit.extract('theta', permuted=True)['theta']) np.testing.assert_equal(*thetas) def test_bernoulli_random_seed_inconsistency(self): thetas = [] for seed in range(2): # seeds will be 0, 1 fit = self.model.sampling(data=self.bernoulli_data, seed=np.random.RandomState(seed)) thetas.append(fit.extract('theta', permuted=True)['theta']) self.assertFalse(np.allclose(*thetas)) def test_bernoulli_summary(self): fit = self.fit s = fit.summary() assert s is not None # printing to make sure no exception raised repr(fit) print(fit) def test_bernoulli_plot(self): fit = self.fit fig = fit.plot() assert fig is not None fig = fit.plot(['theta']) assert fig is not None fig = fit.plot('theta') assert fig is not None def test_bernoulli_sampling_sample_file(self): tmpdir = tempfile.mkdtemp() sample_file = os.path.join(tmpdir, 'sampling.csv') fit = self.model.sampling(data=self.bernoulli_data, sample_file=sample_file) num_chains = len(fit.sim['samples']) for i in range(num_chains): fn = os.path.splitext(os.path.join(tmpdir, 'sampling.csv'))[0] + "_{}.csv".format(i) assert os.path.exists(fn) fit = self.model.sampling(data=self.bernoulli_data, sample_file='/tmp/pathdoesnotexist/sampling.csv') assert fit is not None def test_bernoulli_optimizing_sample_file(self): tmpdir = tempfile.mkdtemp() sample_file = os.path.join(tmpdir, 'optim.csv') self.model.optimizing(data=self.bernoulli_data, sample_file=sample_file) assert os.path.exists(sample_file) fit = self.model.optimizing(data=self.bernoulli_data, sample_file='/tmp/pathdoesnotexist/optim.csv') assert fit is not None
7,434
Python
.py
156
38.301282
109
0.607976
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,003
test_linear_regression.py
stan-dev_pystan2/pystan/tests/test_linear_regression.py
import unittest import numpy as np import pystan class TestLinearRegression(unittest.TestCase): @classmethod def setUpClass(cls): np.random.seed(1) n = 10000 p = 3 cls.beta_true = beta_true = (1, 3, 5) X = np.random.normal(size=(n, p)) X = (X - np.mean(X, axis=0)) / np.std(X, ddof=1, axis=0, keepdims=True) y = np.dot(X, beta_true) + np.random.normal(size=n) model_code = """ data { int<lower=0> N; int<lower=0> p; matrix[N,p] x; vector[N] y; } parameters { vector[p] beta; real<lower=0> sigma; } model { y ~ normal(x * beta, sigma); } """ data = {'N': n, 'p': p, 'x': X, 'y': y} cls.fit = pystan.stan(model_code=model_code, data=data, iter=500) def test_linear_regression(self): fit = self.fit beta_true = self.beta_true self.assertEqual(fit.sim['dims_oi'], fit._get_param_dims()) np.mean(fit.extract()['beta'], axis=0) np.mean(fit.extract()['sigma']) sigma = fit.extract()['sigma'] beta = fit.extract()['beta'] # mean of sigma is 1 self.assertTrue(np.count_nonzero(np.abs(sigma - 1) < 0.05)) self.assertTrue(all(np.abs(np.mean(beta, 0) - np.array(beta_true)) < 0.05))
1,396
Python
.py
41
25.121951
83
0.527571
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,004
test_user_inits.py
stan-dev_pystan2/pystan/tests/test_user_inits.py
import unittest import numpy as np import pystan class TestUserInits(unittest.TestCase): @classmethod def setUpClass(cls): model_code = """ data { real x; } parameters { real mu; } model { x ~ normal(mu,1); } """ cls.data = dict(x=2) cls.model = pystan.StanModel(model_code=model_code) def test_user_init(self): model, data = self.model, self.data fit1 = model.sampling(iter=10, chains=1, seed=2, data=data, init=[dict(mu=4)], warmup=0, control={"adapt_engaged" : False}) self.assertEqual(fit1.get_inits()[0]['mu'], 4) fit2 = model.sampling(iter=10, chains=1, seed=2, data=data, init=[dict(mu=400)], warmup=0, control={"adapt_engaged" : False}) self.assertEqual(fit2.get_inits()[0]['mu'], 400) self.assertFalse(all(fit1.extract()['mu'] == fit2.extract()['mu'])) def test_user_initfun(self): model, data = self.model, self.data def make_inits(chain_id): return dict(mu=chain_id) fit1 = model.sampling(iter=10, chains=4, seed=2, data=data, init=make_inits, warmup=0, control={"adapt_engaged" : False}) for i, inits in enumerate(fit1.get_inits()): self.assertEqual(inits['mu'], i) def test_user_initfun_chainid(self): model, data = self.model, self.data def make_inits(chain_id): return dict(mu=chain_id) chain_id = [9, 10, 11, 12] fit1 = model.sampling(iter=10, chains=4, seed=2, data=data, init=make_inits, warmup=0, chain_id=chain_id, control={"adapt_engaged" : False}) for i, inits in zip(chain_id, fit1.get_inits()): self.assertEqual(inits['mu'], i) def test_user_init_unspecified(self): model_code = """ data { real x; } parameters { real mu; real<lower=0> sigma; } model { x ~ normal(mu, sigma); } """ data = self.data # NOTE: we are only specifying 'mu' and not 'sigma' (partial inits) fit = pystan.stan(model_code=model_code, iter=10, chains=1, seed=2, data=data, init=[dict(mu=4)], warmup=0, control={"adapt_engaged" : False}) self.assertIsNotNone(fit) class TestUserInitsMatrix(unittest.TestCase): @classmethod def setUpClass(cls): model_code = """ data { int<lower=2> K; int<lower=1> D; } parameters { matrix[K,D] beta; } model { for (k in 1:K) for (d in 1:D) beta[k,d] ~ normal((d==2?100:0),1); } """ cls.model = pystan.StanModel(model_code=model_code) cls.data = dict(K=3, D=4) def test_user_init(self): model, data = self.model, self.data beta = np.ones((data['K'], data['D'])) fit1 = model.sampling(iter=10, chains=1, seed=2, data=data, init=[dict(beta=beta)], warmup=0, control={"adapt_engaged" : False}) np.testing.assert_equal(fit1.get_inits()[0]['beta'], beta) beta = 5 * np.ones((data['K'], data['D'])) fit2 = model.sampling(iter=10, chains=1, seed=2, data=data, init=[dict(beta=beta)], warmup=0, control={"adapt_engaged" : False}) np.testing.assert_equal(fit2.get_inits()[0]['beta'], beta) def test_user_initfun(self): model, data = self.model, self.data beta = np.ones((data['K'], data['D'])) def make_inits(chain_id): return dict(beta=beta * chain_id) fit1 = model.sampling(iter=10, chains=4, seed=2, data=data, init=make_inits, warmup=0, control={"adapt_engaged" : False}) for i, inits in enumerate(fit1.get_inits()): np.testing.assert_equal(beta * i, inits['beta'])
4,001
Python
.py
96
31.177083
150
0.548919
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,005
test_euclidian_metric.py
stan-dev_pystan2/pystan/tests/test_euclidian_metric.py
import unittest import os import numpy as np import tempfile import pystan from pystan import StanModel from pystan.tests.helper import get_model class TestEuclidianMetric(unittest.TestCase): @classmethod def setUpClass(cls): model_code = """ data { int<lower=2> K; int<lower=1> D; } parameters { matrix[K,D] beta; } model { for (k in 1:K) for (d in 1:D) beta[k,d] ~ normal((d==2?100:0),1); }""" cls.model = get_model("matrix_normal_model", model_code) #cls.model = StanModel(model_code=model_code) control = {"metric" : "diag_e"} fit = cls.model.sampling(chains=1, data=dict(K=3, D=4), warmup=1500, iter=1501, control=control, check_hmc_diagnostics=False, seed=14) cls.pos_def_matrix_diag_e = fit.get_inv_metric()[0] cls.stepsize_diag_e = fit.get_stepsize()[0] control = {"metric" : "dense_e"} fit = cls.model.sampling(chains=1, data=dict(K=3, D=4), warmup=1500, iter=1501, control=control, check_hmc_diagnostics=False, seed=14) cls.pos_def_matrix_dense_e = fit.get_inv_metric()[0] cls.stepsize_dense_e = fit.get_stepsize()[0] def test_get_inv_metric(self): sm = self.model control_dict = {"metric" : "diag_e"} fit = sm.sampling(chains=3, data=dict(K=3, D=4), warmup=1000, iter=1001, algorithm="NUTS", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric = fit.get_inv_metric() assert isinstance(inv_metric, list) assert len(inv_metric) == 3 assert all(mm.shape == (3*4,) for mm in inv_metric) def test_path_inv_metric_diag_e(self): sm = self.model path = os.path.join(tempfile.mkdtemp(), "inv_metric_t1.Rdata") inv_metric = self.pos_def_matrix_diag_e stepsize = self.stepsize_diag_e pystan.misc.stan_rdump({"inv_metric" : inv_metric}, path) control_dict = {"metric" : "diag_e", "inv_metric" : path, "stepsize" : stepsize, "adapt_engaged" : False} fit = sm.sampling(data=dict(K=3, D=4), warmup=0, iter=10, algorithm="NUTS", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_ = fit.get_inv_metric() assert all(mm.shape == (3*4,) for mm in inv_metric_) assert all(np.all(inv_metric == mm) for mm in inv_metric_) try: os.remove(path) except OSError: pass def test_path_inv_metric_dict_diag_e(self): sm = self.model paths = [] inv_metrics = [] for i in range(4): path = os.path.join(tempfile.mkdtemp(), "inv_metric_t2_{}.Rdata".format(i)) inv_metric = self.pos_def_matrix_diag_e pystan.misc.stan_rdump({"inv_metric" : inv_metric}, path) paths.append(path) inv_metrics.append(inv_metric) stepsize = self.stepsize_diag_e control_dict = {"metric" : "diag_e", "inv_metric" : dict(enumerate(paths)), "stepsize" : stepsize, "adapt_engaged" : False} fit = sm.sampling(chains=4, data=dict(K=3, D=4), warmup=0, iter=10, algorithm="NUTS", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_ = fit.get_inv_metric() assert all(mm.shape == (3*4,) for mm in inv_metric_) assert all(mm.shape == (3*4,) for mm in inv_metrics) assert all(np.all(mm_ == mm) for mm_, mm in zip(inv_metric_, inv_metrics)) for path in paths: try: os.remove(path) except OSError: pass def test_path_inv_metric_dense_e(self): sm = self.model path = os.path.join(tempfile.mkdtemp(), "inv_metric_t3.Rdata") inv_metric = self.pos_def_matrix_dense_e stepsize = self.stepsize_diag_e pystan.misc.stan_rdump({"inv_metric" : inv_metric}, path) control_dict = {"metric" : "dense_e", "inv_metric" : path, "stepsize" : stepsize, "adapt_engaged" : False} fit = sm.sampling(data=dict(K=3, D=4), warmup=0, iter=10, algorithm="NUTS", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_ = fit.get_inv_metric() assert all(mm.shape == (3*4,3*4) for mm in inv_metric_) assert all(np.all(inv_metric == mm) for mm in inv_metric_) try: os.remove(path) except OSError: pass def test_one_inv_metric_diag_e(self): sm = self.model inv_metric = self.pos_def_matrix_diag_e stepsize = self.stepsize_diag_e control_dict = {"metric" : "diag_e", "inv_metric" : inv_metric, "stepsize" : stepsize, "adapt_engaged" : False} fit = sm.sampling(data=dict(K=3, D=4), warmup=0, iter=10, algorithm="NUTS", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_ = fit.get_inv_metric() assert all(mm.shape == (3*4,) for mm in inv_metric_) assert all(np.all(inv_metric == mm) for mm in inv_metric_) def test_one_inv_metric_dense_e(self): sm = self.model inv_metric = self.pos_def_matrix_dense_e stepsize = self.stepsize_diag_e control_dict = {"metric" : "dense_e", "inv_metric" : inv_metric, "stepsize" : stepsize, "adapt_engaged" : False} fit = sm.sampling(data=dict(K=3, D=4), warmup=0, iter=10, algorithm="NUTS", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_ = fit.get_inv_metric() assert all(mm.shape == (3*4,3*4) for mm in inv_metric_) assert all(np.all(inv_metric == mm) for mm in inv_metric_) def test_inv_metric_nuts_diag_e_adapt_true(self): sm = self.model control_dict = {"metric" : "diag_e", "adapt_engaged" : True} fit1 = sm.sampling(data=dict(K=3, D=4), warmup=1500, iter=1501, algorithm="NUTS", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_fit1 = fit1.get_inv_metric() stepsize = fit1.get_stepsize() control_dict = {"inv_metric" : dict(enumerate(inv_metric_fit1)), "metric" : "diag_e", "adapt_engaged" : True, "stepsize" : stepsize} fit2 = sm.sampling(data=dict(K=3, D=4), warmup=10, iter=10, algorithm="NUTS", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_fit2 = fit2.get_inv_metric() for inv_metric1, inv_metric2 in zip(inv_metric_fit1, inv_metric_fit2): assert inv_metric1.shape == (3*4,) assert inv_metric2.shape == (3*4,) def test_inv_metric_nuts_diag_e_adapt_false(self): sm = self.model control_dict = {"metric" : "diag_e", "adapt_engaged" : False} fit1 = sm.sampling(data=dict(K=3, D=4), warmup=1500, iter=1501, algorithm="NUTS", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_fit1 = fit1.get_inv_metric() stepsize = fit1.get_stepsize() control_dict = {"inv_metric" : dict(enumerate(inv_metric_fit1)), "metric" : "diag_e", "adapt_engaged" : False, "stepsize" : stepsize} fit2 = sm.sampling(data=dict(K=3, D=4), warmup=0, iter=10, algorithm="NUTS", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_fit2 = fit2.get_inv_metric() for inv_metric1, inv_metric2 in zip(inv_metric_fit1, inv_metric_fit2): assert inv_metric1.shape == (3*4,) assert inv_metric2.shape == (3*4,) assert np.all(inv_metric1 == inv_metric2) def test_inv_metric_nuts_dense_e_adapt_true(self): sm = self.model control_dict = {"metric" : "dense_e", "adapt_engaged" : True} fit1 = sm.sampling(data=dict(K=3, D=4), warmup=1500, iter=1501, algorithm="NUTS", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_fit1 = fit1.get_inv_metric() stepsize = fit1.get_stepsize() control_dict = {"inv_metric" : dict(enumerate(inv_metric_fit1)), "metric" : "dense_e", "adapt_engaged" : True, "stepsize" : stepsize} fit2 = sm.sampling(data=dict(K=3, D=4), warmup=10, iter=10, algorithm="NUTS", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_fit2 = fit2.get_inv_metric() for inv_metric1, inv_metric2 in zip(inv_metric_fit1, inv_metric_fit2): assert inv_metric1.shape == (3*4,3*4) assert inv_metric2.shape == (3*4,3*4) def test_inv_metric_nuts_dense_e_adapt_false(self): sm = self.model control_dict = {"metric" : "dense_e", "adapt_engaged" : False} fit1 = sm.sampling(data=dict(K=3, D=4), warmup=1500, iter=1501, algorithm="NUTS", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_fit1 = fit1.get_inv_metric() stepsize = fit1.get_stepsize() control_dict = {"inv_metric" : dict(enumerate(inv_metric_fit1)), "metric" : "dense_e", "adapt_engaged" : False, "stepsize" : stepsize} fit2 = sm.sampling(data=dict(K=3, D=4), warmup=0, iter=10, algorithm="NUTS", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_fit2 = fit2.get_inv_metric() for inv_metric1, inv_metric2 in zip(inv_metric_fit1, inv_metric_fit2): assert inv_metric1.shape == (3*4,3*4) assert inv_metric2.shape == (3*4,3*4) assert np.all(inv_metric1 == inv_metric2) def test_inv_metric_hmc_diag_e_adapt_true(self): sm = self.model control_dict = {"metric" : "diag_e", "adapt_engaged" : True} fit1 = sm.sampling(data=dict(K=3, D=4), warmup=1500, iter=1501, algorithm="HMC", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_fit1 = fit1.get_inv_metric() stepsize = fit1.get_stepsize() control_dict = {"inv_metric" : dict(enumerate(inv_metric_fit1)), "metric" : "diag_e", "adapt_engaged" : True, "stepsize" : stepsize} fit2 = sm.sampling(data=dict(K=3, D=4), warmup=10, iter=10, algorithm="HMC", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_fit2 = fit2.get_inv_metric() for inv_metric1, inv_metric2 in zip(inv_metric_fit1, inv_metric_fit2): assert inv_metric1.shape == (3*4,) assert inv_metric2.shape == (3*4,) def test_inv_metric_hmc_diag_e_adapt_false(self): sm = self.model control_dict = {"metric" : "diag_e", "adapt_engaged" : False} fit1 = sm.sampling(data=dict(K=3, D=4), warmup=1500, iter=1501, algorithm="HMC", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_fit1 = fit1.get_inv_metric() stepsize = fit1.get_stepsize() control_dict = {"inv_metric" : dict(enumerate(inv_metric_fit1)), "metric" : "diag_e", "adapt_engaged" : False, "stepsize" : stepsize} fit2 = sm.sampling(data=dict(K=3, D=4), warmup=0, iter=10, algorithm="HMC", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_fit2 = fit2.get_inv_metric() for inv_metric1, inv_metric2 in zip(inv_metric_fit1, inv_metric_fit2): assert inv_metric1.shape == (3*4,) assert inv_metric2.shape == (3*4,) assert np.all(inv_metric1 == inv_metric2) def test_inv_metric_hmc_dense_e_adapt_true(self): sm = self.model # this is fragile, using precalculated inv_metric and stepsizes inv_metric = self.pos_def_matrix_dense_e stepsize = self.stepsize_diag_e control_dict = {"metric" : "dense_e", "adapt_engaged" : True, "inv_metric" : inv_metric, "stepsize" : stepsize} fit1 = sm.sampling(data=dict(K=3, D=4), warmup=10, iter=10, algorithm="HMC", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_fit1 = fit1.get_inv_metric() stepsize = fit1.get_stepsize() control_dict = {"inv_metric" : dict(enumerate(inv_metric_fit1)), "metric" : "dense_e", "adapt_engaged" : True, "stepsize" : stepsize} fit2 = sm.sampling(data=dict(K=3, D=4), warmup=10, iter=10, algorithm="HMC", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_fit2 = fit2.get_inv_metric() for inv_metric1, inv_metric2 in zip(inv_metric_fit1, inv_metric_fit2): assert inv_metric1.shape == (3*4,3*4) assert inv_metric2.shape == (3*4,3*4) def test_inv_metric_hmc_dense_e_adapt_false(self): sm = self.model control_dict = {"metric" : "dense_e", "adapt_engaged" : False} fit1 = sm.sampling(data=dict(K=3, D=4), warmup=1500, iter=1501, algorithm="HMC", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_fit1 = fit1.get_inv_metric() stepsize = fit1.get_stepsize() control_dict = {"inv_metric" : dict(enumerate(inv_metric_fit1)), "metric" : "dense_e", "adapt_engaged" : False, "stepsize" : stepsize} fit2 = sm.sampling(data=dict(K=3, D=4), warmup=0, iter=10, algorithm="HMC", control=control_dict, check_hmc_diagnostics=False, seed=14) inv_metric_fit2 = fit2.get_inv_metric() for inv_metric1, inv_metric2 in zip(inv_metric_fit1, inv_metric_fit2): assert inv_metric1.shape == (3*4,3*4) assert inv_metric2.shape == (3*4,3*4) assert np.all(inv_metric1 == inv_metric2) @unittest.expectedFailure def test_fail_diag_e(self): sm = self.model inv_metric = np.ones((3*4,3*4))/10+np.eye(3*4) control_dict = {"metric" : "diag_e", "inv_metric" : inv_metric} fit = sm.sampling(data=dict(K=3, D=4), warmup=0, iter=10, algorithm="NUTS", control=control_dict, check_hmc_diagnostics=False, seed=14) @unittest.expectedFailure def test_fail_dense_e(self): sm = self.model inv_metric = self.ones(3*4) control_dict = {"metric" : "dense_e", "inv_metric" : inv_metric} fit = sm.sampling(data=dict(K=3, D=4), warmup=0, iter=10, algorithm="NUTS", control=control_dict, check_hmc_diagnostics=False, seed=14)
13,947
Python
.py
226
52.411504
158
0.627224
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,006
test_generated_quantities_seed.py
stan-dev_pystan2/pystan/tests/test_generated_quantities_seed.py
from collections import OrderedDict import gc import os import tempfile import unittest import numpy as np import pystan from pystan._compat import PY2 class TestGeneratedQuantitiesSeed(unittest.TestCase): """Verify that the RNG in the transformed data block uses the overall seed. See https://github.com/stan-dev/stan/issues/2241 """ @classmethod def setUpClass(cls): model_code = """ data { int<lower=0> N; } transformed data { vector[N] y; for (n in 1:N) y[n] = normal_rng(0, 1); } parameters { real mu; real<lower = 0> sigma; } model { y ~ normal(mu, sigma); } generated quantities { real mean_y = mean(y); real sd_y = sd(y); } """ cls.model = pystan.StanModel(model_code=model_code, verbose=True) def test_generated_quantities_seed(self): fit1 = self.model.sampling(data={'N': 1000}, iter=10, seed=123) extr1 = fit1.extract() fit2 = self.model.sampling(data={'N': 1000}, iter=10, seed=123) extr2 = fit2.extract() self.assertTrue((extr1['mean_y'] == extr2['mean_y']).all()) fit3 = self.model.sampling(data={'N': 1000}, iter=10, seed=456) extr3 = fit3.extract() self.assertFalse((extr1['mean_y'] == extr3['mean_y']).all())
1,494
Python
.py
45
24.022222
79
0.553782
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,007
test_utf8.py
stan-dev_pystan2/pystan/tests/test_utf8.py
import unittest from pystan import stanc, StanModel from pystan._compat import PY2 class TestUTF8(unittest.TestCase): desired = sorted({"status", "model_cppname", "cppcode", "model_name", "model_code", "include_paths"}) def test_utf8(self): model_code = 'parameters {real y;} model {y ~ normal(0,1);}' result = stanc(model_code=model_code) self.assertEqual(sorted(result.keys()), self.desired) self.assertTrue(result['cppcode'].startswith("// Code generated by Stan ")) self.assertEqual(result['status'], 0) def test_utf8_linecomment(self): model_code = u'parameters {real y;\n //äöéü\n} model {y ~ normal(0,1);}' result = stanc(model_code=model_code) self.assertEqual(sorted(result.keys()), self.desired) self.assertTrue(result['cppcode'].startswith("// Code generated by Stan ")) self.assertEqual(result['status'], 0) def test_utf8_multilinecomment(self): model_code = u'parameters {real y;\n /*äöéü\näöéü*/\n} model {y ~ normal(0,1);}' result = stanc(model_code=model_code) self.assertEqual(sorted(result.keys()), self.desired) self.assertTrue(result['cppcode'].startswith("// Code generated by Stan ")) self.assertEqual(result['status'], 0) def test_utf8_inprogramcode(self): model_code = u'parameters {real ö;\n} model {ö ~ normal(0,1);}' assertRaisesRegex = self.assertRaisesRegexp if PY2 else self.assertRaisesRegex with assertRaisesRegex(ValueError, 'Failed to parse Stan model .*'): stanc(model_code=model_code)
1,618
Python
.py
28
49.75
105
0.668579
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,008
test_extract.py
stan-dev_pystan2/pystan/tests/test_extract.py
import unittest import numpy as np from pandas.util.testing import assert_series_equal from numpy.testing import assert_array_equal import pystan class TestExtract(unittest.TestCase): @classmethod def setUpClass(cls): ex_model_code = ''' parameters { real alpha[2,3]; real beta[2]; } model { for (i in 1:2) for (j in 1:3) alpha[i, j] ~ normal(0, 1); for (i in 1:2) beta ~ normal(0, 2); } ''' cls.sm = sm = pystan.StanModel(model_code=ex_model_code) cls.fit = sm.sampling(chains=4, iter=2000) def test_extract_permuted(self): ss = self.fit.extract(permuted=True) alpha = ss['alpha'] beta = ss['beta'] lp__ = ss['lp__'] self.assertEqual(sorted(ss.keys()), sorted({'alpha', 'beta', 'lp__'})) self.assertEqual(alpha.shape, (4000, 2, 3)) self.assertEqual(beta.shape, (4000, 2)) self.assertEqual(lp__.shape, (4000,)) self.assertTrue((~np.isnan(alpha)).all()) self.assertTrue((~np.isnan(beta)).all()) self.assertTrue((~np.isnan(lp__)).all()) # extract one at a time alpha2 = self.fit.extract('alpha', permuted=True)['alpha'] self.assertEqual(alpha2.shape, (4000, 2, 3)) np.testing.assert_array_equal(alpha, alpha2) beta = self.fit.extract('beta', permuted=True)['beta'] self.assertEqual(beta.shape, (4000, 2)) lp__ = self.fit.extract('lp__', permuted=True)['lp__'] self.assertEqual(lp__.shape, (4000,)) def test_extract_permuted_false(self): fit = self.fit ss = fit.extract(permuted=False) num_samples = fit.sim['iter'] - fit.sim['warmup'] self.assertEqual(ss.shape, (num_samples, 4, 9)) self.assertTrue((~np.isnan(ss)).all()) def test_extract_permuted_false_pars(self): fit = self.fit ss = fit.extract(pars=['beta'], permuted=False) num_samples = fit.sim['iter'] - fit.sim['warmup'] self.assertEqual(ss['beta'].shape, (num_samples, 4, 2)) self.assertTrue((~np.isnan(ss['beta'])).all()) def test_extract_permuted_false_pars_inc_warmup(self): fit = self.fit ss = fit.extract(pars=['beta'], inc_warmup=True, permuted=False) num_samples = fit.sim['iter'] self.assertEqual(ss['beta'].shape, (num_samples, 4, 2)) self.assertTrue((~np.isnan(ss['beta'])).all()) def test_extract_permuted_false_inc_warmup(self): fit = self.fit ss = fit.extract(inc_warmup=True, permuted=False) num_samples = fit.sim['iter'] self.assertEqual(ss.shape, (num_samples, 4, 9)) self.assertTrue((~np.isnan(ss)).all()) def test_extract_thin(self): sm = self.sm fit = sm.sampling(chains=4, iter=2000, thin=2) # permuted True ss = fit.extract(permuted=True) alpha = ss['alpha'] beta = ss['beta'] lp__ = ss['lp__'] self.assertEqual(sorted(ss.keys()), sorted({'alpha', 'beta', 'lp__'})) self.assertEqual(alpha.shape, (2000, 2, 3)) self.assertEqual(beta.shape, (2000, 2)) self.assertEqual(lp__.shape, (2000,)) self.assertTrue((~np.isnan(alpha)).all()) self.assertTrue((~np.isnan(beta)).all()) self.assertTrue((~np.isnan(lp__)).all()) # permuted False ss = fit.extract(permuted=False) self.assertEqual(ss.shape, (500, 4, 9)) self.assertTrue((~np.isnan(ss)).all()) # permuted False inc_warmup True ss = fit.extract(inc_warmup=True, permuted=False) self.assertEqual(ss.shape, (1000, 4, 9)) self.assertTrue((~np.isnan(ss)).all()) def test_extract_dtype(self): dtypes = {"alpha": np.int, "beta": np.int} ss = self.fit.extract(dtypes = dtypes) alpha = ss['alpha'] beta = ss['beta'] lp__ = ss['lp__'] self.assertEqual(alpha.dtype, np.dtype(np.int)) self.assertEqual(beta.dtype, np.dtype(np.int)) self.assertEqual(lp__.dtype, np.dtype(np.float)) def test_extract_dtype_permuted_false(self): dtypes = {"alpha": np.int, "beta": np.int} pars = ['alpha', 'beta', 'lp__'] ss = self.fit.extract(pars=pars, dtypes = dtypes, permuted=False) alpha = ss['alpha'] beta = ss['beta'] lp__ = ss['lp__'] self.assertEqual(alpha.dtype, np.dtype(np.int)) self.assertEqual(beta.dtype, np.dtype(np.int)) self.assertEqual(lp__.dtype, np.dtype(np.float)) def test_to_dataframe_permuted_true(self): ss = self.fit.extract(permuted=True) alpha = ss['alpha'] beta = ss['beta'] lp__ = ss['lp__'] df = self.fit.to_dataframe(permuted=True) self.assertEqual(df.shape, (4000,7+9+6)) for idx in range(2): for jdx in range(3): name = 'alpha[{},{}]'.format(idx+1,jdx+1) assert_array_equal(df[name].values,alpha[:,idx,jdx]) for idx in range(2): name = 'beta[{}]'.format(idx+1) assert_array_equal(df[name].values,beta[:,idx]) assert_array_equal(df['lp__'].values,lp__) # Test pars argument df = self.fit.to_dataframe(pars='alpha', permuted=True) self.assertEqual(df.shape, (4000,7+6+6)) for idx in range(2): for jdx in range(3): name = 'alpha[{},{}]'.format(idx+1,jdx+1) assert_array_equal(df[name].values,alpha[:,idx,jdx]) # Test pars and dtype argument df = self.fit.to_dataframe(pars='alpha',dtypes = {'alpha':np.int}, permuted=True) alpha_int = ss['alpha'].astype(np.int) self.assertEqual(df.shape, (4000,7+6+6)) for idx in range(2): for jdx in range(3): name = 'alpha[{},{}]'.format(idx+1,jdx+1) assert_array_equal(df[name].values,alpha_int[:,idx,jdx]) def test_to_dataframe_permuted_false_inc_warmup_false(self): fit = self.fit ss = fit.extract(permuted=False) df = fit.to_dataframe(permuted=False) num_samples = fit.sim['iter'] - fit.sim['warmup'] num_chains = fit.sim['chains'] self.assertEqual(df.shape, (num_samples*num_chains,3+9+6)) alpha_index = 0 for jdx in range(3): for idx in range(2): name = 'alpha[{},{}]'.format(idx+1,jdx+1) for n in range(num_chains): assert_array_equal( df.loc[df.chain == n, name].values,ss[:,n,alpha_index] ) alpha_index += 1 for idx in range(2): name = 'beta[{}]'.format(idx+1) for n in range(num_chains): assert_array_equal( df.loc[df.chain == n, name].values,ss[:,n,6+idx] ) for n in range(num_chains): assert_array_equal(df.loc[df.chain == n,'lp__'].values,ss[:,n,-1]) diagnostic_type = {'divergent':int,'energy':float,'treedepth':int, 'accept_stat':float, 'stepsize':float, 'n_leapfrog':int} for n in range(num_chains): assert_array_equal( df.chain.values[n*num_samples:(n+1)*num_samples], n*np.ones(num_samples,dtype=np.int) ) assert_array_equal( df.draw.values[n*num_samples:(n+1)*num_samples], np.arange(num_samples,dtype=np.int) ) for diag, diag_type in diagnostic_type.items(): assert_array_equal( df[diag+'__'].values[n*num_samples:(n+1)*num_samples], fit.get_sampler_params()[n][diag+'__'][-num_samples:].astype(diag_type) ) def test_to_dataframe_permuted_false_inc_warmup_true(self): fit = self.fit ss = fit.extract(permuted=False, inc_warmup=True) df = fit.to_dataframe(permuted=False,inc_warmup=True) num_samples = fit.sim['iter'] num_chains = fit.sim['chains'] self.assertEqual(df.shape, (num_samples*num_chains,3+9+6)) alpha_index = 0 for jdx in range(3): for idx in range(2): name = 'alpha[{},{}]'.format(idx+1,jdx+1) for n in range(num_chains): assert_array_equal( df.loc[df.chain == n, name].values,ss[:,n,alpha_index] ) alpha_index += 1 for idx in range(2): name = 'beta[{}]'.format(idx+1) for n in range(num_chains): assert_array_equal( df.loc[df.chain == n, name].values,ss[:,n,6+idx] ) for n in range(num_chains): assert_array_equal(df.loc[df.chain == n,'lp__'].values,ss[:,n,-1]) assert_array_equal(df.loc[ n*fit.sim['n_save'][n]:n*fit.sim['n_save'][n]+fit.sim['warmup2'][n]-1, 'warmup'].values, np.ones(fit.sim['warmup2'][n])) assert_array_equal(df.loc[ n*fit.sim['n_save'][n]+fit.sim['warmup2'][n]: (n+1)*fit.sim['n_save'][n]-1,'warmup'].values, np.zeros(fit.sim['warmup2'][n])) diagnostic_type = {'divergent':int,'energy':float,'treedepth':int, 'accept_stat':float, 'stepsize':float, 'n_leapfrog':int} for n in range(num_chains): assert_array_equal( df.chain.values[n*num_samples:(n+1)*num_samples], n*np.ones(num_samples,dtype=np.int) ) assert_array_equal( df.draw.values[n*num_samples:(n+1)*num_samples], np.arange(num_samples,dtype=np.int)-int(fit.sim['warmup']) ) for diag, diag_type in diagnostic_type.items(): assert_array_equal( df[diag+'__'].values[n*num_samples:(n+1)*num_samples], fit.get_sampler_params()[n][diag+'__'][-num_samples:].astype(diag_type) ) def test_to_dataframe_permuted_false_diagnostics_false(self): fit = self.fit ss = fit.extract(permuted=False) df = fit.to_dataframe(permuted=False,diagnostics=False) num_samples = fit.sim['iter'] - fit.sim['warmup'] num_chains = fit.sim['chains'] self.assertEqual(df.shape, (num_samples*num_chains,3+9)) alpha_index = 0 for jdx in range(3): for idx in range(2): name = 'alpha[{},{}]'.format(idx+1,jdx+1) for n in range(num_chains): assert_array_equal( df[name].loc[df.chain == n].values,ss[:,n,alpha_index] ) alpha_index += 1 for idx in range(2): name = 'beta[{}]'.format(idx+1) for n in range(num_chains): assert_array_equal( df[name].loc[df.chain == n].values,ss[:,n,6+idx] ) for n in range(num_chains): assert_array_equal(df.loc[df.chain == n,'lp__'].values,ss[:,n,-1]) for n in range(num_chains): assert_array_equal( df.chain.values[n*num_samples:(n+1)*num_samples], n*np.ones(num_samples,dtype=np.int) ) assert_array_equal( df.draw.values[n*num_samples:(n+1)*num_samples], np.arange(num_samples,dtype=np.int) ) def test_to_dataframe_permuted_false_pars(self): fit = self.fit ss = fit.extract(permuted=False) df = fit.to_dataframe(permuted=False, pars='alpha') num_samples = fit.sim['iter'] - fit.sim['warmup'] num_chains = fit.sim['chains'] self.assertEqual(df.shape, (num_samples*num_chains,3+6+6)) alpha_index = 0 for jdx in range(3): for idx in range(2): name = 'alpha[{},{}]'.format(idx+1,jdx+1) for n in range(num_chains): assert_array_equal( df[name].loc[df.chain == n].values,ss[:,n,alpha_index] ) alpha_index += 1 diagnostic_type = {'divergent':int,'energy':float,'treedepth':int, 'accept_stat':float, 'stepsize':float, 'n_leapfrog':int} for n in range(num_chains): assert_array_equal( df.chain.values[n*num_samples:(n+1)*num_samples], n*np.ones(num_samples,dtype=np.int) ) assert_array_equal( df.draw.values[n*num_samples:(n+1)*num_samples], np.arange(num_samples,dtype=np.int) ) for diag, diag_type in diagnostic_type.items(): assert_array_equal( df[diag+'__'].values[n*num_samples:(n+1)*num_samples], fit.get_sampler_params()[n][diag+'__'][-num_samples:].astype(diag_type) )
13,084
Python
.py
290
33.265517
104
0.537974
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,009
test_basic_array.py
stan-dev_pystan2/pystan/tests/test_basic_array.py
import unittest import numpy as np import pystan class TestBasicArray(unittest.TestCase): @classmethod def setUpClass(cls): model_code = """ data { int<lower=2> K; } parameters { real beta[K,1,2]; } model { for (k in 1:K) beta[k,1,1] ~ normal(0,1); for (k in 1:K) beta[k,1,2] ~ normal(100,1); }""" cls.model = pystan.StanModel(model_code=model_code) cls.fit = cls.model.sampling(data=dict(K=4)) def test_array_param_sampling(self): """ Make sure shapes are getting unraveled correctly. Mixing up row-major and column-major data is a potential issue. """ fit = self.fit # extract, permuted beta = fit.extract()['beta'] self.assertEqual(beta.shape, (4000, 4, 1, 2)) beta_mean = np.mean(beta, axis=0) self.assertEqual(beta_mean.shape, (4, 1, 2)) self.assertTrue(np.all(beta_mean[:, 0, 0] < 4)) self.assertTrue(np.all(beta_mean[:, 0, 1] > 100 - 4)) # extract, permuted=False extracted = fit.extract(permuted=False) self.assertEqual(extracted.shape, (1000, 4, 9)) # in theory 0:4 should be # 'beta[0,0,0]' # 'beta[1,0,0]' # 'beta[2,0,0]' # 'beta[3,0,0]' # # and 4:8 should be # 'beta[0,0,1]' # 'beta[1,0,1]' # 'beta[2,0,1]' # 'beta[3,0,1]' self.assertTrue(np.all(np.mean(extracted[:, :, 0:4], axis=(0, 1)) < 4)) self.assertTrue(np.all(np.mean(extracted[:, :, 4:8], axis=(0, 1)) > 100 - 4)) self.assertTrue(np.all(extracted[:, :, 8] < 0)) # lp__ def test_array_param_optimizing(self): fit = self.fit sm = fit.stanmodel op = sm.optimizing(data=dict(K=4)) beta = op['beta'] self.assertEqual(beta.shape, (4, 1, 2)) self.assertTrue(np.all(beta[:, 0, 0] < 4)) self.assertTrue(np.all(beta[:, 0, 1] > 100 - 4))
2,048
Python
.py
59
26.101695
85
0.531313
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,010
test_misc.py
stan-dev_pystan2/pystan/tests/test_misc.py
from collections import OrderedDict import os import tempfile import unittest import numpy as np from pystan import misc from pystan._compat import PY2 from pystan.constants import MAX_UINT def is_valid_seed(seed): return isinstance(seed, int) and seed >= 0 and seed <= MAX_UINT class TestMisc(unittest.TestCase): def test_pars_total_indexes(self): pars_oi = ['mu', 'tau', 'eta', 'theta', 'lp__'] dims_oi = [[], [], [8], [8], []] fnames_oi = ['mu', 'tau', 'eta[1]', 'eta[2]', 'eta[3]', 'eta[4]', 'eta[5]', 'eta[6]', 'eta[7]', 'eta[8]', 'theta[1]', 'theta[2]', 'theta[3]', 'theta[4]', 'theta[5]', 'theta[6]', 'theta[7]', 'theta[8]', 'lp__'] pars = ['mu', 'tau', 'eta', 'theta', 'lp__'] rslt = misc._pars_total_indexes(pars_oi, dims_oi, fnames_oi, pars) self.assertEqual(rslt['mu'], (0,)) self.assertEqual(rslt['tau'], (1,)) self.assertEqual(rslt['eta'], (2, 3, 4, 5, 6, 7, 8, 9)) self.assertEqual(rslt['theta'], (10, 11, 12, 13, 14, 15, 16, 17)) self.assertEqual(rslt['lp__'], (18,)) def test_par_vector2dict(self): v = [0, 1, -1, -1, 0, 1, -1, -2] pars = ['alpha', 'beta'] dims = [[2, 3], [2]] rslt = misc._par_vector2dict(v, pars, dims) np.testing.assert_equal(rslt['alpha'], np.array([0, 1, -1, -1, 0, 1]).reshape(dims[0], order='F')) np.testing.assert_equal(rslt['beta'], np.array([-1, -2])) def test_check_seed(self): self.assertEqual(misc._check_seed('10'), 10) self.assertEqual(misc._check_seed(10), 10) self.assertEqual(misc._check_seed(10.5), 10) self.assertTrue(is_valid_seed(misc._check_seed(np.random.RandomState()))) self.assertTrue(is_valid_seed(misc._check_seed(-1))) def test_check_seed_gt_max_uint(self): assertRaisesRegex = self.assertRaisesRegexp if PY2 else self.assertRaisesRegex with assertRaisesRegex(ValueError, '`seed` is too large'): misc._check_seed(MAX_UINT + 1) def test_stan_rdump(self): data = OrderedDict(x=1, y=0, z=[1, 2, 3], Phi=np.array([[1, 2], [3, 4]])) tempdir = tempfile.mkdtemp() filename = os.path.join(tempdir, 'test_rdump.rdump') misc.stan_rdump(data, filename) data_recovered = misc.read_rdump(filename) np.testing.assert_equal(data, data_recovered) data = OrderedDict(x=True, y=np.array([True, False])) data_expected = OrderedDict(x=1, y=np.array([1, 0])) misc.stan_rdump(data, filename) data_recovered = misc.read_rdump(filename) np.testing.assert_equal(data_recovered, data_expected) data = OrderedDict(x='foo') np.testing.assert_raises(ValueError, misc.stan_rdump, data, filename) data = OrderedDict(new=3) np.testing.assert_raises(ValueError, misc.stan_rdump, data, filename) def test_stan_rdump_array(self): y = np.asarray([[1, 3, 5], [2, 4, 6]]) data = {'y': y} expected = 'y <-\nstructure(c(1, 2, 3, 4, 5, 6), .Dim = c(2, 3))\n' np.testing.assert_equal(misc._dict_to_rdump(data), expected) def test_stan_read_rdump_array(self): """ For reference: > structure(c(1, 2, 3, 4, 5, 6), .Dim = c(2, 3)) [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 """ # make this into some sort of stream rdump = 'y <-\nstructure(c(1, 2, 3, 4, 5, 6), .Dim = c(2, 3))\n' tempdir = tempfile.mkdtemp() filename = os.path.join(tempdir, 'test_rdump.rdump') with open(filename, 'w') as f: f.write(rdump) d = misc.read_rdump(filename) y = np.asarray([[1, 3, 5], [2, 4, 6]]) np.testing.assert_equal(d['y'], y) def test_rstan_read_rdump(self): a = np.array([1, 3, 5]) b = np.arange(10).reshape((-1, 2)) c = np.arange(18).reshape([2, 3, 3]) data = dict(a=a, b=b, c=c) tempdir = tempfile.mkdtemp() filename = os.path.join(tempdir, 'test_rdump.rdump') misc.stan_rdump(data, filename) d = misc.read_rdump(filename) np.testing.assert_equal(d['a'], a) np.testing.assert_equal(d['b'], b) np.testing.assert_equal(d['c'], c) def test_remove_empty_pars(self): pars = ('alpha', 'beta', 'gamma', 'eta', 'xi') dims = [[], (2,), (2, 4), 0, (2, 0)] # NOTE: np.prod([]) -> 1 np.testing.assert_equal(misc._remove_empty_pars(pars[0:1], pars, dims), pars[0:1]) np.testing.assert_equal(misc._remove_empty_pars(pars[0:3], pars, dims), pars[0:3]) np.testing.assert_equal(misc._remove_empty_pars(pars[0:4], pars, dims), pars[0:3]) np.testing.assert_equal(misc._remove_empty_pars(['beta[1]'], pars, dims), ['beta[1]']) np.testing.assert_equal(misc._remove_empty_pars(['eta'], pars, dims), []) def test_format_number_si(self): np.testing.assert_equal(misc._format_number_si(-12345, 2), '-1.2e4') np.testing.assert_equal(misc._format_number_si(123456, 2), '1.2e5') np.testing.assert_equal(misc._format_number_si(-123456, 2), '-1.2e5') np.testing.assert_equal(misc._format_number_si(-123456.393, 2), '-1.2e5') np.testing.assert_equal(misc._format_number_si(1234567, 2), '1.2e6') np.testing.assert_equal(misc._format_number_si(0.12, 2), '1.2e-1') np.testing.assert_equal(misc._format_number_si(3.32, 2), '3.3e0') def test_format_number(self): np.testing.assert_equal(misc._format_number(-1234, 2, 6), '-1234') np.testing.assert_equal(misc._format_number(-12345, 2, 6), '-12345') np.testing.assert_equal(misc._format_number(123456, 2, 6), '123456') np.testing.assert_equal(misc._format_number(-123456, 2, 6), '-1.2e5') np.testing.assert_equal(misc._format_number(1234567, 2, 6), '1.2e6') np.testing.assert_equal(misc._format_number(0.12, 2, 6), '0.12') np.testing.assert_equal(misc._format_number(3.32, 2, 6), '3.32') np.testing.assert_equal(misc._format_number(3.3, 2, 6), '3.3') np.testing.assert_equal(misc._format_number(3.32, 2, 6), '3.32') np.testing.assert_equal(misc._format_number(3.323945, 2, 6), '3.32') np.testing.assert_equal(misc._format_number(-0.0003434, 2, 6), '-3.4e-4') np.testing.assert_equal(misc._format_number(1654.25, 2, 6), '1654.2') np.testing.assert_equal(misc._format_number(-1654.25, 2, 6), '-1654') np.testing.assert_equal(misc._format_number(-165.25, 2, 6), '-165.2') np.testing.assert_equal(misc._format_number(9.94598693e-01, 2, 6), '0.99') np.testing.assert_equal(misc._format_number(-9.94598693e-01, 2, 6), '-0.99') def test_format_number_inf(self): np.testing.assert_equal(misc._format_number_si(float('inf'), 2), 'inf') np.testing.assert_equal(misc._format_number_si(float('-inf'), 2), '-inf') def test_array_to_table(self): rownames = np.array(['alpha', 'beta[0]', 'beta[1]', 'beta[2]', 'beta[3]', 'sigma', 'lp__']) colnames = ('mean', 'se_mean', 'sd', '2.5%', '25%', '50%', '75%', '97.5%', 'n_eff', 'Rhat') arr = np.array([[-1655, 625, 1654, -4378, -3485, -927, -27, -9, 7, 2], [ -47, 59, 330, -770, -69, -2, 2, 1060, 31, 1], [ -18, 70, 273, -776, -30, 0, 35, 608, 15, 1], [ 8, 38, 230, -549, -26, 0, 17, 604, 36, 1], [ 23, 32, 303, -748, -34, 0, 49, 751, 92, 1], [ 405, 188, 974, 0, 4, 73, 458, 2203, 27, 1], [ -13, 3, 8, -23, -20, -15, -5, 1, 8, 2]]) n_digits = 2 result = misc._array_to_table(arr, rownames, colnames, n_digits) desired = "alpha -1655 625 1654 -4378 -3485 -927 -27 -9 7 2" desired_py2 = "alpha -1655 625.0 1654.0 -4378 -3485 -927.0 -27.0 -9.0 7.0 2.0" # round() behaves differently in Python 3 if PY2: np.testing.assert_equal(result.split('\n')[1], desired_py2) else: np.testing.assert_equal(result.split('\n')[1], desired) arr = np.array([[-1655325, 625.25, 1654.25, -4378.25, -3485.25, -927.25, -27.25, -9.25, 7.25, 2], [ -47.25, 59.25, 330.25, -770.25, -69.25, -2.25, 2.25, 1060.25, 31.25, 1], [ -18.25, 70.25, 273.25, -776.25, -30.25, 0.25, 35.25, 608.25, 15.25, 1], [ 8.25, 38.25, 230.25, -549.25, -26.25, 0.25, 17.25, 604.25, 36.25, 1], [ 23.25, 32.25, 303.25, -748.25, -34.25, 0.25, 49.25, 751.25, 92.25, 1], [ 405.25, 188.25, 974.25, 0.25, 4.25, 73.25, 458.25, 2203.25, 27.25, 1], [ -13.25, 3.25, 8.25, -23.25, -20.25, -15.25, -5.25, 1.25, 8.25, 2]]) result = misc._array_to_table(arr, rownames, colnames, n_digits) desired = "alpha -1.7e6 625.25 1654.2 -4378 -3485 -927.2 -27.25 -9.25 7 2.0" desired_py2 = "alpha -1.7e6 625.25 1654.2 -4378 -3485 -927.2 -27.25 -9.25 7.0 2.0" # round() behaves differently in Python 3 if PY2: np.testing.assert_equal(result.split('\n')[1], desired_py2) else: np.testing.assert_equal(result.split('\n')[1], desired)
9,688
Python
.py
163
49.546012
113
0.537514
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,011
test_basic_matrix.py
stan-dev_pystan2/pystan/tests/test_basic_matrix.py
import unittest import numpy as np from pystan import StanModel from pystan.tests.helper import get_model class TestMatrixParam(unittest.TestCase): @classmethod def setUpClass(cls): model_code = """ data { int<lower=2> K; int<lower=1> D; } parameters { matrix[K,D] beta; } model { for (k in 1:K) for (d in 1:D) beta[k,d] ~ normal((d==2?100:0),1); }""" cls.model = get_model("matrix_normal_model", model_code) #cls.model = StanModel(model_code=model_code) def test_matrix_param(self): sm = self.model fit = sm.sampling(data=dict(K=3, D=4)) beta = fit.extract()['beta'] assert beta.shape == (4000, 3, 4) assert np.mean(beta[:, 0, 0]) < 4 extracted = fit.extract(permuted=False) assert extracted.shape == (1000, 4, 13) assert np.mean(extracted[:,:,0]) < 4 assert np.all(extracted[:,:,12] < 0) # lp__ def test_matrix_param_order(self): sm = self.model fit = sm.sampling(data=dict(K=3, D=2)) beta = fit.extract()['beta'] assert beta.shape == (4000, 3, 2) beta_mean = np.mean(beta, axis=0) beta_colmeans = np.mean(beta_mean, axis=0) assert beta_colmeans[0] < 4 assert beta_colmeans[1] > 100 - 4 def test_matrix_param_order_optimizing(self): sm = self.model op = sm.optimizing(data=dict(K=3, D=2)) beta = op['beta'] assert beta.shape == (3, 2) beta_colmeans = np.mean(beta, axis=0) assert beta_colmeans[0] < 4 assert beta_colmeans[1] > 100 - 4
1,684
Python
.py
49
26.306122
64
0.562922
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,012
test_posterior_means.py
stan-dev_pystan2/pystan/tests/test_posterior_means.py
import unittest import numpy as np import pystan class TestPosteriorMeans(unittest.TestCase): """Test get_posterior_mean""" @classmethod def setUpClass(cls): model_code = """ data { int<lower=0> n_subjects; // number of subjects int<lower=0,upper=40> score[n_subjects]; // UPSIT scores int<lower=0,upper=40> n_questions; // number of questions } parameters { real rating[n_subjects]; } transformed parameters { real p[n_subjects]; for (j in 1:n_subjects) { p[j] = exp(rating[j])/(1+exp(rating[j])); // Logistic function } } model { rating ~ normal(0, 1); score ~ binomial(40, p); } """ cls.sm = pystan.StanModel(model_code=model_code) cls.data = {'n_questions': 40, 'n_subjects': 92, 'score': np.random.randint(0, 40, 92)} def test_posterior_means(self): sm = self.sm data = self.data fit = sm.sampling(data, iter=100) self.assertIsNotNone(fit.get_posterior_mean())
1,185
Python
.py
36
23.055556
78
0.535902
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,013
test_chains.py
stan-dev_pystan2/pystan/tests/test_chains.py
from collections import OrderedDict import math import os import unittest import numpy as np import pystan import pystan.chains class TestMcmcChains(unittest.TestCase): # REF: stan/src/test/unit/mcmc/chains_test.cpp @classmethod def setUpClass(cls): testdata_path = os.path.join(os.path.dirname(__file__), 'data') f1 = os.path.join(testdata_path, 'blocker.1.csv') f2 = os.path.join(testdata_path, 'blocker.2.csv') # read csv using numpy c1 = np.loadtxt(f1, skiprows=41, delimiter=',')[:, 4:] c1_colnames = open(f1, 'r').readlines()[36].strip().split(',')[4:] np.testing.assert_equal(c1_colnames[0], 'd') c2 = np.loadtxt(f2, skiprows=41, delimiter=',')[:, 4:] c2_colnames = open(f2, 'r').readlines()[36].strip().split(',')[4:] np.testing.assert_equal(c1_colnames, c2_colnames) np.testing.assert_equal(len(c1_colnames), c1.shape[1]) n_samples = len(c1) np.testing.assert_equal(n_samples, 1000) c1 = OrderedDict((k, v) for k, v in zip(c1_colnames, c1.T)) c2 = OrderedDict((k, v) for k, v in zip(c2_colnames, c2.T)) cls.lst = dict(fnames_oi=c1_colnames, samples=[{'chains': c1}, {'chains': c2}], n_save=np.repeat(n_samples, 2), permutation=None, warmup=0, warmup2=[0, 0], chains=2, n_flatnames=len(c1)) def test_essnrhat(self): n_eff = [ 466.099,136.953,1170.390,541.256, 518.051,589.244,764.813,688.294, 323.777,502.892,353.823,588.142, 654.336,480.914,176.978,182.649, 642.389,470.949,561.947,581.187, 446.389,397.641,338.511,678.772, 1442.250,837.956,869.865,951.124, 619.336,875.805,233.260,786.568, 910.144,231.582,907.666,747.347, 720.660,195.195,944.547,767.271, 723.665,1077.030,470.903,954.924, 497.338,583.539,697.204,98.421 ] lst = self.lst for i in range(4, len(n_eff)): ess = pystan.chains.ess(lst, i) self.assertAlmostEqual(ess, n_eff[i], delta=.01) def test_rhat(self): r_hat = [ 1.00718, 1.00473, 0.999203, 1.00061, 1.00378, 1.01031, 1.00173, 1.0045, 1.00111, 1.00337, 1.00546, 1.00105, 1.00558, 1.00463, 1.00534, 1.01244, 1.00174, 1.00718, 1.00186, 1.00554, 1.00436, 1.00147, 1.01017, 1.00162, 1.00143, 1.00058, 0.999221, 1.00012, 1.01028, 1.001, 1.00305, 1.00435, 1.00055, 1.00246, 1.00447, 1.0048, 1.00209, 1.01159, 1.00202, 1.00077, 1.0021, 1.00262, 1.00308, 1.00197, 1.00246, 1.00085, 1.00047, 1.00735 ] lst = self.lst for i in range(4, len(r_hat)): rhat = pystan.chains.splitrhat(lst, i) self.assertAlmostEqual(rhat, r_hat[i], delta=0.001) class TestRhatZero(unittest.TestCase): def test_rhat_zero(self): model_code = """ parameters { real x; } transformed parameters { real y; y = 0.0; } model {x ~ normal(0, 1);} """ model = pystan.StanModel(model_code=model_code) fit = model.sampling() rhat = pystan.chains.splitrhat(fit.sim, 1) self.assertTrue(math.isnan(rhat))
3,353
Python
.py
76
34.328947
87
0.574012
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,014
test_covexpquad.py
stan-dev_pystan2/pystan/tests/test_covexpquad.py
import unittest from pystan import StanModel class TestCovExpQuad(unittest.TestCase): """ Unit test added to address issue discussed here: https://github.com/stan-dev/pystan/issues/271 """ @classmethod def setUpClass(cls): covexpquad = """ data { real rx1[5]; } model { matrix[5,5] a; a = cov_exp_quad(rx1, 1, 1); } """ cls.model = StanModel(model_code=covexpquad) def test_covexpquad(self): model = self.model self.assertIsNotNone(model)
563
Python
.py
21
19.904762
98
0.60223
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,015
test_ess.py
stan-dev_pystan2/pystan/tests/test_ess.py
import unittest import pystan import pystan.chains import pystan._chains from pystan.tests.helper import get_model # NOTE: This test is fragile because the default sampling algorithm used by Stan # may change in significant ways. class TestESS(unittest.TestCase): @classmethod def setUpClass(cls): model_code = 'parameters {real y;} model {y ~ normal(0,1);}' cls.model = get_model("standard_normal_model", model_code, model_name="normal1", verbose=True, obfuscate_model_name=False) #model = pystan.StanModel(model_code=model_code) cls.fits = [cls.model.sampling(iter=4000, chains=2, seed=i) for i in range(10)] def test_ess(self): sims = [fit.sim for fit in self.fits] esses = [pystan.chains.ess(sim, sim['fnames_oi'].index('y')) for sim in sims] # in Stan 2.15 the default acceptance rate was changed, ess dropped self.assertGreater(sum(esses) / len(esses), 1200)
1,007
Python
.py
21
40.190476
87
0.664286
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,016
test_external_cpp.py
stan-dev_pystan2/pystan/tests/test_external_cpp.py
import unittest import numpy as np from numpy.testing import assert_array_equal import os import pystan # NOTE: This test is fragile because the default sampling algorithm used by Stan # may change in significant ways. external_cpp_code = """ inline double my_func (double A, double B, std::ostream* pstream) { double C = A*B*B+A; return C; } inline var my_func (const var& A_var, const var& B_var, std::ostream* pstream) { // Compute the value double A = A_var.val(), B = B_var.val(), C = my_func(A, B, pstream); // Compute the partial derivatives: double dC_dA = B*B+1.0, dC_dB = 2.0*A*B; // Autodiff wrapper: return var(new precomp_vv_vari( C, // The _value_ of the output A_var.vi_, // The input gradient wrt A B_var.vi_, // The input gradient wrt B dC_dA, // The partial introduced by this function wrt A dC_dB // The partial introduced by this function wrt B )); } inline var my_func (double A, const var& B_var, std::ostream* pstream) { double B = B_var.val(), C = my_func(A, B, pstream), dC_dB = 2.0*A*B; return var(new precomp_v_vari(C, B_var.vi_, dC_dB)); } inline var my_func (const var& A_var, double B, std::ostream* pstream) { double A = A_var.val(), C = my_func(A, B, pstream), dC_dA = B*B+1.0; return var(new precomp_v_vari(C, A_var.vi_, dC_dA)); } """ external_cpp_code_stan_autograd = """ template <typename T1, typename T2> typename boost::math::tools::promote_args<T1, T2>::type my_other_func (const T1& A, const T2& B, std::ostream* pstream) { typedef typename boost::math::tools::promote_args<T1, T2>::type T; T C = A*B*B+A; return C; } """ class TestExternalCpp(unittest.TestCase): @classmethod def setUpClass(cls): include_dir = os.path.join(os.path.dirname(__file__), 'data') with open(os.path.join(include_dir, "external_cpp.hpp"), "w") as f: f.write(external_cpp_code) with open(os.path.join(include_dir, "external_autograd_cpp.hpp"), "w") as f: f.write(external_cpp_code_stan_autograd) model_code = """ functions { real my_func(real A, real B); real my_other_func(real A, real B); } data { real B; } parameters { real A; real D; } transformed parameters { real C = my_func(A, B); real E = my_other_func(D, B); } model { C ~ std_normal(); E ~ normal(5,3); } """ cls.model = pystan.StanModel(model_code=model_code, verbose=True, allow_undefined=True, includes=["external_cpp.hpp", "external_autograd_cpp.hpp"], include_dirs=[include_dir], ) cls.B = 4.0 cls.fit = cls.model.sampling(data={"B" : cls.B}, iter=100, chains=2) os.remove(os.path.join(include_dir, "external_cpp.hpp")) os.remove(os.path.join(include_dir, "external_autograd_cpp.hpp")) def test_external_cpp(self): A = self.fit["A"] B = self.B C = self.fit["C"] assert_array_equal(C, A * B * B + A) def test_external_autograd_cpp(self): B = self.B D = self.fit["D"] E = self.fit["E"] assert_array_equal(E, D * B * B + D)
3,693
Python
.py
101
27.148515
85
0.536496
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,017
test_extra_compile_args.py
stan-dev_pystan2/pystan/tests/test_extra_compile_args.py
import distutils.errors import sys import os import unittest import pystan from pystan._compat import PY2 class TestExtraCompileArgs(unittest.TestCase): def test_extra_compile_args(self): extra_compile_args = [ '-O3', '-ftemplate-depth-1024', '-Wno-unused-function', '-Wno-uninitialized', ] model_code = 'parameters {real y;} model {y ~ normal(0,1);}' model = pystan.StanModel(model_code=model_code, model_name="normal1", extra_compile_args=extra_compile_args) fit = model.sampling() extr = fit.extract() y_last, log_prob_last = extr['y'][-1], extr['lp__'][-1] self.assertEqual(fit.log_prob(y_last), log_prob_last) def test_extra_compile_args_failure(self): extra_compile_args = ['-non-existent-option'] if sys.platform.startswith("win"): return model_code = 'parameters {real y;} model {y ~ normal(0,1);}' assertRaisesRegex = self.assertRaisesRegexp if PY2 else self.assertRaisesRegex with assertRaisesRegex(distutils.errors.CompileError, 'failed with exit status'): pystan.StanModel(model_code=model_code, model_name="normal1", extra_compile_args=extra_compile_args) def test_threading_support(self): # Set up environmental variable os.environ['STAN_NUM_THREADS'] = "2" stan_code = """ functions { vector bl_glm(vector mu_sigma, vector beta, real[] x, int[] y) { vector[2] mu = mu_sigma[1:2]; vector[2] sigma = mu_sigma[3:4]; real lp = normal_lpdf(beta | mu, sigma); real ll = bernoulli_logit_lpmf(y | beta[1] + beta[2] * to_vector(x)); return [lp + ll]'; } } data { int<lower = 0> K; int<lower = 0> N; vector[N] x; int<lower = 0, upper = 1> y[N]; } transformed data { int<lower = 0> J = N / K; real x_r[K, J]; int<lower = 0, upper = 1> x_i[K, J]; { int pos = 1; for (k in 1:K) { int end = pos + J - 1; x_r[k] = to_array_1d(x[pos:end]); x_i[k] = y[pos:end]; pos += J; } } } parameters { vector[2] beta[K]; vector[2] mu; vector<lower=0>[2] sigma; } model { mu ~ normal(0, 2); sigma ~ normal(0, 2); target += sum(map_rect(bl_glm, append_row(mu, sigma), beta, x_r, x_i)); } """ stan_data = dict( K = 4, N = 12, x = [1.204, -0.573, -1.35, -1.157, -1.29, 0.515, 1.496, 0.918, 0.517, 1.092, -0.485, -2.157], y = [1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1] ) stan_model = pystan.StanModel(model_code=stan_code) for i in range(10): try: fit = stan_model.sampling(data=stan_data, chains=2, iter=200, n_jobs=1) self.assertIsNotNone(fit) fit2 = stan_model.sampling(data=stan_data, chains=2, iter=200, n_jobs=2) self.assertIsNotNone(fit2) draw = fit.extract(pars=fit.model_pars+['lp__'], permuted=False) lp = {key : values[-1, 0] for key, values in draw.items() if key == 'lp__'}['lp__'] draw = {key : values[-1, 0] for key, values in draw.items() if key != 'lp__'} draw = fit.unconstrain_pars(draw) self.assertEqual(fit.log_prob(draw), lp) draw2 = fit2.extract(pars=fit2.model_pars+['lp__'], permuted=False) lp2 = {key : values[-1, 0] for key, values in draw2.items() if key == 'lp__'}['lp__'] draw2 = {key : values[-1, 0] for key, values in draw2.items() if key != 'lp__'} draw2 = fit2.unconstrain_pars(draw2) self.assertEqual(fit2.log_prob(draw2), lp2) break except AssertionError: if i < 9: continue else: raise
4,296
Python
.py
107
27.962617
101
0.495577
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,018
test_lookup.py
stan-dev_pystan2/pystan/tests/test_lookup.py
import unittest import numpy as np import pystan class TestLookup(unittest.TestCase): def test_lookup(self): cbind = pystan.lookup("R.cbind")["StanFunction"] hstack = pystan.lookup("numpy.hstack")["StanFunction"] cbind_err = pystan.lookup("R.cbindd")["StanFunction"] cbind_2 = pystan.lookup("R.cbind", 1.0)["StanFunction"] hstack_2 = pystan.lookup("numpy.hstack", 1.0)["StanFunction"] for i in range(len(cbind)): self.assertEqual(cbind[i], "append_col") self.assertEqual(cbind[i], hstack[i]) self.assertEqual(cbind[i], cbind_err[i]) self.assertEqual(cbind[i], cbind_2[i]) self.assertEqual(cbind[i], hstack_2[i]) normal = pystan.lookup("scipy.stats.norm")["StanFunction"] for i in range(len(normal)): self.assertEqual("normal", normal[i][:6]) poisson = pystan.lookup("scipy.stats.poisson")["StanFunction"] for i in range(len(poisson)): self.assertEqual("poisson", poisson[i][:7]) wrongf = pystan.lookup("someverycrazyfunctionyouwontfind", 1.0) self.assertTrue(wrongf is None)
1,160
Python
.py
24
39.625
71
0.635242
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,019
test_basic_pars.py
stan-dev_pystan2/pystan/tests/test_basic_pars.py
import unittest from pystan.tests.helper import get_model import pystan class Test8Schools(unittest.TestCase): @classmethod def setUpClass(cls): schools_code = """\ data { int<lower=0> J; // number of schools real y[J]; // estimated treatment effects real<lower=0> sigma[J]; // s.e. of effect estimates } parameters { real mu; real<lower=0> tau; real eta[J]; } transformed parameters { real theta[J]; for (j in 1:J) theta[j] = mu + tau * eta[j]; } model { eta ~ normal(0, 1); y ~ normal(theta, sigma); }""" cls.schools_dat = {'J': 8, 'y': [28, 8, -3, 7, -1, 1, 18, 12], 'sigma': [15, 10, 16, 11, 9, 11, 10, 18]} cls.model = get_model("schools_model", schools_code) #cls.model pystan.StanModel(model_code=schools_code) def test_8schools_pars(self): model = self.model data = self.schools_dat pars = ['mu'] # list of parameters fit = model.sampling(data=data, pars=pars, iter=100) self.assertEqual(len(fit.sim['pars_oi']), len(fit.sim['dims_oi'])) self.assertEqual(len(fit.extract()), 2) self.assertIn('mu', fit.extract()) self.assertRaises(ValueError, fit.extract, 'theta') self.assertIsNotNone(fit.extract(permuted=False)) pars = ['eta'] fit = model.sampling(data=data, pars=pars, iter=100) self.assertEqual(len(fit.extract()), 2) self.assertIn('eta', fit.extract()) self.assertRaises(ValueError, fit.extract, 'theta') self.assertIsNotNone(fit.extract(permuted=False)) pars = ['mu', 'eta'] fit = model.sampling(data=data, pars=pars, iter=100) self.assertEqual(len(fit.extract()), 3) self.assertIn('mu', fit.extract()) self.assertIn('eta', fit.extract()) self.assertRaises(ValueError, fit.extract, 'theta') self.assertIsNotNone(fit.extract(permuted=False)) def test_8schools_pars_bare(self): model = self.model data = self.schools_dat pars = 'mu' # bare string fit = model.sampling(data=data, pars=pars, iter=100) self.assertEqual(len(fit.extract()), 2) self.assertIn('mu', fit.extract()) self.assertRaises(ValueError, fit.extract, 'theta') self.assertIsNotNone(fit.extract(permuted=False)) pars = 'eta' # bare string fit = model.sampling(data=data, pars=pars) self.assertEqual(len(fit.extract()), 2) self.assertIn('eta', fit.extract()) self.assertRaises(ValueError, fit.extract, 'theta') self.assertIsNotNone(fit.extract(permuted=False)) def test_8schools_bad_pars(self): model = self.model data = self.schools_dat pars = ['mu', 'missing'] # 'missing' is not in the model self.assertRaises(ValueError, model.sampling, data=data, pars=pars, iter=100) class TestParsLabels(unittest.TestCase): @classmethod def setUpClass(cls): model_code = '''\ parameters { real a; real b; real c; real d; } model { a ~ normal(0, 1); b ~ normal(-19, 1); c ~ normal(5, 1); d ~ normal(11, 1); } ''' cls.model = pystan.StanModel(model_code=model_code) def test_pars_single(self): '''Make sure labels are not getting switched''' fit = self.model.sampling(iter=100, chains=1, n_jobs=1, pars=['d']) self.assertGreater(fit.extract()['d'].mean(), 7) def test_pars_single_chains(self): '''Make sure labels are not getting switched''' fit = self.model.sampling(iter=100, chains=2, n_jobs=2, pars=['d']) self.assertGreater(fit.extract()['d'].mean(), 7) def test_pars_labels(self): '''Make sure labels are not getting switched''' fit = self.model.sampling(iter=100, chains=2, n_jobs=2, pars=['a', 'd']) extr = fit.extract() a = extr['a'].mean() d = extr['d'].mean() self.assertTrue('b' not in extr) self.assertTrue('c' not in extr) self.assertGreater(d, a)
4,498
Python
.py
110
30.227273
80
0.55436
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,020
test_optimizing_example.py
stan-dev_pystan2/pystan/tests/test_optimizing_example.py
import unittest import numpy as np import pystan class TestOptimizingExample(unittest.TestCase): """Test optimizing example from documentation""" @classmethod def setUpClass(cls): ocode = """ data { int<lower=1> N; real y[N]; } parameters { real mu; } model { y ~ normal(mu, 1); } """ cls.sm = pystan.StanModel(model_code=ocode) def test_optimizing(self): sm = self.sm np.random.seed(3) y2 = np.random.normal(size=20) op = sm.optimizing(data=dict(y=y2, N=len(y2))) self.assertAlmostEqual(op['mu'], np.mean(y2))
694
Python
.py
26
18.653846
54
0.553707
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,021
test_fixed_param.py
stan-dev_pystan2/pystan/tests/test_fixed_param.py
import unittest import numpy as np import pystan from pystan._compat import PY2 class TestFixedParam(unittest.TestCase): @classmethod def setUpClass(cls): model_code = ''' model { } generated quantities { real y; y = normal_rng(0, 1); } ''' cls.model = pystan.StanModel(model_code=model_code) def test_fixed_param(self): fit = self.model.sampling(algorithm='Fixed_param') self.assertEqual(fit.sim['iter'], 2000) self.assertEqual(fit.sim['pars_oi'], ['y', 'lp__']) self.assertEqual(len(fit.sim['samples']), 4) for sample_dict in fit.sim['samples']: assert -0.5 < np.mean(sample_dict['chains']['y']) < 0.5 assert 0.5 < np.std(sample_dict['chains']['y']) < 1.5
828
Python
.py
23
27.608696
67
0.579474
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,022
test_misc_args.py
stan-dev_pystan2/pystan/tests/test_misc_args.py
import unittest import numpy as np import pystan from pystan._compat import PY2 from pystan.tests.helper import get_model class TestArgs(unittest.TestCase): @classmethod def setUpClass(cls): model_code = 'parameters {real x;real y;real z;} model {x ~ normal(0,1);y ~ normal(0,1);z ~ normal(0,1);}' cls.model = get_model("standard_normals_model", model_code) #cls.model = pystan.StanModel(model_code=model_code) def test_control(self): model = self.model assertRaisesRegex = self.assertRaisesRegexp if PY2 else self.assertRaisesRegex with assertRaisesRegex(ValueError, '`control` must be a dictionary'): control_invalid = 3 model.sampling(control=control_invalid) with assertRaisesRegex(ValueError, '`control` contains unknown'): control_invalid = dict(foo=3) model.sampling(control=control_invalid) with assertRaisesRegex(ValueError, '`metric` must be one of'): model.sampling(control={'metric': 'lorem-ipsum'}) def test_print_summary(self): model = self.model fit = model.sampling(iter=100) summary_full = pystan.misc.stansummary(fit) summary_one_par1 = pystan.misc.stansummary(fit, pars='z') summary_one_par2 = pystan.misc.stansummary(fit, pars=['z']) summary_pars = pystan.misc.stansummary(fit, pars=['x', 'y']) self.assertNotEqual(summary_full, summary_one_par1) self.assertNotEqual(summary_full, summary_one_par2) self.assertNotEqual(summary_full, summary_pars) self.assertNotEqual(summary_one_par1, summary_pars) self.assertNotEqual(summary_one_par2, summary_pars) self.assertEqual(summary_one_par1, summary_one_par2)
1,769
Python
.py
35
42.542857
114
0.686377
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,023
test_stan_file_io.py
stan-dev_pystan2/pystan/tests/test_stan_file_io.py
from __future__ import absolute_import, division, print_function, unicode_literals import unittest import io import os import tempfile import numpy as np from pystan import stan, stanc class TestStanFileIO(unittest.TestCase): def test_stan_model_from_file(self): bernoulli_model_code = """ data { int<lower=0> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { for (n in 1:N) y[n] ~ bernoulli(theta); } """ bernoulli_data = {'N': 10, 'y': [0, 1, 0, 0, 0, 0, 0, 0, 0, 1]} temp_dir = tempfile.mkdtemp() temp_fn = os.path.join(temp_dir, 'modelcode.stan') with io.open(temp_fn, 'wt') as outfile: outfile.write(bernoulli_model_code) code = stanc(file=temp_fn)['model_code'] fit = stan(model_code=code, data=bernoulli_data) extr = fit.extract(permuted=True) assert -7.9 < np.mean(extr['lp__']) < -7.0 assert 0.1 < np.mean(extr['theta']) < 0.4 assert 0.01 < np.var(extr['theta']) < 0.02 # permuted=False extr = fit.extract(permuted=False) assert extr.shape == (1000, 4, 2) assert 0.1 < np.mean(extr[:, 0, 0]) < 0.4 # permuted=True extr = fit.extract('lp__', permuted=True) assert -7.9 < np.mean(extr['lp__']) < -7.0 extr = fit.extract('theta', permuted=True) assert 0.1 < np.mean(extr['theta']) < 0.4 assert 0.01 < np.var(extr['theta']) < 0.02 extr = fit.extract('theta', permuted=False) assert extr['theta'].shape == (1000, 4) assert 0.1 < np.mean(extr['theta'][:, 0]) < 0.4 fit = stan(file=temp_fn, data=bernoulli_data) extr = fit.extract(permuted=True) assert -7.9 < np.mean(extr['lp__']) < -7.0 assert 0.1 < np.mean(extr['theta']) < 0.4 assert 0.01 < np.var(extr['theta']) < 0.02 # permuted=False extr = fit.extract(permuted=False) assert extr.shape == (1000, 4, 2) assert 0.1 < np.mean(extr[:, 0, 0]) < 0.4 # permuted=True extr = fit.extract('lp__', permuted=True) assert -7.9 < np.mean(extr['lp__']) < -7.0 extr = fit.extract('theta', permuted=True) assert 0.1 < np.mean(extr['theta']) < 0.4 assert 0.01 < np.var(extr['theta']) < 0.02 extr = fit.extract('theta', permuted=False) assert extr['theta'].shape == (1000, 4) assert 0.1 < np.mean(extr['theta'][:, 0]) < 0.4 os.remove(temp_fn)
2,640
Python
.py
65
31.584615
82
0.544709
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,024
test_rstan_testoptim.py
stan-dev_pystan2/pystan/tests/test_rstan_testoptim.py
import logging import unittest import numpy as np import pystan from pystan.tests.helper import get_model class TestOptim(unittest.TestCase): @classmethod def setUpClass(cls): stdnorm = """ data { int N; real y[N]; } parameters { real mu; real<lower=0> sigma; } model { y ~ normal(mu, sigma); } """ N = 30 np.random.seed(1) y = np.random.normal(size=N) cls.dat = {'N': N, 'y': y} cls.sm = get_model("normal_mu_sigma_model", stdnorm, verbose=True) #cls.sm = pystan.StanModel(model_code=stdnorm, verbose=True) def test_optim_stdnorm(self): optim = self.sm.optimizing(data=self.dat) self.assertTrue(-1 < optim['mu'] < 1) self.assertTrue(0 < optim['sigma'] < 2) def test_optim_stdnorm_from_file(self): sm = self.sm dat = self.dat dump_fn = 'optim_data.Rdump' pystan.misc.stan_rdump(dat, dump_fn) data_from_file = pystan.misc.read_rdump(dump_fn) optim = sm.optimizing(data=data_from_file, algorithm='BFGS') def test_optim_stdnorm_bfgs(self): sm = self.sm dat = self.dat optim = sm.optimizing(data=dat, algorithm='BFGS') self.assertTrue(-1 < optim['mu'] < 1) self.assertTrue(0 < optim['sigma'] < 2) optim2 = sm.optimizing(data=dat, algorithm='BFGS', sample_file='opt.csv', init_alpha=0.02, tol_obj=1e-7, tol_grad=1e-9, tol_param=1e-7) self.assertTrue(-1 < optim['mu'] < 1) self.assertTrue(0 < optim['sigma'] < 2) print(optim2) def test_optim_stdnorm_lbfgs(self): sm = self.sm optim = sm.optimizing(data=self.dat, algorithm='LBFGS', seed=5, init_alpha=0.02, tol_obj=1e-7, tol_grad=1e-9, tol_param=1e-7) self.assertTrue(-3 < optim['mu'] < 3) self.assertTrue(0 < optim['sigma'] < 5) optim = sm.optimizing(data=self.dat, algorithm='LBFGS', seed=5, init_alpha=0.02, tol_obj=1e-7, tol_grad=1e-9, tol_param=1e-7, as_vector=False) self.assertTrue(-3 < optim['par']['mu'] < 3) self.assertTrue(0 < optim['par']['sigma'] < 5) optim = sm.optimizing(data=self.dat, algorithm='LBFGS', seed=5, history_size=10) self.assertTrue(-3 < optim['mu'] < 3) self.assertTrue(0 < optim['sigma'] < 5)
2,501
Python
.py
63
30.238095
91
0.564483
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,025
helper.py
stan-dev_pystan2/pystan/tests/helper.py
import os import pickle import bz2 import pystan from pystan._compat import PY2 def get_bz2_open(): if PY2: bz2_open = bz2.BZ2File else: bz2_open = bz2.open return bz2_open def load_model(path): _, ext = os.path.splitext(path) if ext != '.bz2': path = path + ".bz2" bz2_open = get_bz2_open() with bz2_open(path, "rb") as f: pickled_model = f.read() stan_model = pickle.loads(pickled_model) return stan_model def save_model(stan_model, path): pickled_model = pickle.dumps(stan_model, protocol=pickle.HIGHEST_PROTOCOL) _, ext = os.path.splitext(path) if ext != '.bz2': path = path + ".bz2" bz2_open = get_bz2_open() with bz2_open(path, "wb") as f: f.write(pickled_model) def get_model(filename, model_code, **kwargs): root = os.path.join(os.path.dirname(__file__), 'cached_models') # py27 does not have 'exist_ok' try: os.makedirs(root) except OSError: pass path = os.path.join(root, filename) # use .bz2 compression _, ext = os.path.splitext(path) if ext != '.bz2': path = path + ".bz2" if os.path.exists(path): stan_model = load_model(path) else: stan_model = pystan.StanModel(model_code=model_code, **kwargs) save_model(stan_model, path) return stan_model
1,359
Python
.py
46
24.152174
78
0.623565
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,026
test_vb.py
stan-dev_pystan2/pystan/tests/test_vb.py
import os import unittest import tempfile import pystan from pystan.tests.helper import get_model class TestNormalVB(unittest.TestCase): seed = 1 @classmethod def setUpClass(cls): model_code = 'parameters {real x;real y;real z;} model {x ~ normal(0,1);y ~ normal(0,1);z ~ normal(0,1);}' cls.model = get_model("standard_normals_model", model_code) #cls.model = pystan.StanModel(model_code=model_code) def test_vb_default(self): vbf1 = self.model.vb(seed=self.seed) self.assertIsNotNone(vbf1) csv_fn = vbf1['args']['sample_file'].decode('ascii') with open(csv_fn) as f: csv_sample1 = f.readlines()[10] # vb run with same seed should yield identical results vbf2 = self.model.vb(seed=self.seed) self.assertIsNotNone(vbf2) csv_fn = vbf2['args']['sample_file'].decode('ascii') with open(csv_fn) as f: csv_sample2 = f.readlines()[10] self.assertEqual(csv_sample1, csv_sample2) def test_vb_fullrank(self): vbf = self.model.vb(algorithm='fullrank', seed=self.seed) self.assertIsNotNone(vbf) def test_vb_sample_file(self): sample_file = os.path.join(tempfile.mkdtemp(), 'vb-results.csv') vbf = self.model.vb(algorithm='fullrank', sample_file=sample_file, seed=self.seed) self.assertIsNotNone(vbf) self.assertEqual(vbf['args']['sample_file'].decode('utf-8'), sample_file) self.assertTrue(os.path.exists(sample_file)) def test_vb_diagnostic_file(self): sample_file = os.path.join(tempfile.mkdtemp(), 'vb-results.csv') diag_file = os.path.join(tempfile.mkdtemp(), 'vb-diag.csv') vbf = self.model.vb(algorithm='fullrank', sample_file=sample_file, diagnostic_file=diag_file, seed=self.seed) self.assertIsNotNone(vbf) self.assertEqual(vbf['args']['diagnostic_file'].decode('utf-8'), diag_file) self.assertTrue(os.path.exists(diag_file)) def test_vb_pars(self): vbfit = self.model.vb(algorithm='fullrank', pars=['y'], seed=self.seed) vbfit2 = self.model.vb(algorithm='fullrank', pars='z', seed=self.seed) self.assertIsNotNone(vbfit) self.assertIsNotNone(vbfit2) self.assertEqual(vbfit['mean_par_names'], ['y']) self.assertEqual(vbfit2['mean_par_names'], ['z'])
2,367
Python
.py
48
41.604167
117
0.656994
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,027
test_stanc.py
stan-dev_pystan2/pystan/tests/test_stanc.py
import unittest import os from pystan import stanc, StanModel from pystan._compat import PY2 class TestStanc(unittest.TestCase): def test_stanc(self): model_code = 'parameters {real y;} model {y ~ normal(0,1);}' result = stanc(model_code=model_code) desired = sorted({"status", "model_cppname", "cppcode", "model_name", "model_code", "include_paths"}) self.assertEqual(sorted(result.keys()), desired) self.assertTrue(result['cppcode'].startswith("// Code generated by Stan ")) self.assertEqual(result['status'], 0) def test_stanc_exception(self): model_code = 'parameters {real z;} model {z ~ no_such_distribution();}' assertRaisesRegex = self.assertRaisesRegexp if PY2 else self.assertRaisesRegex # distribution not found error with assertRaisesRegex(ValueError, r'Probability function must end in _lpdf or _lpmf\. Found'): stanc(model_code=model_code) with assertRaisesRegex(ValueError, r'Probability function must end in _lpdf or _lpmf\. Found'): StanModel(model_code=model_code) def test_stanc_exception_semicolon(self): model_code = """ parameters { real z real y } model { z ~ normal(0, 1); y ~ normal(0, 1);} """ assertRaisesRegex = self.assertRaisesRegexp if PY2 else self.assertRaisesRegex with assertRaisesRegex(ValueError, 'Failed to parse'): stanc(model_code=model_code) with assertRaisesRegex(ValueError, 'Failed to parse'): StanModel(model_code=model_code) def test_stanc_include(self): model_code = 'parameters {\n#include external1.stan\n} model {\ny ~ normal(0,1);}' testdata_path = os.path.join(os.path.dirname(__file__), 'data', "") result = stanc(model_code=model_code, include_paths=[testdata_path]) desired = sorted({"status", "model_cppname", "cppcode", "model_name", "model_code", "include_paths"}) self.assertEqual(sorted(result.keys()), desired) self.assertEqual(result['status'], 0) def test_stanc_2_includes(self): model_code = 'parameters {\n#include external1.stan\n#include external2.stan\n} model {\ny ~ normal(0,1);\nz ~ normal(0,1);}' testdata_path = os.path.join(os.path.dirname(__file__), 'data', "") result = stanc(model_code=model_code, include_paths=[testdata_path]) desired = sorted({"status", "model_cppname", "cppcode", "model_name", "model_code", "include_paths"}) self.assertEqual(sorted(result.keys()), desired) self.assertEqual(result['status'], 0)
2,667
Python
.py
49
45.836735
133
0.647893
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,028
test_pickle.py
stan-dev_pystan2/pystan/tests/test_pickle.py
import io import os import pickle import sys import tempfile import unittest import numpy as np import pystan from pystan.tests.helper import get_model from pystan.experimental import unpickle_fit class TestPickle(unittest.TestCase): @classmethod def setUpClass(cls): cls.pickle_file = os.path.join(tempfile.mkdtemp(), 'stanmodel.pkl') cls.model_code = 'parameters {real y;} model {y ~ normal(0,1);}' def test_pickle_model(self): pickle_file = self.pickle_file model_code = self.model_code m = pystan.StanModel(model_code=model_code, model_name="normal2") module_name = m.module.__name__ module_filename = m.module.__file__ with open(pickle_file, 'wb') as f: pickle.dump(m, f) del m del sys.modules[module_name] with open(pickle_file, 'rb') as f: m = pickle.load(f) self.assertTrue(m.model_name.startswith("normal2")) self.assertIsNotNone(m.module) if not sys.platform.startswith('win'): # will fail on Windows self.assertNotEqual(module_filename, m.module.__file__) fit = m.sampling() y = fit.extract()['y'] assert len(y) == 4000 def test_pickle_fit(self): model_code = 'parameters {real y;} model {y ~ normal(0,1);}' sm = pystan.StanModel(model_code=model_code, model_name="normal1") # additional error checking fit = sm.sampling(iter=100) y = fit.extract()['y'].copy() self.assertIsNotNone(y) # pickle pickled_model = pickle.dumps(sm) module_name = sm.module.__name__ del sm pickled_fit = pickle.dumps(fit) del fit # unload module if module_name in sys.modules: del(sys.modules[module_name]) # load from file sm_from_pickle = pickle.loads(pickled_model) fit_from_pickle = pickle.loads(pickled_fit) self.assertIsNotNone(fit_from_pickle) self.assertTrue((fit_from_pickle.extract()['y'] == y).all()) def test_pickle_model_and_reload(self): pickle_file = self.pickle_file pickle_file2 = os.path.join(tempfile.mkdtemp(), 'stanmodel.pkl') model_code = self.model_code model = pystan.StanModel(model_code=model_code, model_name="normal1") with open(pickle_file, 'wb') as f: pickle.dump(model, f) with open(pickle_file2, 'wb') as f: pickle.dump(model, f) del model with open(pickle_file, 'rb') as f: model_from_pickle = pickle.load(f) self.assertIsNotNone(model_from_pickle.sampling(iter=100).extract()) with open(pickle_file2, 'rb') as f: model_from_pickle = pickle.load(f) self.assertIsNotNone(model_from_pickle.sampling(iter=100).extract()) def test_model_unique_names(self): model_code = self.model_code model1 = pystan.StanModel(model_code=model_code, model_name="normal1") model2 = pystan.StanModel(model_code=model_code, model_name="normal1") self.assertNotEqual(model1.module_name, model2.module_name) class TestPickleFitOnly(unittest.TestCase): @classmethod def setUpClass(cls): model_code = 'parameters {real y;} model {y ~ normal(0,1);}' model = get_model("standard_normal_model", model_code, model_name="normal1", verbose=True, obfuscate_model_name=False) fit = model.sampling() tempfolder = tempfile.mkdtemp() cls.pickle_fit = os.path.join(tempfolder, 'stanfit.pkl') cls.pickle_extract = os.path.join(tempfolder, 'stanextract.pkl') with io.open(cls.pickle_fit, mode="wb") as f: pickle.dump(fit, f) with io.open(cls.pickle_extract, mode="wb") as f: pickle.dump(fit.extract(), f) module_name = model.module.__name__ del model del sys.modules[module_name] @unittest.expectedFailure def test_unpickle_fit_fail(self): with io.open(self.pickle_file, "rb") as f: pickle.load(f) def test_load_fit(self): fit, model = unpickle_fit(self.pickle_fit, open_func=io.open, open_kwargs={"mode" : "rb"}, return_model=True) self.assertIsNotNone(fit) self.assertIsNotNone(model) self.assertIsNotNone(fit.extract()) self.assertTrue("y" in fit.extract()) with io.open(self.pickle_extract, "rb") as f: extract = pickle.load(f) self.assertTrue(np.all(fit.extract()["y"] == extract["y"]))
4,607
Python
.py
108
33.935185
117
0.625642
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,029
test_rstan_getting_started.py
stan-dev_pystan2/pystan/tests/test_rstan_getting_started.py
import tempfile import unittest import numpy as np import pystan from pystan.tests.helper import get_model def validate_data(fit): la = fit.extract(permuted=True) # return a dictionary of arrays mu, tau, eta, theta = la['mu'], la['tau'], la['eta'], la['theta'] np.testing.assert_equal(mu.shape, (2000,)) np.testing.assert_equal(tau.shape, (2000,)) np.testing.assert_equal(eta.shape, (2000, 8)) np.testing.assert_equal(theta.shape, (2000, 8)) assert -1 < np.mean(mu) < 17 assert 0 < np.mean(tau) < 17 assert all(-3 < np.mean(eta, axis=0)) assert all(np.mean(eta, axis=0) < 3) assert all(-15 < np.mean(theta, axis=0)) assert all(np.mean(theta, axis=0) < 30) # return an array of three dimensions: iterations, chains, parameters a = fit.extract(permuted=False) np.testing.assert_equal(a.shape, (500, 4, 19)) class TestRStanGettingStarted(unittest.TestCase): @classmethod def setUpClass(cls): cls.schools_code = schools_code = """ data { int<lower=0> J; // number of schools real y[J]; // estimated treatment effects real<lower=0> sigma[J]; // s.e. of effect estimates } parameters { real mu; real<lower=0> tau; real eta[J]; } transformed parameters { real theta[J]; for (j in 1:J) theta[j] = mu + tau * eta[j]; } model { eta ~ normal(0, 1); y ~ normal(theta, sigma); } """ cls.schools_dat = schools_dat = { 'J': 8, 'y': [28, 8, -3, 7, -1, 1, 18, 12], 'sigma': [15, 10, 16, 11, 9, 11, 10, 18] } cls.sm = sm = get_model("schools_model", schools_code) #cls.sm = sm = pystan.StanModel(model_code=schools_code) cls.fit = sm.sampling(data=schools_dat, iter=1000, chains=4) def test_stan(self): fit = self.fit validate_data(fit) def test_stan_file(self): schools_code = self.schools_code schools_dat = self.schools_dat with tempfile.NamedTemporaryFile(delete=False) as f: f.write(schools_code.encode('utf-8')) fit = pystan.stan(file=f.name, data=schools_dat, iter=1000, chains=4) validate_data(fit) def test_stan_reuse_fit(self): fit1 = self.fit schools_dat = self.schools_dat fit = pystan.stan(fit=fit1, data=schools_dat, iter=1000, chains=4) validate_data(fit) def test_sampling_parallel(self): sm = self.sm schools_dat = self.schools_dat fit = sm.sampling(data=schools_dat, iter=1000, chains=4, n_jobs=-1) validate_data(fit) # n_jobs specified explicitly fit = sm.sampling(data=schools_dat, iter=1000, chains=4, n_jobs=4) validate_data(fit)
2,883
Python
.py
76
29.776316
77
0.589394
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,030
test_rstan_stanfit.py
stan-dev_pystan2/pystan/tests/test_rstan_stanfit.py
import unittest import numpy as np from pystan import StanModel, stan from pystan._compat import PY2 from pystan.tests.helper import get_model # REF: rstan/tests/unitTests/runit.test.stanfit.R class TestStanfit(unittest.TestCase): def test_init_zero_exception_inf_grad(self): code = """ parameters { real x; } model { target += 1 / log(x); } """ sm = StanModel(model_code=code) with self.assertRaises(RuntimeError): sm.sampling(init='0', iter=1, chains=1, control={"adapt_engaged" : False}) def test_grad_log(self): y = np.array([0.70, -0.16, 0.77, -1.37, -1.99, 1.35, 0.08, 0.02, -1.48, -0.08, 0.34, 0.03, -0.42, 0.87, -1.36, 1.43, 0.80, -0.48, -1.61, -1.27]) code = ''' data { int N; real y[N]; } parameters { real mu; real<lower=0> sigma; } model { y ~ normal(mu, sigma); }''' def log_prob_fun(mu, log_sigma, adjust=True): sigma = np.exp(log_sigma) lp = -1 * np.sum((y - mu)**2) / (2 * (sigma**2)) - len(y) * np.log(sigma) if adjust: lp = lp + np.log(sigma) return lp def log_prob_grad_fun(mu, log_sigma, adjust=True): sigma = np.exp(log_sigma) g_lsigma = np.sum((y - mu)**2) * sigma**(-2) - len(y) if adjust: g_lsigma = g_lsigma + 1 g_mu = np.sum(y - mu) * sigma**(-2) return (g_mu, g_lsigma) sm = get_model("normal_mu_sigma_model", code) sf = sm.sampling(data=dict(y=y, N=20), iter=200) mu = 0.1 sigma = 2 self.assertEqual(sf.log_prob(sf.unconstrain_pars(dict(mu=mu, sigma=sigma))), log_prob_fun(mu, np.log(sigma))) self.assertEqual(sf.log_prob(sf.unconstrain_pars(dict(mu=mu, sigma=sigma)), False), log_prob_fun(mu, np.log(sigma), adjust=False)) g1 = sf.grad_log_prob(sf.unconstrain_pars(dict(mu=mu, sigma=sigma)), False) np.testing.assert_allclose(g1, log_prob_grad_fun(mu, np.log(sigma), adjust=False)) def test_specify_args(self): y = (0.70, -0.16, 0.77, -1.37, -1.99, 1.35, 0.08, 0.02, -1.48, -0.08, 0.34, 0.03, -0.42, 0.87, -1.36, 1.43, 0.80, -0.48, -1.61, -1.27) code = """ data { int N; real y[N]; } parameters { real mu; real<lower=0> sigma; } model { y ~ normal(mu, sigma); }""" stepsize0 = 0.15 sm = get_model("normal_mu_sigma_model", code) sf = sm.sampling(data=dict(y=y, N=20), iter=200, control=dict(adapt_engaged=False, stepsize=stepsize0)) self.assertEqual(sf.get_sampler_params()[0]['stepsize__'][0], stepsize0) sf2 = stan(fit=sf, iter=20, algorithm='HMC', data=dict(y=y, N=20), control=dict(adapt_engaged=False, stepsize=stepsize0)) self.assertEqual(sf2.get_sampler_params()[0]['stepsize__'][0], stepsize0) sf3 = stan(fit=sf, iter=1, data=dict(y=y, N=20), init=0, chains=1, control={"adapt_engaged" : False}) i_u = sf3.unconstrain_pars(sf3.get_inits()[0]) np.testing.assert_equal(i_u, [0, 0])
3,510
Python
.py
85
29.964706
109
0.505858
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,031
test_unconstrain_pars.py
stan-dev_pystan2/pystan/tests/test_unconstrain_pars.py
import unittest import pystan from pystan._compat import PY2 class TestUnconstrainPars(unittest.TestCase): @classmethod def setUpClass(cls): cls.model = pystan.StanModel(model_code="parameters { real x; } model { }") def test_unconstrain_pars(self): data, seed = {}, 1 fit = self.model.fit_class(data, seed) assertRaisesRegex = self.assertRaisesRegexp if PY2 else self.assertRaisesRegex with assertRaisesRegex(RuntimeError, 'Variable x missing'): fit.unconstrain_pars({})
541
Python
.py
13
35.307692
86
0.705545
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,032
enum.py
stan-dev_pystan2/pystan/external/enum/enum.py
"""Python Enumerations""" import sys as _sys __all__ = ['Enum', 'IntEnum', 'unique'] pyver = float('%s.%s' % _sys.version_info[:2]) try: any except NameError: def any(iterable): for element in iterable: if element: return True return False class _RouteClassAttributeToGetattr(object): """Route attribute access on a class to __getattr__. This is a descriptor, used to define attributes that act differently when accessed through an instance and through a class. Instance access remains normal, but access to an attribute through a class will be routed to the class's __getattr__ method; this is done by raising AttributeError. """ def __init__(self, fget=None): self.fget = fget def __get__(self, instance, ownerclass=None): if instance is None: raise AttributeError() return self.fget(instance) def __set__(self, instance, value): raise AttributeError("can't set attribute") def __delete__(self, instance): raise AttributeError("can't delete attribute") def _is_descriptor(obj): """Returns True if obj is a descriptor, False otherwise.""" return ( hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__')) def _is_dunder(name): """Returns True if a __dunder__ name, False otherwise.""" return (name[:2] == name[-2:] == '__' and name[2:3] != '_' and name[-3:-2] != '_' and len(name) > 4) def _is_sunder(name): """Returns True if a _sunder_ name, False otherwise.""" return (name[0] == name[-1] == '_' and name[1:2] != '_' and name[-2:-1] != '_' and len(name) > 2) def _make_class_unpicklable(cls): """Make the given class un-picklable.""" def _break_on_call_reduce(self): raise TypeError('%r cannot be pickled' % self) cls.__reduce__ = _break_on_call_reduce cls.__module__ = '<unknown>' class _EnumDict(dict): """Track enum member order and ensure member names are not reused. EnumMeta will use the names found in self._member_names as the enumeration member names. """ def __init__(self): super(_EnumDict, self).__init__() self._member_names = [] def __setitem__(self, key, value): """Changes anything not dundered or not a descriptor. If a descriptor is added with the same name as an enum member, the name is removed from _member_names (this may leave a hole in the numerical sequence of values). If an enum member name is used twice, an error is raised; duplicate values are not checked for. Single underscore (sunder) names are reserved. Note: in 3.x __order__ is simply discarded as a not necessary piece leftover from 2.x """ if pyver >= 3.0 and key == '__order__': return if _is_sunder(key): raise ValueError('_names_ are reserved for future Enum use') elif _is_dunder(key): pass elif key in self._member_names: # descriptor overwriting an enum? raise TypeError('Attempted to reuse key: %r' % key) elif not _is_descriptor(value): if key in self: # enum overwriting a descriptor? raise TypeError('Key already defined as: %r' % self[key]) self._member_names.append(key) super(_EnumDict, self).__setitem__(key, value) # Dummy value for Enum as EnumMeta explicity checks for it, but of course until # EnumMeta finishes running the first time the Enum class doesn't exist. This # is also why there are checks in EnumMeta like `if Enum is not None` Enum = None class EnumMeta(type): """Metaclass for Enum""" @classmethod def __prepare__(metacls, cls, bases): return _EnumDict() def __new__(metacls, cls, bases, classdict): # an Enum class is final once enumeration items have been defined; it # cannot be mixed with other types (int, float, etc.) if it has an # inherited __new__ unless a new __new__ is defined (or the resulting # class will fail). if type(classdict) is dict: original_dict = classdict classdict = _EnumDict() for k, v in original_dict.items(): classdict[k] = v member_type, first_enum = metacls._get_mixins_(bases) #if member_type is object: # use_args = False #else: # use_args = True __new__, save_new, use_args = metacls._find_new_(classdict, member_type, first_enum) # save enum items into separate mapping so they don't get baked into # the new class members = dict((k, classdict[k]) for k in classdict._member_names) for name in classdict._member_names: del classdict[name] # py2 support for definition order __order__ = classdict.get('__order__') if __order__ is None: __order__ = classdict._member_names if pyver < 3.0: order_specified = False else: order_specified = True else: del classdict['__order__'] order_specified = True if pyver < 3.0: __order__ = __order__.replace(',', ' ').split() aliases = [name for name in members if name not in __order__] __order__ += aliases # check for illegal enum names (any others?) invalid_names = set(members) & set(['mro']) if invalid_names: raise ValueError('Invalid enum member name(s): %s' % ( ', '.join(invalid_names), )) # create our new Enum type enum_class = super(EnumMeta, metacls).__new__(metacls, cls, bases, classdict) enum_class._member_names_ = [] # names in random order enum_class._member_map_ = {} # name->value map enum_class._member_type_ = member_type # Reverse value->name map for hashable values. enum_class._value2member_map_ = {} # check for a __getnewargs__, and if not present sabotage # pickling, since it won't work anyway if (member_type is not object and member_type.__dict__.get('__getnewargs__') is None ): _make_class_unpicklable(enum_class) # instantiate them, checking for duplicates as we go # we instantiate first instead of checking for duplicates first in case # a custom __new__ is doing something funky with the values -- such as # auto-numbering ;) if __new__ is None: __new__ = enum_class.__new__ for member_name in __order__: value = members[member_name] if not isinstance(value, tuple): args = (value, ) else: args = value if member_type is tuple: # special case for tuple enums args = (args, ) # wrap it one more time if not use_args or not args: enum_member = __new__(enum_class) if not hasattr(enum_member, '_value_'): enum_member._value_ = value else: enum_member = __new__(enum_class, *args) if not hasattr(enum_member, '_value_'): enum_member._value_ = member_type(*args) value = enum_member._value_ enum_member._name_ = member_name enum_member.__objclass__ = enum_class enum_member.__init__(*args) # If another member with the same value was already defined, the # new member becomes an alias to the existing one. for name, canonical_member in enum_class._member_map_.items(): if canonical_member.value == enum_member._value_: enum_member = canonical_member break else: # Aliases don't appear in member names (only in __members__). enum_class._member_names_.append(member_name) enum_class._member_map_[member_name] = enum_member try: # This may fail if value is not hashable. We can't add the value # to the map, and by-value lookups for this value will be # linear. enum_class._value2member_map_[value] = enum_member except TypeError: pass # in Python2.x we cannot know definition order, so go with value order # unless __order__ was specified in the class definition if not order_specified: enum_class._member_names_ = [ e[0] for e in sorted( [(name, enum_class._member_map_[name]) for name in enum_class._member_names_], key=lambda t: t[1]._value_ )] # double check that repr and friends are not the mixin's or various # things break (such as pickle) if Enum is not None: setattr(enum_class, '__getnewargs__', Enum.__getnewargs__) for name in ('__repr__', '__str__', '__format__'): class_method = getattr(enum_class, name) obj_method = getattr(member_type, name, None) enum_method = getattr(first_enum, name, None) if obj_method is not None and obj_method is class_method: setattr(enum_class, name, enum_method) # method resolution and int's are not playing nice # Python's less than 2.6 use __cmp__ if pyver < 2.6: if issubclass(enum_class, int): setattr(enum_class, '__cmp__', getattr(int, '__cmp__')) elif pyver < 3.0: if issubclass(enum_class, int): for method in ( '__le__', '__lt__', '__gt__', '__ge__', '__eq__', '__ne__', '__hash__', ): setattr(enum_class, method, getattr(int, method)) # replace any other __new__ with our own (as long as Enum is not None, # anyway) -- again, this is to support pickle if Enum is not None: # if the user defined their own __new__, save it before it gets # clobbered in case they subclass later if save_new: setattr(enum_class, '__member_new__', enum_class.__dict__['__new__']) setattr(enum_class, '__new__', Enum.__dict__['__new__']) return enum_class def __call__(cls, value, names=None, module=None, type=None): """Either returns an existing member, or creates a new enum class. This method is used both when an enum class is given a value to match to an enumeration member (i.e. Color(3)) and for the functional API (i.e. Color = Enum('Color', names='red green blue')). When used for the functional API: `module`, if set, will be stored in the new class' __module__ attribute; `type`, if set, will be mixed in as the first base class. Note: if `module` is not set this routine will attempt to discover the calling module by walking the frame stack; if this is unsuccessful the resulting class will not be pickleable. """ if names is None: # simple value lookup return cls.__new__(cls, value) # otherwise, functional API: we're creating a new Enum type return cls._create_(value, names, module=module, type=type) def __contains__(cls, member): return isinstance(member, cls) and member.name in cls._member_map_ def __delattr__(cls, attr): # nicer error message when someone tries to delete an attribute # (see issue19025). if attr in cls._member_map_: raise AttributeError( "%s: cannot delete Enum member." % cls.__name__) super(EnumMeta, cls).__delattr__(attr) def __dir__(self): return (['__class__', '__doc__', '__members__', '__module__'] + self._member_names_) @property def __members__(cls): """Returns a mapping of member name->value. This mapping lists all enum members, including aliases. Note that this is a copy of the internal mapping. """ return cls._member_map_.copy() def __getattr__(cls, name): """Return the enum member matching `name` We use __getattr__ instead of descriptors or inserting into the enum class' __dict__ in order to support `name` and `value` being both properties for enum members (which live in the class' __dict__) and enum members themselves. """ if _is_dunder(name): raise AttributeError(name) try: return cls._member_map_[name] except KeyError: raise AttributeError(name) def __getitem__(cls, name): return cls._member_map_[name] def __iter__(cls): return (cls._member_map_[name] for name in cls._member_names_) def __reversed__(cls): return (cls._member_map_[name] for name in reversed(cls._member_names_)) def __len__(cls): return len(cls._member_names_) def __repr__(cls): return "<enum %r>" % cls.__name__ def __setattr__(cls, name, value): """Block attempts to reassign Enum members. A simple assignment to the class namespace only changes one of the several possible ways to get an Enum member from the Enum class, resulting in an inconsistent Enumeration. """ member_map = cls.__dict__.get('_member_map_', {}) if name in member_map: raise AttributeError('Cannot reassign members.') super(EnumMeta, cls).__setattr__(name, value) def _create_(cls, class_name, names=None, module=None, type=None): """Convenience method to create a new Enum class. `names` can be: * A string containing member names, separated either with spaces or commas. Values are auto-numbered from 1. * An iterable of member names. Values are auto-numbered from 1. * An iterable of (member name, value) pairs. * A mapping of member name -> value. """ metacls = cls.__class__ if type is None: bases = (cls, ) else: bases = (type, cls) classdict = metacls.__prepare__(class_name, bases) __order__ = [] # special processing needed for names? if isinstance(names, str): names = names.replace(',', ' ').split() if isinstance(names, (tuple, list)) and isinstance(names[0], str): names = [(e, i+1) for (i, e) in enumerate(names)] # Here, names is either an iterable of (name, value) or a mapping. for item in names: if isinstance(item, str): member_name, member_value = item, names[item] else: member_name, member_value = item classdict[member_name] = member_value __order__.append(member_name) # only set __order__ in classdict if name/value was not from a mapping if not isinstance(item, str): classdict['__order__'] = ' '.join(__order__) enum_class = metacls.__new__(metacls, class_name, bases, classdict) # TODO: replace the frame hack if a blessed way to know the calling # module is ever developed if module is None: try: module = _sys._getframe(2).f_globals['__name__'] except (AttributeError, ValueError): pass if module is None: _make_class_unpicklable(enum_class) else: enum_class.__module__ = module return enum_class @staticmethod def _get_mixins_(bases): """Returns the type for creating enum members, and the first inherited enum class. bases: the tuple of bases that was given to __new__ """ if not bases or Enum is None: return object, Enum # double check that we are not subclassing a class with existing # enumeration members; while we're at it, see if any other data # type has been mixed in so we can use the correct __new__ member_type = first_enum = None for base in bases: if (base is not Enum and issubclass(base, Enum) and base._member_names_): raise TypeError("Cannot extend enumerations") # base is now the last base in bases if not issubclass(base, Enum): raise TypeError("new enumerations must be created as " "`ClassName([mixin_type,] enum_type)`") # get correct mix-in type (either mix-in type of Enum subclass, or # first base if last base is Enum) if not issubclass(bases[0], Enum): member_type = bases[0] # first data type first_enum = bases[-1] # enum type else: for base in bases[0].__mro__: # most common: (IntEnum, int, Enum, object) # possible: (<Enum 'AutoIntEnum'>, <Enum 'IntEnum'>, # <class 'int'>, <Enum 'Enum'>, # <class 'object'>) if issubclass(base, Enum): if first_enum is None: first_enum = base else: if member_type is None: member_type = base return member_type, first_enum if pyver < 3.0: @staticmethod def _find_new_(classdict, member_type, first_enum): """Returns the __new__ to be used for creating the enum members. classdict: the class dictionary given to __new__ member_type: the data type whose __new__ will be used by default first_enum: enumeration to check for an overriding __new__ """ # now find the correct __new__, checking to see of one was defined # by the user; also check earlier enum classes in case a __new__ was # saved as __member_new__ __new__ = classdict.get('__new__', None) if __new__: return None, True, True # __new__, save_new, use_args N__new__ = getattr(None, '__new__') O__new__ = getattr(object, '__new__') if Enum is None: E__new__ = N__new__ else: E__new__ = Enum.__dict__['__new__'] # check all possibles for __member_new__ before falling back to # __new__ for method in ('__member_new__', '__new__'): for possible in (member_type, first_enum): try: target = possible.__dict__[method] except (AttributeError, KeyError): target = getattr(possible, method, None) if target not in [ None, N__new__, O__new__, E__new__, ]: if method == '__member_new__': classdict['__new__'] = target return None, False, True if isinstance(target, staticmethod): target = target.__get__(member_type) __new__ = target break if __new__ is not None: break else: __new__ = object.__new__ # if a non-object.__new__ is used then whatever value/tuple was # assigned to the enum member name will be passed to __new__ and to the # new enum member's __init__ if __new__ is object.__new__: use_args = False else: use_args = True return __new__, False, use_args else: @staticmethod def _find_new_(classdict, member_type, first_enum): """Returns the __new__ to be used for creating the enum members. classdict: the class dictionary given to __new__ member_type: the data type whose __new__ will be used by default first_enum: enumeration to check for an overriding __new__ """ # now find the correct __new__, checking to see of one was defined # by the user; also check earlier enum classes in case a __new__ was # saved as __member_new__ __new__ = classdict.get('__new__', None) # should __new__ be saved as __member_new__ later? save_new = __new__ is not None if __new__ is None: # check all possibles for __member_new__ before falling back to # __new__ for method in ('__member_new__', '__new__'): for possible in (member_type, first_enum): target = getattr(possible, method, None) if target not in ( None, None.__new__, object.__new__, Enum.__new__, ): __new__ = target break if __new__ is not None: break else: __new__ = object.__new__ # if a non-object.__new__ is used then whatever value/tuple was # assigned to the enum member name will be passed to __new__ and to the # new enum member's __init__ if __new__ is object.__new__: use_args = False else: use_args = True return __new__, save_new, use_args ######################################################## # In order to support Python 2 and 3 with a single # codebase we have to create the Enum methods separately # and then use the `type(name, bases, dict)` method to # create the class. ######################################################## temp_enum_dict = {} temp_enum_dict['__doc__'] = "Generic enumeration.\n\n Derive from this class to define new enumerations.\n\n" def __new__(cls, value): # all enum instances are actually created during class construction # without calling this method; this method is called by the metaclass' # __call__ (i.e. Color(3) ), and by pickle if type(value) is cls: # For lookups like Color(Color.red) value = value.value #return value # by-value search for a matching enum member # see if it's in the reverse mapping (for hashable values) try: if value in cls._value2member_map_: return cls._value2member_map_[value] except TypeError: # not there, now do long search -- O(n) behavior for member in cls._member_map_.values(): if member.value == value: return member raise ValueError("%s is not a valid %s" % (value, cls.__name__)) temp_enum_dict['__new__'] = __new__ del __new__ def __repr__(self): return "<%s.%s: %r>" % ( self.__class__.__name__, self._name_, self._value_) temp_enum_dict['__repr__'] = __repr__ del __repr__ def __str__(self): return "%s.%s" % (self.__class__.__name__, self._name_) temp_enum_dict['__str__'] = __str__ del __str__ def __dir__(self): added_behavior = [m for m in self.__class__.__dict__ if m[0] != '_'] return (['__class__', '__doc__', '__module__', 'name', 'value'] + added_behavior) temp_enum_dict['__dir__'] = __dir__ del __dir__ def __format__(self, format_spec): # mixed-in Enums should use the mixed-in type's __format__, otherwise # we can get strange results with the Enum name showing up instead of # the value # pure Enum branch if self._member_type_ is object: cls = str val = str(self) # mix-in branch else: cls = self._member_type_ val = self.value return cls.__format__(val, format_spec) temp_enum_dict['__format__'] = __format__ del __format__ #################################### # Python's less than 2.6 use __cmp__ if pyver < 2.6: def __cmp__(self, other): if type(other) is self.__class__: if self is other: return 0 return -1 return NotImplemented raise TypeError("unorderable types: %s() and %s()" % (self.__class__.__name__, other.__class__.__name__)) temp_enum_dict['__cmp__'] = __cmp__ del __cmp__ else: def __le__(self, other): raise TypeError("unorderable types: %s() <= %s()" % (self.__class__.__name__, other.__class__.__name__)) temp_enum_dict['__le__'] = __le__ del __le__ def __lt__(self, other): raise TypeError("unorderable types: %s() < %s()" % (self.__class__.__name__, other.__class__.__name__)) temp_enum_dict['__lt__'] = __lt__ del __lt__ def __ge__(self, other): raise TypeError("unorderable types: %s() >= %s()" % (self.__class__.__name__, other.__class__.__name__)) temp_enum_dict['__ge__'] = __ge__ del __ge__ def __gt__(self, other): raise TypeError("unorderable types: %s() > %s()" % (self.__class__.__name__, other.__class__.__name__)) temp_enum_dict['__gt__'] = __gt__ del __gt__ def __eq__(self, other): if type(other) is self.__class__: return self is other return NotImplemented temp_enum_dict['__eq__'] = __eq__ del __eq__ def __ne__(self, other): if type(other) is self.__class__: return self is not other return NotImplemented temp_enum_dict['__ne__'] = __ne__ del __ne__ def __getnewargs__(self): return (self._value_, ) temp_enum_dict['__getnewargs__'] = __getnewargs__ del __getnewargs__ def __hash__(self): return hash(self._name_) temp_enum_dict['__hash__'] = __hash__ del __hash__ # _RouteClassAttributeToGetattr is used to provide access to the `name` # and `value` properties of enum members while keeping some measure of # protection from modification, while still allowing for an enumeration # to have members named `name` and `value`. This works because enumeration # members are not set directly on the enum class -- __getattr__ is # used to look them up. @_RouteClassAttributeToGetattr def name(self): return self._name_ temp_enum_dict['name'] = name del name @_RouteClassAttributeToGetattr def value(self): return self._value_ temp_enum_dict['value'] = value del value Enum = EnumMeta('Enum', (object, ), temp_enum_dict) del temp_enum_dict # Enum has now been created ########################### class IntEnum(int, Enum): """Enum where members are also (and must be) ints""" def unique(enumeration): """Class decorator that ensures only unique members exist in an enumeration.""" duplicates = [] for name, member in enumeration.__members__.items(): if name != member.name: duplicates.append((name, member.name)) if duplicates: duplicate_names = ', '.join( ["%s -> %s" % (alias, name) for (alias, name) in duplicates] ) raise ValueError('duplicate names found in %r: %s' % (enumeration, duplicate_names) ) return enumeration
27,890
Python
.py
626
33.789137
113
0.547854
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,033
__init__.py
stan-dev_pystan2/pystan/external/enum/__init__.py
"""Python Enumerations""" import sys as _sys __all__ = ['Enum', 'IntEnum', 'unique'] pyver = float('%s.%s' % _sys.version_info[:2]) try: any except NameError: def any(iterable): for element in iterable: if element: return True return False class _RouteClassAttributeToGetattr(object): """Route attribute access on a class to __getattr__. This is a descriptor, used to define attributes that act differently when accessed through an instance and through a class. Instance access remains normal, but access to an attribute through a class will be routed to the class's __getattr__ method; this is done by raising AttributeError. """ def __init__(self, fget=None): self.fget = fget def __get__(self, instance, ownerclass=None): if instance is None: raise AttributeError() return self.fget(instance) def __set__(self, instance, value): raise AttributeError("can't set attribute") def __delete__(self, instance): raise AttributeError("can't delete attribute") def _is_descriptor(obj): """Returns True if obj is a descriptor, False otherwise.""" return ( hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__')) def _is_dunder(name): """Returns True if a __dunder__ name, False otherwise.""" return (name[:2] == name[-2:] == '__' and name[2:3] != '_' and name[-3:-2] != '_' and len(name) > 4) def _is_sunder(name): """Returns True if a _sunder_ name, False otherwise.""" return (name[0] == name[-1] == '_' and name[1:2] != '_' and name[-2:-1] != '_' and len(name) > 2) def _make_class_unpicklable(cls): """Make the given class un-picklable.""" def _break_on_call_reduce(self): raise TypeError('%r cannot be pickled' % self) cls.__reduce__ = _break_on_call_reduce cls.__module__ = '<unknown>' class _EnumDict(dict): """Track enum member order and ensure member names are not reused. EnumMeta will use the names found in self._member_names as the enumeration member names. """ def __init__(self): super(_EnumDict, self).__init__() self._member_names = [] def __setitem__(self, key, value): """Changes anything not dundered or not a descriptor. If a descriptor is added with the same name as an enum member, the name is removed from _member_names (this may leave a hole in the numerical sequence of values). If an enum member name is used twice, an error is raised; duplicate values are not checked for. Single underscore (sunder) names are reserved. Note: in 3.x __order__ is simply discarded as a not necessary piece leftover from 2.x """ if pyver >= 3.0 and key == '__order__': return if _is_sunder(key): raise ValueError('_names_ are reserved for future Enum use') elif _is_dunder(key): pass elif key in self._member_names: # descriptor overwriting an enum? raise TypeError('Attempted to reuse key: %r' % key) elif not _is_descriptor(value): if key in self: # enum overwriting a descriptor? raise TypeError('Key already defined as: %r' % self[key]) self._member_names.append(key) super(_EnumDict, self).__setitem__(key, value) # Dummy value for Enum as EnumMeta explicity checks for it, but of course until # EnumMeta finishes running the first time the Enum class doesn't exist. This # is also why there are checks in EnumMeta like `if Enum is not None` Enum = None class EnumMeta(type): """Metaclass for Enum""" @classmethod def __prepare__(metacls, cls, bases): return _EnumDict() def __new__(metacls, cls, bases, classdict): # an Enum class is final once enumeration items have been defined; it # cannot be mixed with other types (int, float, etc.) if it has an # inherited __new__ unless a new __new__ is defined (or the resulting # class will fail). if type(classdict) is dict: original_dict = classdict classdict = _EnumDict() for k, v in original_dict.items(): classdict[k] = v member_type, first_enum = metacls._get_mixins_(bases) #if member_type is object: # use_args = False #else: # use_args = True __new__, save_new, use_args = metacls._find_new_(classdict, member_type, first_enum) # save enum items into separate mapping so they don't get baked into # the new class members = dict((k, classdict[k]) for k in classdict._member_names) for name in classdict._member_names: del classdict[name] # py2 support for definition order __order__ = classdict.get('__order__') if __order__ is None: __order__ = classdict._member_names if pyver < 3.0: order_specified = False else: order_specified = True else: del classdict['__order__'] order_specified = True if pyver < 3.0: __order__ = __order__.replace(',', ' ').split() aliases = [name for name in members if name not in __order__] __order__ += aliases # check for illegal enum names (any others?) invalid_names = set(members) & set(['mro']) if invalid_names: raise ValueError('Invalid enum member name(s): %s' % ( ', '.join(invalid_names), )) # create our new Enum type enum_class = super(EnumMeta, metacls).__new__(metacls, cls, bases, classdict) enum_class._member_names_ = [] # names in random order enum_class._member_map_ = {} # name->value map enum_class._member_type_ = member_type # Reverse value->name map for hashable values. enum_class._value2member_map_ = {} # check for a __getnewargs__, and if not present sabotage # pickling, since it won't work anyway if (member_type is not object and member_type.__dict__.get('__getnewargs__') is None ): _make_class_unpicklable(enum_class) # instantiate them, checking for duplicates as we go # we instantiate first instead of checking for duplicates first in case # a custom __new__ is doing something funky with the values -- such as # auto-numbering ;) if __new__ is None: __new__ = enum_class.__new__ for member_name in __order__: value = members[member_name] if not isinstance(value, tuple): args = (value, ) else: args = value if member_type is tuple: # special case for tuple enums args = (args, ) # wrap it one more time if not use_args or not args: enum_member = __new__(enum_class) if not hasattr(enum_member, '_value_'): enum_member._value_ = value else: enum_member = __new__(enum_class, *args) if not hasattr(enum_member, '_value_'): enum_member._value_ = member_type(*args) value = enum_member._value_ enum_member._name_ = member_name enum_member.__objclass__ = enum_class enum_member.__init__(*args) # If another member with the same value was already defined, the # new member becomes an alias to the existing one. for name, canonical_member in enum_class._member_map_.items(): if canonical_member.value == enum_member._value_: enum_member = canonical_member break else: # Aliases don't appear in member names (only in __members__). enum_class._member_names_.append(member_name) enum_class._member_map_[member_name] = enum_member try: # This may fail if value is not hashable. We can't add the value # to the map, and by-value lookups for this value will be # linear. enum_class._value2member_map_[value] = enum_member except TypeError: pass # in Python2.x we cannot know definition order, so go with value order # unless __order__ was specified in the class definition if not order_specified: enum_class._member_names_ = [ e[0] for e in sorted( [(name, enum_class._member_map_[name]) for name in enum_class._member_names_], key=lambda t: t[1]._value_ )] # double check that repr and friends are not the mixin's or various # things break (such as pickle) if Enum is not None: setattr(enum_class, '__getnewargs__', Enum.__getnewargs__) for name in ('__repr__', '__str__', '__format__'): class_method = getattr(enum_class, name) obj_method = getattr(member_type, name, None) enum_method = getattr(first_enum, name, None) if obj_method is not None and obj_method is class_method: setattr(enum_class, name, enum_method) # method resolution and int's are not playing nice # Python's less than 2.6 use __cmp__ if pyver < 2.6: if issubclass(enum_class, int): setattr(enum_class, '__cmp__', getattr(int, '__cmp__')) elif pyver < 3.0: if issubclass(enum_class, int): for method in ( '__le__', '__lt__', '__gt__', '__ge__', '__eq__', '__ne__', '__hash__', ): setattr(enum_class, method, getattr(int, method)) # replace any other __new__ with our own (as long as Enum is not None, # anyway) -- again, this is to support pickle if Enum is not None: # if the user defined their own __new__, save it before it gets # clobbered in case they subclass later if save_new: setattr(enum_class, '__member_new__', enum_class.__dict__['__new__']) setattr(enum_class, '__new__', Enum.__dict__['__new__']) return enum_class def __call__(cls, value, names=None, module=None, type=None): """Either returns an existing member, or creates a new enum class. This method is used both when an enum class is given a value to match to an enumeration member (i.e. Color(3)) and for the functional API (i.e. Color = Enum('Color', names='red green blue')). When used for the functional API: `module`, if set, will be stored in the new class' __module__ attribute; `type`, if set, will be mixed in as the first base class. Note: if `module` is not set this routine will attempt to discover the calling module by walking the frame stack; if this is unsuccessful the resulting class will not be pickleable. """ if names is None: # simple value lookup return cls.__new__(cls, value) # otherwise, functional API: we're creating a new Enum type return cls._create_(value, names, module=module, type=type) def __contains__(cls, member): return isinstance(member, cls) and member.name in cls._member_map_ def __delattr__(cls, attr): # nicer error message when someone tries to delete an attribute # (see issue19025). if attr in cls._member_map_: raise AttributeError( "%s: cannot delete Enum member." % cls.__name__) super(EnumMeta, cls).__delattr__(attr) def __dir__(self): return (['__class__', '__doc__', '__members__', '__module__'] + self._member_names_) @property def __members__(cls): """Returns a mapping of member name->value. This mapping lists all enum members, including aliases. Note that this is a copy of the internal mapping. """ return cls._member_map_.copy() def __getattr__(cls, name): """Return the enum member matching `name` We use __getattr__ instead of descriptors or inserting into the enum class' __dict__ in order to support `name` and `value` being both properties for enum members (which live in the class' __dict__) and enum members themselves. """ if _is_dunder(name): raise AttributeError(name) try: return cls._member_map_[name] except KeyError: raise AttributeError(name) def __getitem__(cls, name): return cls._member_map_[name] def __iter__(cls): return (cls._member_map_[name] for name in cls._member_names_) def __reversed__(cls): return (cls._member_map_[name] for name in reversed(cls._member_names_)) def __len__(cls): return len(cls._member_names_) def __repr__(cls): return "<enum %r>" % cls.__name__ def __setattr__(cls, name, value): """Block attempts to reassign Enum members. A simple assignment to the class namespace only changes one of the several possible ways to get an Enum member from the Enum class, resulting in an inconsistent Enumeration. """ member_map = cls.__dict__.get('_member_map_', {}) if name in member_map: raise AttributeError('Cannot reassign members.') super(EnumMeta, cls).__setattr__(name, value) def _create_(cls, class_name, names=None, module=None, type=None): """Convenience method to create a new Enum class. `names` can be: * A string containing member names, separated either with spaces or commas. Values are auto-numbered from 1. * An iterable of member names. Values are auto-numbered from 1. * An iterable of (member name, value) pairs. * A mapping of member name -> value. """ metacls = cls.__class__ if type is None: bases = (cls, ) else: bases = (type, cls) classdict = metacls.__prepare__(class_name, bases) __order__ = [] # special processing needed for names? if isinstance(names, str): names = names.replace(',', ' ').split() if isinstance(names, (tuple, list)) and isinstance(names[0], str): names = [(e, i+1) for (i, e) in enumerate(names)] # Here, names is either an iterable of (name, value) or a mapping. for item in names: if isinstance(item, str): member_name, member_value = item, names[item] else: member_name, member_value = item classdict[member_name] = member_value __order__.append(member_name) # only set __order__ in classdict if name/value was not from a mapping if not isinstance(item, str): classdict['__order__'] = ' '.join(__order__) enum_class = metacls.__new__(metacls, class_name, bases, classdict) # TODO: replace the frame hack if a blessed way to know the calling # module is ever developed if module is None: try: module = _sys._getframe(2).f_globals['__name__'] except (AttributeError, ValueError): pass if module is None: _make_class_unpicklable(enum_class) else: enum_class.__module__ = module return enum_class @staticmethod def _get_mixins_(bases): """Returns the type for creating enum members, and the first inherited enum class. bases: the tuple of bases that was given to __new__ """ if not bases or Enum is None: return object, Enum # double check that we are not subclassing a class with existing # enumeration members; while we're at it, see if any other data # type has been mixed in so we can use the correct __new__ member_type = first_enum = None for base in bases: if (base is not Enum and issubclass(base, Enum) and base._member_names_): raise TypeError("Cannot extend enumerations") # base is now the last base in bases if not issubclass(base, Enum): raise TypeError("new enumerations must be created as " "`ClassName([mixin_type,] enum_type)`") # get correct mix-in type (either mix-in type of Enum subclass, or # first base if last base is Enum) if not issubclass(bases[0], Enum): member_type = bases[0] # first data type first_enum = bases[-1] # enum type else: for base in bases[0].__mro__: # most common: (IntEnum, int, Enum, object) # possible: (<Enum 'AutoIntEnum'>, <Enum 'IntEnum'>, # <class 'int'>, <Enum 'Enum'>, # <class 'object'>) if issubclass(base, Enum): if first_enum is None: first_enum = base else: if member_type is None: member_type = base return member_type, first_enum if pyver < 3.0: @staticmethod def _find_new_(classdict, member_type, first_enum): """Returns the __new__ to be used for creating the enum members. classdict: the class dictionary given to __new__ member_type: the data type whose __new__ will be used by default first_enum: enumeration to check for an overriding __new__ """ # now find the correct __new__, checking to see of one was defined # by the user; also check earlier enum classes in case a __new__ was # saved as __member_new__ __new__ = classdict.get('__new__', None) if __new__: return None, True, True # __new__, save_new, use_args N__new__ = getattr(None, '__new__') O__new__ = getattr(object, '__new__') if Enum is None: E__new__ = N__new__ else: E__new__ = Enum.__dict__['__new__'] # check all possibles for __member_new__ before falling back to # __new__ for method in ('__member_new__', '__new__'): for possible in (member_type, first_enum): try: target = possible.__dict__[method] except (AttributeError, KeyError): target = getattr(possible, method, None) if target not in [ None, N__new__, O__new__, E__new__, ]: if method == '__member_new__': classdict['__new__'] = target return None, False, True if isinstance(target, staticmethod): target = target.__get__(member_type) __new__ = target break if __new__ is not None: break else: __new__ = object.__new__ # if a non-object.__new__ is used then whatever value/tuple was # assigned to the enum member name will be passed to __new__ and to the # new enum member's __init__ if __new__ is object.__new__: use_args = False else: use_args = True return __new__, False, use_args else: @staticmethod def _find_new_(classdict, member_type, first_enum): """Returns the __new__ to be used for creating the enum members. classdict: the class dictionary given to __new__ member_type: the data type whose __new__ will be used by default first_enum: enumeration to check for an overriding __new__ """ # now find the correct __new__, checking to see of one was defined # by the user; also check earlier enum classes in case a __new__ was # saved as __member_new__ __new__ = classdict.get('__new__', None) # should __new__ be saved as __member_new__ later? save_new = __new__ is not None if __new__ is None: # check all possibles for __member_new__ before falling back to # __new__ for method in ('__member_new__', '__new__'): for possible in (member_type, first_enum): target = getattr(possible, method, None) if target not in ( None, None.__new__, object.__new__, Enum.__new__, ): __new__ = target break if __new__ is not None: break else: __new__ = object.__new__ # if a non-object.__new__ is used then whatever value/tuple was # assigned to the enum member name will be passed to __new__ and to the # new enum member's __init__ if __new__ is object.__new__: use_args = False else: use_args = True return __new__, save_new, use_args ######################################################## # In order to support Python 2 and 3 with a single # codebase we have to create the Enum methods separately # and then use the `type(name, bases, dict)` method to # create the class. ######################################################## temp_enum_dict = {} temp_enum_dict['__doc__'] = "Generic enumeration.\n\n Derive from this class to define new enumerations.\n\n" def __new__(cls, value): # all enum instances are actually created during class construction # without calling this method; this method is called by the metaclass' # __call__ (i.e. Color(3) ), and by pickle if type(value) is cls: # For lookups like Color(Color.red) value = value.value #return value # by-value search for a matching enum member # see if it's in the reverse mapping (for hashable values) try: if value in cls._value2member_map_: return cls._value2member_map_[value] except TypeError: # not there, now do long search -- O(n) behavior for member in cls._member_map_.values(): if member.value == value: return member raise ValueError("%s is not a valid %s" % (value, cls.__name__)) temp_enum_dict['__new__'] = __new__ del __new__ def __repr__(self): return "<%s.%s: %r>" % ( self.__class__.__name__, self._name_, self._value_) temp_enum_dict['__repr__'] = __repr__ del __repr__ def __str__(self): return "%s.%s" % (self.__class__.__name__, self._name_) temp_enum_dict['__str__'] = __str__ del __str__ def __dir__(self): added_behavior = [m for m in self.__class__.__dict__ if m[0] != '_'] return (['__class__', '__doc__', '__module__', 'name', 'value'] + added_behavior) temp_enum_dict['__dir__'] = __dir__ del __dir__ def __format__(self, format_spec): # mixed-in Enums should use the mixed-in type's __format__, otherwise # we can get strange results with the Enum name showing up instead of # the value # pure Enum branch if self._member_type_ is object: cls = str val = str(self) # mix-in branch else: cls = self._member_type_ val = self.value return cls.__format__(val, format_spec) temp_enum_dict['__format__'] = __format__ del __format__ #################################### # Python's less than 2.6 use __cmp__ if pyver < 2.6: def __cmp__(self, other): if type(other) is self.__class__: if self is other: return 0 return -1 return NotImplemented raise TypeError("unorderable types: %s() and %s()" % (self.__class__.__name__, other.__class__.__name__)) temp_enum_dict['__cmp__'] = __cmp__ del __cmp__ else: def __le__(self, other): raise TypeError("unorderable types: %s() <= %s()" % (self.__class__.__name__, other.__class__.__name__)) temp_enum_dict['__le__'] = __le__ del __le__ def __lt__(self, other): raise TypeError("unorderable types: %s() < %s()" % (self.__class__.__name__, other.__class__.__name__)) temp_enum_dict['__lt__'] = __lt__ del __lt__ def __ge__(self, other): raise TypeError("unorderable types: %s() >= %s()" % (self.__class__.__name__, other.__class__.__name__)) temp_enum_dict['__ge__'] = __ge__ del __ge__ def __gt__(self, other): raise TypeError("unorderable types: %s() > %s()" % (self.__class__.__name__, other.__class__.__name__)) temp_enum_dict['__gt__'] = __gt__ del __gt__ def __eq__(self, other): if type(other) is self.__class__: return self is other return NotImplemented temp_enum_dict['__eq__'] = __eq__ del __eq__ def __ne__(self, other): if type(other) is self.__class__: return self is not other return NotImplemented temp_enum_dict['__ne__'] = __ne__ del __ne__ def __getnewargs__(self): return (self._value_, ) temp_enum_dict['__getnewargs__'] = __getnewargs__ del __getnewargs__ def __hash__(self): return hash(self._name_) temp_enum_dict['__hash__'] = __hash__ del __hash__ # _RouteClassAttributeToGetattr is used to provide access to the `name` # and `value` properties of enum members while keeping some measure of # protection from modification, while still allowing for an enumeration # to have members named `name` and `value`. This works because enumeration # members are not set directly on the enum class -- __getattr__ is # used to look them up. @_RouteClassAttributeToGetattr def name(self): return self._name_ temp_enum_dict['name'] = name del name @_RouteClassAttributeToGetattr def value(self): return self._value_ temp_enum_dict['value'] = value del value Enum = EnumMeta('Enum', (object, ), temp_enum_dict) del temp_enum_dict # Enum has now been created ########################### class IntEnum(int, Enum): """Enum where members are also (and must be) ints""" def unique(enumeration): """Class decorator that ensures only unique members exist in an enumeration.""" duplicates = [] for name, member in enumeration.__members__.items(): if name != member.name: duplicates.append((name, member.name)) if duplicates: duplicate_names = ', '.join( ["%s -> %s" % (alias, name) for (alias, name) in duplicates] ) raise ValueError('duplicate names found in %r: %s' % (enumeration, duplicate_names) ) return enumeration
27,890
Python
.py
626
33.789137
113
0.547854
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,034
mstats.py
stan-dev_pystan2/pystan/external/scipy/mstats.py
""" mquantiles function from scipy scipy commit: 195569e91b0708aae26ea74581d03d3ca279117e :author: Pierre GF Gerard-Marchant :contact: pierregm_at_uga_edu scipy is distributed under a BSD license """ import numpy as np import numpy.ma as ma from numpy.ma import masked, nomask def mquantiles(a, prob=list([.25,.5,.75]), alphap=.4, betap=.4, axis=None, limit=()): """ Computes empirical quantiles for a data array. Samples quantile are defined by ``Q(p) = (1-gamma)*x[j] + gamma*x[j+1]``, where ``x[j]`` is the j-th order statistic, and gamma is a function of ``j = floor(n*p + m)``, ``m = alphap + p*(1 - alphap - betap)`` and ``g = n*p + m - j``. Reinterpreting the above equations to compare to **R** lead to the equation: ``p(k) = (k - alphap)/(n + 1 - alphap - betap)`` Typical values of (alphap,betap) are: - (0,1) : ``p(k) = k/n`` : linear interpolation of cdf (**R** type 4) - (.5,.5) : ``p(k) = (k - 1/2.)/n`` : piecewise linear function (**R** type 5) - (0,0) : ``p(k) = k/(n+1)`` : (**R** type 6) - (1,1) : ``p(k) = (k-1)/(n-1)``: p(k) = mode[F(x[k])]. (**R** type 7, **R** default) - (1/3,1/3): ``p(k) = (k-1/3)/(n+1/3)``: Then p(k) ~ median[F(x[k])]. The resulting quantile estimates are approximately median-unbiased regardless of the distribution of x. (**R** type 8) - (3/8,3/8): ``p(k) = (k-3/8)/(n+1/4)``: Blom. The resulting quantile estimates are approximately unbiased if x is normally distributed (**R** type 9) - (.4,.4) : approximately quantile unbiased (Cunnane) - (.35,.35): APL, used with PWM Parameters ---------- a : array_like Input data, as a sequence or array of dimension at most 2. prob : array_like, optional List of quantiles to compute. alphap : float, optional Plotting positions parameter, default is 0.4. betap : float, optional Plotting positions parameter, default is 0.4. axis : int, optional Axis along which to perform the trimming. If None (default), the input array is first flattened. limit : tuple Tuple of (lower, upper) values. Values of `a` outside this open interval are ignored. Returns ------- mquantiles : MaskedArray An array containing the calculated quantiles. Notes ----- This formulation is very similar to **R** except the calculation of ``m`` from ``alphap`` and ``betap``, where in **R** ``m`` is defined with each type. References ---------- .. [1] *R* statistical software at http://www.r-project.org/ Examples -------- >>> from scipy.stats.mstats import mquantiles >>> a = np.array([6., 47., 49., 15., 42., 41., 7., 39., 43., 40., 36.]) >>> mquantiles(a) array([ 19.2, 40. , 42.8]) Using a 2D array, specifying axis and limit. >>> data = np.array([[ 6., 7., 1.], [ 47., 15., 2.], [ 49., 36., 3.], [ 15., 39., 4.], [ 42., 40., -999.], [ 41., 41., -999.], [ 7., -999., -999.], [ 39., -999., -999.], [ 43., -999., -999.], [ 40., -999., -999.], [ 36., -999., -999.]]) >>> mquantiles(data, axis=0, limit=(0, 50)) array([[ 19.2 , 14.6 , 1.45], [ 40. , 37.5 , 2.5 ], [ 42.8 , 40.05, 3.55]]) >>> data[:, 2] = -999. >>> mquantiles(data, axis=0, limit=(0, 50)) masked_array(data = [[19.2 14.6 --] [40.0 37.5 --] [42.8 40.05 --]], mask = [[False False True] [False False True] [False False True]], fill_value = 1e+20) """ def _quantiles1D(data,m,p): x = np.sort(data.compressed()) n = len(x) if n == 0: return ma.array(np.empty(len(p), dtype=float), mask=True) elif n == 1: return ma.array(np.resize(x, p.shape), mask=nomask) aleph = (n*p + m) k = np.floor(aleph.clip(1, n-1)).astype(int) gamma = (aleph-k).clip(0,1) return (1.-gamma)*x[(k-1).tolist()] + gamma*x[k.tolist()] # Initialization & checks --------- data = ma.array(a, copy=False) if data.ndim > 2: raise TypeError("Array should be 2D at most !") # if limit: condition = (limit[0] < data) & (data < limit[1]) data[~condition.filled(True)] = masked # p = np.array(prob, copy=False, ndmin=1) m = alphap + p*(1.-alphap-betap) # Computes quantiles along axis (or globally) if (axis is None): return _quantiles1D(data, m, p) return ma.apply_along_axis(_quantiles1D, axis, data, m, p)
4,996
Python
.py
127
30.96063
77
0.515564
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,035
trace.py
stan-dev_pystan2/pystan/external/pymc/trace.py
# mock out pymc classes for now MultiTrace = type(None)
56
Python
.py
2
27
31
0.777778
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,036
plots.py
stan-dev_pystan2/pystan/external/pymc/plots.py
# pymc git commit: 6115726122d46267c86d16de635941daa37eb357 # ======= # License # ======= # # PyMC is distributed under the Apache License, Version 2.0 # # Copyright (c) 2006 Christopher J. Fonnesbeck (Academic Free License) # Copyright (c) 2007-2008 Christopher J. Fonnesbeck, Anand Prabhakar Patil, David Huard (Academic Free License) # Copyright (c) 2009-2013 The PyMC developers (see contributors to pymc-devs on GitHub) # All rights reserved. from pylab import * try: import matplotlib.gridspec as gridspec except ImportError: gridspec = None import numpy as np from scipy.stats import kde from .stats import * from .trace import * __all__ = ['traceplot', 'kdeplot', 'kde2plot', 'forestplot', 'autocorrplot'] def traceplot(trace, vars=None): if vars is None: vars = trace.varnames if isinstance(trace, MultiTrace): trace = trace.combined() n = len(vars) f, ax = subplots(n, 2, squeeze=False) for i, v in enumerate(vars): d = np.squeeze(trace[v]) if trace[v].dtype.kind == 'i': ax[i, 0].hist(d, bins=sqrt(d.size)) else: kdeplot_op(ax[i, 0], d) ax[i, 0].set_title(str(v)) ax[i, 1].plot(d, alpha=.35) ax[i, 0].set_ylabel("frequency") ax[i, 1].set_ylabel("sample value") return f def kdeplot_op(ax, data): data = np.atleast_2d(data.T).T for i in range(data.shape[1]): d = data[:, i] density = kde.gaussian_kde(d) l = np.min(d) u = np.max(d) x = np.linspace(0, 1, 100) * (u - l) + l ax.plot(x, density(x)) def kde2plot_op(ax, x, y, grid=200): xmin = x.min() xmax = x.max() ymin = y.min() ymax = y.max() grid = grid * 1j X, Y = np.mgrid[xmin:xmax:grid, ymin:ymax:grid] positions = np.vstack([X.ravel(), Y.ravel()]) values = np.vstack([x, y]) kernel = kde.gaussian_kde(values) Z = np.reshape(kernel(positions).T, X.shape) ax.imshow(np.rot90(Z), cmap=cm.gist_earth_r, extent=[xmin, xmax, ymin, ymax]) def kdeplot(data): f, ax = subplots(1, 1, squeeze=True) kdeplot_op(ax, data) return f def kde2plot(x, y, grid=200): f, ax = subplots(1, 1, squeeze=True) kde2plot_op(ax, x, y, grid) return f def autocorrplot(trace, vars=None, fontmap = None, max_lag=100): """Bar plot of the autocorrelation function for a trace""" try: # MultiTrace traces = trace.traces except AttributeError: # NpTrace traces = [trace] if fontmap is None: fontmap = {1:10, 2:8, 3:6, 4:5, 5:4} if vars is None: vars = traces[0].varnames # Extract sample data samples = [{v:trace[v] for v in vars} for trace in traces] chains = len(traces) n = len(samples[0]) f, ax = subplots(n, chains, squeeze=False) max_lag = min(len(samples[0][vars[0]])-1, max_lag) for i, v in enumerate(vars): for j in xrange(chains): d = np.squeeze(samples[j][v]) ax[i,j].acorr(d, detrend=mlab.detrend_mean, maxlags=max_lag) if not j: ax[i, j].set_ylabel("correlation") ax[i, j].set_xlabel("lag") if chains > 1: ax[i, j].set_title("chain {0}".format(j+1)) # Smaller tick labels tlabels = gca().get_xticklabels() setp(tlabels, 'fontsize', fontmap[1]) tlabels = gca().get_yticklabels() setp(tlabels, 'fontsize', fontmap[1]) def var_str(name, shape): """Return a sequence of strings naming the element of the tallyable object. This is a support function for forestplot. :Example: >>> var_str('theta', (4,)) ['theta[1]', 'theta[2]', 'theta[3]', 'theta[4]'] """ size = prod(shape) ind = (indices(shape) + 1).reshape(-1, size) names = ['[' + ','.join(map(str, i)) + ']' for i in zip(*ind)] # if len(name)>12: # name = '\n'.join(name.split('_')) # name += '\n' names[0] = '%s %s' % (name, names[0]) return names def forestplot(trace_obj, vars=None, alpha=0.05, quartiles=True, rhat=True, main=None, xtitle=None, xrange=None, ylabels=None, chain_spacing=0.05, vline=0): """ Forest plot (model summary plot) Generates a "forest plot" of 100*(1-alpha)% credible intervals for either the set of variables in a given model, or a specified set of nodes. :Arguments: trace_obj: NpTrace or MultiTrace object Trace(s) from an MCMC sample. vars: list List of variables to plot (defaults to None, which results in all variables plotted). alpha (optional): float Alpha value for (1-alpha)*100% credible intervals (defaults to 0.05). quartiles (optional): bool Flag for plotting the interquartile range, in addition to the (1-alpha)*100% intervals (defaults to True). rhat (optional): bool Flag for plotting Gelman-Rubin statistics. Requires 2 or more chains (defaults to True). main (optional): string Title for main plot. Passing False results in titles being suppressed; passing None (default) results in default titles. xtitle (optional): string Label for x-axis. Defaults to no label xrange (optional): list or tuple Range for x-axis. Defaults to matplotlib's best guess. ylabels (optional): list User-defined labels for each variable. If not provided, the node __name__ attributes are used. chain_spacing (optional): float Plot spacing between chains (defaults to 0.05). vline (optional): numeric Location of vertical reference line (defaults to 0). """ if not gridspec: print_( '\nYour installation of matplotlib is not recent enough to support summary_plot; this function is disabled until matplotlib is updated.') return # Quantiles to be calculated qlist = [100 * alpha / 2, 50, 100 * (1 - alpha / 2)] if quartiles: qlist = [100 * alpha / 2, 25, 50, 75, 100 * (1 - alpha / 2)] # Range for x-axis plotrange = None # Number of chains chains = None # Gridspec gs = None # Subplots interval_plot = None rhat_plot = None try: # First try MultiTrace type traces = trace_obj.traces if rhat and len(traces) > 1: from .diagnostics import gelman_rubin R = gelman_rubin(trace_obj) if vars is not None: R = {v: R[v] for v in vars} else: rhat = False except AttributeError: # Single NpTrace traces = [trace_obj] # Can't calculate Gelman-Rubin with a single trace rhat = False if vars is None: vars = traces[0].varnames # Empty list for y-axis labels labels = [] chains = len(traces) if gs is None: # Initialize plot if rhat and chains > 1: gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1]) else: gs = gridspec.GridSpec(1, 1) # Subplot for confidence intervals interval_plot = subplot(gs[0]) for j, tr in enumerate(traces): # Get quantiles trace_quantiles = quantiles(tr, qlist) hpd_intervals = hpd(tr, alpha) # Counter for current variable var = 1 for varname in vars: var_quantiles = trace_quantiles[varname] quants = var_quantiles.values() var_hpd = hpd_intervals[varname].T # Substitute HPD interval for quantile quants[0] = var_hpd[0].T quants[-1] = var_hpd[1].T # Ensure x-axis contains range of current interval if plotrange: plotrange = [min( plotrange[0], np.min(quants)), max(plotrange[1], np.max(quants))] else: plotrange = [np.min(quants), np.max(quants)] # Number of elements in current variable value = tr[varname][0] k = np.size(value) # Append variable name(s) to list if not j: if k > 1: names = var_str(varname, shape(value)) labels += names else: labels.append(varname) # labels.append('\n'.join(varname.split('_'))) # Add spacing for each chain, if more than one e = [0] + [(chain_spacing * ((i + 2) / 2)) * (-1) ** i for i in range(chains - 1)] # Deal with multivariate nodes if k > 1: for i, q in enumerate(np.transpose(quants).squeeze()): # Y coordinate with jitter y = -(var + i) + e[j] if quartiles: # Plot median plot(q[2], y, 'bo', markersize=4) # Plot quartile interval errorbar( x=(q[1], q[3]), y=(y, y), linewidth=2, color="blue") else: # Plot median plot(q[1], y, 'bo', markersize=4) # Plot outer interval errorbar( x=(q[0], q[-1]), y=(y, y), linewidth=1, color="blue") else: # Y coordinate with jitter y = -var + e[j] if quartiles: # Plot median plot(quants[2], y, 'bo', markersize=4) # Plot quartile interval errorbar( x=(quants[1], quants[3]), y=(y, y), linewidth=2, color="blue") else: # Plot median plot(quants[1], y, 'bo', markersize=4) # Plot outer interval errorbar( x=(quants[0], quants[-1]), y=(y, y), linewidth=1, color="blue") # Increment index var += k labels = ylabels or labels # Update margins left_margin = np.max([len(x) for x in labels]) * 0.015 gs.update(left=left_margin, right=0.95, top=0.9, bottom=0.05) # Define range of y-axis ylim(-var + 0.5, -0.5) datarange = plotrange[1] - plotrange[0] xlim(plotrange[0] - 0.05 * datarange, plotrange[1] + 0.05 * datarange) # Add variable labels yticks([-(l + 1) for l in range(len(labels))], labels) # Add title if main is not False: plot_title = main or str(int(( 1 - alpha) * 100)) + "% Credible Intervals" title(plot_title) # Add x-axis label if xtitle is not None: xlabel(xtitle) # Constrain to specified range if xrange is not None: xlim(*xrange) # Remove ticklines on y-axes for ticks in interval_plot.yaxis.get_major_ticks(): ticks.tick1On = False ticks.tick2On = False for loc, spine in interval_plot.spines.iteritems(): if loc in ['bottom', 'top']: pass # spine.set_position(('outward',10)) # outward by 10 points elif loc in ['left', 'right']: spine.set_color('none') # don't draw spine # Reference line axvline(vline, color='k', linestyle='--') # Genenerate Gelman-Rubin plot if rhat and chains > 1: # If there are multiple chains, calculate R-hat rhat_plot = subplot(gs[1]) if main is not False: title("R-hat") # Set x range xlim(0.9, 2.1) # X axis labels xticks((1.0, 1.5, 2.0), ("1", "1.5", "2+")) yticks([-(l + 1) for l in range(len(labels))], "") i = 1 for varname in vars: value = traces[0][varname][0] k = np.size(value) if k > 1: plot([min(r, 2) for r in R[varname]], [-(j + i) for j in range(k)], 'bo', markersize=4) else: plot(min(R[varname], 2), -i, 'bo', markersize=4) i += k # Define range of y-axis ylim(-i + 0.5, -0.5) # Remove ticklines on y-axes for ticks in rhat_plot.yaxis.get_major_ticks(): ticks.tick1On = False ticks.tick2On = False for loc, spine in rhat_plot.spines.iteritems(): if loc in ['bottom', 'top']: pass # spine.set_position(('outward',10)) # outward by 10 points elif loc in ['left', 'right']: spine.set_color('none') # don't draw spine return gs
13,334
Python
.py
351
26.948718
149
0.528273
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,037
__init__.py
stan-dev_pystan2/pystan/experimental/__init__.py
import logging from .misc import fix_include from .pickling_tools import unpickle_fit logger = logging.getLogger('pystan') logger.warning("This submodule contains experimental code, please use with caution")
209
Python
.py
5
40.6
84
0.832512
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,038
pickling_tools.py
stan-dev_pystan2/pystan/experimental/pickling_tools.py
"""Experimental module to load fit without model instance.""" from distutils.core import Extension from Cython.Build.Inline import _get_build_extension from Cython.Build.Dependencies import cythonize import tempfile import logging import io import os import string import numpy as np import pickle import pystan import platform from string import ascii_letters, digits, printable, punctuation import sys import shutil from pystan._compat import PY2 from pystan.model import load_module logger = logging.getLogger('pystan') def create_fake_model(module_name): """Creates a fake model with specific module name. Parameters ---------- module_name : str Returns ------- StanModel Dummy StanModel object with specific module name. """ tbb_dir = os.path.join(os.path.dirname(__file__), '..', 'stan', 'lib', 'stan_math', 'lib','tbb') tbb_dir = os.path.abspath(tbb_dir) # reverse engineer the name model_name, nonce = module_name.replace("stanfit4", "").rsplit("_", 1) # create minimal code model_code = """generated quantities {real fake_parameter=1;}""" stanc_ret = pystan.api.stanc(model_code=model_code, model_name=model_name, obfuscate_model_name=False) model_cppname = stanc_ret['model_cppname'] model_cppcode = stanc_ret['cppcode'] original_module_name = module_name module_name = 'stanfit4{}_{}'.format(model_name, nonce) # module name should be same assert original_module_name == module_name lib_dir = tempfile.mkdtemp() pystan_dir = os.path.dirname(pystan.__file__) include_dirs = [ lib_dir, pystan_dir, os.path.join(pystan_dir, "stan", "src"), os.path.join(pystan_dir, "stan", "lib", "stan_math"), os.path.join(pystan_dir, "stan", "lib", "stan_math", "lib", "eigen_3.3.3"), os.path.join(pystan_dir, "stan", "lib", "stan_math", "lib", "boost_1.72.0"), os.path.join(pystan_dir, "stan", "lib", "stan_math", "lib", "sundials_4.1.0", "include"), os.path.join(pystan_dir, "stan", "lib", "stan_math", "lib", "tbb", "include"), np.get_include(), ] model_cpp_file = os.path.join(lib_dir, model_cppname + '.hpp') with io.open(model_cpp_file, 'w', encoding='utf-8') as outfile: outfile.write(model_cppcode) pyx_file = os.path.join(lib_dir, module_name + '.pyx') pyx_template_file = os.path.join(pystan_dir, 'stanfit4model.pyx') with io.open(pyx_template_file, 'r', encoding='utf-8') as infile: s = infile.read() template = string.Template(s) with io.open(pyx_file, 'w', encoding='utf-8') as outfile: s = template.safe_substitute(model_cppname=model_cppname) outfile.write(s) stan_macros = [ ('BOOST_RESULT_OF_USE_TR1', None), ('BOOST_NO_DECLTYPE', None), ('BOOST_DISABLE_ASSERTS', None), ] build_extension = _get_build_extension() extra_compile_args = [] if platform.platform().startswith('Win'): if build_extension.compiler in (None, 'msvc'): logger.warning("MSVC compiler is not supported") extra_compile_args = [ '/EHsc', '-DBOOST_DATE_TIME_NO_LIB', '/std:c++14', ] + extra_compile_args else: # Windows, but not msvc, likely mingw # fix bug in MingW-W64 # use posix threads extra_compile_args = [ '-O1', '-ftemplate-depth-256', '-Wno-unused-function', '-Wno-uninitialized', '-std=c++1y', "-D_hypot=hypot", "-pthread", "-fexceptions", '-DSTAN_THREADS', '-D_REENTRANT', ] + extra_compile_args extra_link_args = [] else: # linux or macOS extra_compile_args = [ '-O1', '-ftemplate-depth-256', '-Wno-unused-function', '-Wno-uninitialized', '-std=c++1y', '-DSTAN_THREADS', '-D_REENTRANT', ] + extra_compile_args extra_link_args = ['-Wl,-rpath,{}'.format(os.path.abspath(tbb_dir))] extension = Extension(name=module_name, language="c++", sources=[pyx_file], define_macros=stan_macros, include_dirs=include_dirs, libraries=["tbb"], library_dirs=[tbb_dir], extra_compile_args=extra_compile_args, extra_link_args=extra_link_args ) cython_include_dirs = ['.', pystan_dir] build_extension.extensions = cythonize([extension], include_path=cython_include_dirs, quiet=True) build_extension.build_temp = os.path.dirname(pyx_file) build_extension.build_lib = lib_dir build_extension.run() module = load_module(module_name, lib_dir) shutil.rmtree(lib_dir, ignore_errors=True) return module def get_module_name(path, open_func=None, open_kwargs=None): if open_func is None: open_func = io.open if open_kwargs is None: open_kwargs = {"mode" : "rb"} valid_chr = digits + ascii_letters + punctuation break_next = False name_loc = False module_name = "" with open_func(path, **open_kwargs) as f: # scan first few bytes for i in range(10000): byte, = f.read(1) if not PY2: byte = chr(byte) if name_loc and byte in valid_chr: module_name += byte if module_name == "stanfit": break_next = True elif byte == "s": module_name += byte name_loc = True elif break_next: break return module_name def unpickle_fit(path, open_func=None, open_kwargs=None, module_name=None, return_model=False): """Load pickled (compressed) fit object without model binary. Parameters ---------- path : str open_func : function Function that takes path and returns fileobject. E.g. `io.open`, `gzip.open`. open_kwargs : dict Keyword arguments for `open_func`. module_name : str, optional Module name used for the StanModel. By default module name is extractad from pickled file. return_model : bool Return the fake model. WARNING: Model should not be used for anything. Returns ------- StanFit4Model StanModel, optional Examples -------- >>> import pystan >>> import pystan.experimental >>> path = "path/to/fit.pickle" >>> fit = pystan.experimental.load_fit(path) Save fit to external format Transform fit to dataframe and save to csv >>> df = pystan.misc.to_dataframe(fit) >>> df.to_csv("path/to/fit.csv") Transform fit to arviz.InferenceData and save to netCDF4 >>> import arviz as az >>> idata = az.from_pystan(fit) >>> idata.to_netcdf("path/to/fit.nc") """ if module_name is None: module_name = get_module_name(path, open_func, open_kwargs) if not module_name: raise ValueError("Module name not found") # create fake model model = create_fake_model(module_name) if open_func is None: open_func = io.open if open_kwargs is None: open_kwargs = {"mode":"rb"} with open_func(path, **open_kwargs) as f: fit = pickle.load(f) if return_model: logger.warning("The model binary is built against fake model code. Model should not be used.") return fit, model return fit
7,885
Python
.py
206
29.135922
102
0.582984
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,039
misc.py
stan-dev_pystan2/pystan/experimental/misc.py
import logging import re import os logger = logging.getLogger('pystan') def fix_include(model_code): """Reformat `model_code` (remove whitespace) around the #include statements. Note ---- A modified `model_code` is returned. Parameters ---------- model_code : str Model code Returns ------- str Reformatted model code Example ------- >>> from pystan.experimental import fix_include >>> model_code = "parameters { #include myfile.stan \n..." >>> model_code_reformatted = fix_include(model_code) # "parameters {#include myfile.stan\n..." """ pattern = r"(?<=\n)\s*(#include)\s*(\S+)\s*(?=\n)" model_code, n = re.subn(pattern, r"\1 \2", model_code) if n == 1: msg = "Made {} substitution for the model_code" else: msg = "Made {} substitutions for the model_code" logger.info(msg.format(n)) return model_code
957
Python
.py
32
24.15625
80
0.608213
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,040
differences_pystan_rstan.rst
stan-dev_pystan2/doc/differences_pystan_rstan.rst
.. _differences-pystan-rstan: .. currentmodule:: pystan ====================================== Differences between PyStan and RStan ====================================== While PyStan attempts to maintain API compatibility with RStan, there are certain unavoidable differences between Python and R. Methods and attributes ====================== Methods are invoked in different ways: ``fit.summary()`` and ``fit.extract()`` (Python) vs. ``summary(fit)`` and ``extract(fit)`` (R). Attributes are accessed in a different manner as well: ``fit.sim`` (Python) vs. ``fit@sim`` (R). Dictionaries instead of Lists ============================= Where RStan uses lists, PyStan uses (ordered) dictionaries. Python: .. code-block:: python fit.extract()['theta'] R: .. code-block:: r extract(fit)$theta Reusing models and saving objects ================================= PyStan uses ``pickle`` to save objects for future use. Python: .. code-block:: python import pickle import pystan # bernoulli model model_code = """ data { int<lower=0> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { for (n in 1:N) y[n] ~ bernoulli(theta); } """ data = dict(N=10, y=[0, 1, 0, 0, 0, 0, 0, 0, 0, 1]) model = pystan.StanModel(model_code=model_code) fit = model.sampling(data=data) with open('model.pkl', 'wb') as f: pickle.dump(model, f, protocol=pickle.HIGHEST_PROTOCOL) # load it at some future point with open('model.pkl', 'rb') as f: model = pickle.load(f) # run with different data fit = model.sampling(data=dict(N=5, y=[1, 1, 0, 1, 0])) R: .. code-block:: r library(rstan) model = stan_model(model_code=model_code) save(model, file='model.rdata') See also :ref:`avoiding-recompilation`. If you are saving a large amount of data with ``pickle.dump``, be sure to use the highest protocol version available. Earlier versions are limited in the amount of data they can save in a single file.
2,128
Python
.py
62
29.693548
79
0.612475
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,041
conf.py
stan-dev_pystan2/doc/conf.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # PyStan documentation build configuration file, created by # sphinx-quickstart on Fri May 24 13:36:04 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) # Mock imports for readthedocs class Mock(object): def __init__(self, *args, **kwargs): pass def __call__(self, *args, **kwargs): return Mock() @classmethod def __getattr__(cls, name): if name in ('__file__', '__path__'): return '/dev/null' elif name[0] == name[0].upper(): mockType = type(name, (), {}) mockType.__module__ = __name__ return mockType else: return Mock() MOCK_MODULES = ['pystan._api', 'Cython', 'Cython.Build', 'Cython.Build.Inline', 'Cython.Build.Dependencies', 'numpy', 'numpy.ma'] for mod_name in MOCK_MODULES: sys.modules[mod_name] = Mock() # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', 'sphinx.ext.autosummary', 'sphinx.ext.napoleon' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'PyStan' copyright = '2013-2015, PyStan developers' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. import pystan # version = '%s r%s' % (pandas.__version__, svn_version()) version = '%s' % (pystan.__version__) # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinxdoc' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'PyStandoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto/manual]). latex_documents = [ ('index', 'PyStan.tex', 'PyStan Documentation', 'Allen B. Riddell', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pystan', 'PyStan Documentation', ['Allen B. Riddell'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'PyStan', 'PyStan Documentation', 'Allen B. Riddell', 'PyStan', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = 'PyStan' epub_author = 'Allen B. Riddell' epub_publisher = 'Allen B. Riddell' epub_copyright = '2013, Allen B. Riddell' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. #epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. #epub_exclude_files = [] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True # Choose between 'default' and 'includehidden'. #epub_tocscope = 'default' # Fix unsupported image types using the PIL. #epub_fix_images = False # Scale large images. #epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. #epub_show_urls = 'inline' # If false, no index is generated. #epub_use_index = True # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None}
10,880
Python
.py
264
39.113636
79
0.713783
stan-dev/pystan2
921
191
0
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
28,042
setup.py
arsenetar_dupeguru/setup.py
from setuptools import setup, Extension from pathlib import Path exts = [ Extension( "core.pe._block", [ str(Path("core", "pe", "modules", "block.c")), str(Path("core", "pe", "modules", "common.c")), ], include_dirs=[str(Path("core", "pe", "modules"))], ), Extension( "core.pe._cache", [ str(Path("core", "pe", "modules", "cache.c")), str(Path("core", "pe", "modules", "common.c")), ], include_dirs=[str(Path("core", "pe", "modules"))], ), Extension("qt.pe._block_qt", [str(Path("qt", "pe", "modules", "block.c"))]), ] headers = [str(Path("core", "pe", "modules", "common.h"))] setup(ext_modules=exts, headers=headers)
754
Python
.py
23
25.913043
80
0.519231
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,043
run.py
arsenetar_dupeguru/run.py
#!/usr/bin/python3 # Copyright 2017 Virgil Dupras # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import sys import os.path as op import gc from PyQt5.QtCore import QCoreApplication from PyQt5.QtGui import QIcon, QPixmap from PyQt5.QtWidgets import QApplication from hscommon.trans import install_gettext_trans_under_qt from qt.error_report_dialog import install_excepthook from qt.util import setup_qt_logging, create_qsettings from qt import dg_rc # noqa: F401 from qt.platform import BASE_PATH from core import __version__, __appname__ # SIGQUIT is not defined on Windows if sys.platform == "win32": from signal import signal, SIGINT, SIGTERM SIGQUIT = SIGTERM else: from signal import signal, SIGINT, SIGTERM, SIGQUIT global dgapp dgapp = None def signal_handler(sig, frame): global dgapp if dgapp is None: return if sig in (SIGINT, SIGTERM, SIGQUIT): dgapp.SIGTERM.emit() def setup_signals(): signal(SIGINT, signal_handler) signal(SIGTERM, signal_handler) signal(SIGQUIT, signal_handler) def main(): app = QApplication(sys.argv) QCoreApplication.setOrganizationName("Hardcoded Software") QCoreApplication.setApplicationName(__appname__) QCoreApplication.setApplicationVersion(__version__) setup_qt_logging() settings = create_qsettings() lang = settings.value("Language") locale_folder = op.join(BASE_PATH, "locale") install_gettext_trans_under_qt(locale_folder, lang) # Handle OS signals setup_signals() # Let the Python interpreter runs every 500ms to handle signals. This is # required because Python cannot handle signals while the Qt event loop is # running. from PyQt5.QtCore import QTimer timer = QTimer() timer.start(500) timer.timeout.connect(lambda: None) # Many strings are translated at import time, so this is why we only import after the translator # has been installed from qt.app import DupeGuru app.setWindowIcon(QIcon(QPixmap(f":/{DupeGuru.LOGO_NAME}"))) global dgapp dgapp = DupeGuru() install_excepthook("https://github.com/arsenetar/dupeguru/issues") result = app.exec() # I was getting weird crashes when quitting under Windows, and manually deleting main app # references with gc.collect() in between seems to fix the problem. del dgapp gc.collect() del app gc.collect() return result if __name__ == "__main__": sys.exit(main())
2,628
Python
.py
72
32.666667
100
0.741732
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,044
build.py
arsenetar_dupeguru/build.py
# Copyright 2017 Virgil Dupras # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from pathlib import Path import sys from optparse import OptionParser import shutil from multiprocessing import Pool from setuptools import sandbox from hscommon import sphinxgen from hscommon.build import ( add_to_pythonpath, print_and_do, fix_qt_resource_file, ) from hscommon import loc def parse_args(): usage = "usage: %prog [options]" parser = OptionParser(usage=usage) parser.add_option( "--clean", action="store_true", dest="clean", help="Clean build folder before building", ) parser.add_option("--doc", action="store_true", dest="doc", help="Build only the help file (en)") parser.add_option("--alldoc", action="store_true", dest="all_doc", help="Build only the help file in all languages") parser.add_option("--loc", action="store_true", dest="loc", help="Build only localization") parser.add_option( "--updatepot", action="store_true", dest="updatepot", help="Generate .pot files from source code.", ) parser.add_option( "--mergepot", action="store_true", dest="mergepot", help="Update all .po files based on .pot files.", ) parser.add_option( "--normpo", action="store_true", dest="normpo", help="Normalize all PO files (do this before commit).", ) parser.add_option( "--modules", action="store_true", dest="modules", help="Build the python modules.", ) (options, args) = parser.parse_args() return options def build_one_help(language): print(f"Generating Help in {language}") current_path = Path(".").absolute() changelog_path = current_path.joinpath("help", "changelog") tixurl = "https://github.com/arsenetar/dupeguru/issues/{}" changelogtmpl = current_path.joinpath("help", "changelog.tmpl") conftmpl = current_path.joinpath("help", "conf.tmpl") help_basepath = current_path.joinpath("help", language) help_destpath = current_path.joinpath("build", "help", language) confrepl = {"language": language} sphinxgen.gen( help_basepath, help_destpath, changelog_path, tixurl, confrepl, conftmpl, changelogtmpl, ) def build_help(): languages = ["en", "de", "fr", "hy", "ru", "uk"] # Running with Pools as for some reason sphinx seems to cross contaminate the output otherwise with Pool(len(languages)) as p: p.map(build_one_help, languages) def build_localizations(): loc.compile_all_po("locale") locale_dest = Path("build", "locale") if locale_dest.exists(): shutil.rmtree(locale_dest) shutil.copytree("locale", locale_dest, ignore=shutil.ignore_patterns("*.po", "*.pot")) def build_updatepot(): print("Building .pot files from source files") print("Building core.pot") loc.generate_pot(["core"], Path("locale", "core.pot"), ["tr"]) print("Building columns.pot") loc.generate_pot(["core"], Path("locale", "columns.pot"), ["coltr"]) print("Building ui.pot") loc.generate_pot(["qt"], Path("locale", "ui.pot"), ["tr"], merge=True) def build_mergepot(): print("Updating .po files using .pot files") loc.merge_pots_into_pos("locale") def build_normpo(): loc.normalize_all_pos("locale") def build_pe_modules(): print("Building PE Modules") # Leverage setup.py to build modules sandbox.run_setup("setup.py", ["build_ext", "--inplace"]) def build_normal(): print("Building dupeGuru with UI qt") add_to_pythonpath(".") print("Building dupeGuru") build_pe_modules() print("Building localizations") build_localizations() print("Building Qt stuff") Path("qt", "dg_rc.py").unlink(missing_ok=True) print_and_do("pyrcc5 {} > {}".format(Path("qt", "dg.qrc"), Path("qt", "dg_rc.py"))) fix_qt_resource_file(Path("qt", "dg_rc.py")) build_help() def main(): if sys.version_info < (3, 7): sys.exit("Python < 3.7 is unsupported.") options = parse_args() if options.clean and Path("build").exists(): shutil.rmtree("build") if not Path("build").exists(): Path("build").mkdir() if options.doc: build_one_help("en") elif options.all_doc: build_help() elif options.loc: build_localizations() elif options.updatepot: build_updatepot() elif options.mergepot: build_mergepot() elif options.normpo: build_normpo() elif options.modules: build_pe_modules() else: build_normal() if __name__ == "__main__": main()
4,878
Python
.py
141
29.028369
120
0.645873
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,045
copyright
arsenetar_dupeguru/pkg/debian/copyright
Copyright 2014 Hardcoded Software Inc. (http://www.hardcoded.net) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Hardcoded Software Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * If the source code has been published less than two years ago, any redistribution, in whole or in part, must retain full licensing functionality, without any attempt to change, obscure or in other ways circumvent its intent. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1,757
Python
.py
8
216.25
755
0.813288
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,046
build_pe_modules.py
arsenetar_dupeguru/pkg/debian/build_pe_modules.py
import sys import os import os.path as op import shutil import importlib from setuptools import setup, Extension sys.path.insert(1, op.abspath("src")) from hscommon.build import move_all exts = [ Extension("_block", [op.join("modules", "block.c"), op.join("modules", "common.c")]), Extension("_cache", [op.join("modules", "cache.c"), op.join("modules", "common.c")]), Extension("_block_qt", [op.join("modules", "block_qt.c")]), ] setup( script_args=["build_ext", "--inplace"], ext_modules=exts, ) move_all("_block_qt*", op.join("src", "qt", "pe")) move_all("_cache*", op.join("src", "core/pe")) move_all("_block*", op.join("src", "core/pe"))
666
Python
.py
20
31.1
89
0.657321
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,047
progress_window.py
arsenetar_dupeguru/qt/progress_window.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import Qt, QTimer from PyQt5.QtWidgets import QDialog, QMessageBox, QVBoxLayout, QLabel, QProgressBar, QPushButton from hscommon.trans import tr class ProgressWindow: def __init__(self, parent, model): self._window = None self.parent = parent self.model = model model.view = self # We don't have access to QProgressDialog's labels directly, so we se the model label's view # to self and we'll refresh them together. self.model.jobdesc_textfield.view = self self.model.progressdesc_textfield.view = self # --- Callbacks def refresh(self): # Labels if self._window is not None: self._window.setWindowTitle(self.model.jobdesc_textfield.text) self._label.setText(self.model.progressdesc_textfield.text) def set_progress(self, last_progress): if self._window is not None: if last_progress < 0: self._progress_bar.setRange(0, 0) else: self._progress_bar.setRange(0, 100) self._progress_bar.setValue(last_progress) def show(self): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint self._window = QDialog(self.parent, flags) self._setup_ui() self._window.setModal(True) self._timer = QTimer(self._window) self._timer.timeout.connect(self.model.pulse) self._window.show() self._timer.start(500) def _setup_ui(self): self._window.setWindowTitle(tr("Cancel")) vertical_layout = QVBoxLayout(self._window) self._label = QLabel("", self._window) vertical_layout.addWidget(self._label) self._progress_bar = QProgressBar(self._window) self._progress_bar.setRange(0, 100) vertical_layout.addWidget(self._progress_bar) self._cancel_button = QPushButton(tr("Cancel"), self._window) self._cancel_button.clicked.connect(self.cancel) vertical_layout.addWidget(self._cancel_button) def cancel(self): if self._window is not None: confirm_dialog = QMessageBox( QMessageBox.Icon.Question, tr("Cancel?"), tr("Are you sure you want to cancel? All progress will be lost."), QMessageBox.StandardButton.No | QMessageBox.StandardButton.Yes, self._window, ) confirm_dialog.setDefaultButton(QMessageBox.StandardButton.No) result = confirm_dialog.exec_() if result != QMessageBox.StandardButton.Yes: return self.close() def close(self): # it seems it is possible for close to be called without a corresponding # show, only perform a close if there is a window to close if self._window is not None: self._timer.stop() del self._timer self._window.close() self._window.setParent(None) self._window = None self.model.cancel()
3,337
Python
.py
74
35.635135
100
0.641254
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,048
ignore_list_table.py
arsenetar_dupeguru/qt/ignore_list_table.py
# Created On: 2012-03-13 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from qt.column import Column from qt.table import Table class IgnoreListTable(Table): """Ignore list model""" COLUMNS = [ Column("path1", default_width=230), Column("path2", default_width=230), ]
529
Python
.py
14
34.5
89
0.727984
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,049
directories_model.py
arsenetar_dupeguru/qt/directories_model.py
# Created By: Virgil Dupras # Created On: 2009-04-25 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import pyqtSignal, Qt, QRect, QUrl, QModelIndex, QItemSelection from PyQt5.QtWidgets import ( QComboBox, QStyledItemDelegate, QStyle, QStyleOptionComboBox, QStyleOptionViewItem, QApplication, ) from PyQt5.QtGui import QBrush from hscommon.trans import trget from qt.tree_model import RefNode, TreeModel tr = trget("ui") HEADERS = [tr("Name"), tr("State")] STATES = [tr("Normal"), tr("Reference"), tr("Excluded")] class DirectoriesDelegate(QStyledItemDelegate): def createEditor(self, parent, option, index): editor = QComboBox(parent) editor.addItems(STATES) return editor def paint(self, painter, option, index): self.initStyleOption(option, index) # No idea why, but this cast is required if we want to have access to the V4 valuess option = QStyleOptionViewItem(option) if (index.column() == 1) and (option.state & QStyle.State_Selected): cboption = QStyleOptionComboBox() cboption.rect = option.rect # On OS X (with Qt4.6.0), adding State_Enabled to the flags causes the whole drawing to # fail (draw nothing), but it's an OS X only glitch. On Windows, it works alright. cboption.state |= QStyle.State_Enabled QApplication.style().drawComplexControl(QStyle.CC_ComboBox, cboption, painter) painter.setBrush(option.palette.text()) rect = QRect(option.rect) rect.setLeft(rect.left() + 4) painter.drawText(rect, Qt.AlignLeft, option.text) else: super().paint(painter, option, index) def setEditorData(self, editor, index): value = index.model().data(index, Qt.EditRole) editor.setCurrentIndex(value) editor.showPopup() def setModelData(self, editor, model, index): value = editor.currentIndex() model.setData(index, value, Qt.EditRole) def updateEditorGeometry(self, editor, option, index): editor.setGeometry(option.rect) class DirectoriesModel(TreeModel): MIME_TYPE_FORMAT = "text/uri-list" def __init__(self, model, view, **kwargs): super().__init__(**kwargs) self.model = model self.model.view = self self.view = view self.view.setModel(self) self.view.selectionModel().selectionChanged[(QItemSelection, QItemSelection)].connect(self.selectionChanged) def _create_node(self, ref, row): return RefNode(self, None, ref, row) def _get_children(self): return list(self.model) def columnCount(self, parent=QModelIndex()): return 2 def data(self, index, role): if not index.isValid(): return None node = index.internalPointer() ref = node.ref if role == Qt.DisplayRole: if index.column() == 0: return ref.name else: return STATES[ref.state] elif role == Qt.EditRole and index.column() == 1: return ref.state elif role == Qt.ForegroundRole: state = ref.state if state == 1: return QBrush(Qt.blue) elif state == 2: return QBrush(Qt.red) return None def dropMimeData(self, mime_data, action, row, column, parent_index): # the data in mimeData is urlencoded **in utf-8** if not mime_data.hasFormat(self.MIME_TYPE_FORMAT): return False data = bytes(mime_data.data(self.MIME_TYPE_FORMAT)).decode("ascii") urls = data.split("\r\n") paths = [QUrl(url).toLocalFile() for url in urls if url] for path in paths: self.model.add_directory(path) self.foldersAdded.emit(paths) self.reset() return True def flags(self, index): if not index.isValid(): return Qt.ItemIsEnabled | Qt.ItemIsDropEnabled result = Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDropEnabled if index.column() == 1: result |= Qt.ItemIsEditable return result def headerData(self, section, orientation, role): if orientation == Qt.Horizontal and role == Qt.DisplayRole and section < len(HEADERS): return HEADERS[section] return None def mimeTypes(self): return [self.MIME_TYPE_FORMAT] def setData(self, index, value, role): if not index.isValid() or role != Qt.EditRole or index.column() != 1: return False node = index.internalPointer() ref = node.ref ref.state = value return True def supportedDropActions(self): # Normally, the correct action should be ActionLink, but the drop doesn't work. It doesn't # work with ActionMove either. So screw that, and accept anything. return Qt.ActionMask # --- Events def selectionChanged(self, selected, deselected): new_nodes = [modelIndex.internalPointer().ref for modelIndex in self.view.selectionModel().selectedRows()] self.model.selected_nodes = new_nodes # --- Signals foldersAdded = pyqtSignal(list) # --- model --> view def refresh(self): self.reset() def refresh_states(self): self.refreshData()
5,614
Python
.py
134
33.701493
116
0.647102
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,050
preferences_dialog.py
arsenetar_dupeguru/qt/preferences_dialog.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import Qt, QSize, pyqtSlot from PyQt5.QtWidgets import ( QDialog, QDialogButtonBox, QVBoxLayout, QHBoxLayout, QGridLayout, QLabel, QComboBox, QSlider, QSizePolicy, QSpacerItem, QCheckBox, QLineEdit, QMessageBox, QSpinBox, QLayout, QTabWidget, QWidget, QColorDialog, QPushButton, QGroupBox, QFormLayout, ) from PyQt5.QtGui import QPixmap, QIcon from hscommon import desktop, plat from hscommon.trans import trget from hscommon.plat import ISLINUX from qt.util import horizontal_wrap, move_to_screen_center from qt.preferences import get_langnames from enum import Flag, auto from qt.preferences import Preferences tr = trget("ui") class Sections(Flag): """Filter blocks of preferences when reset or loaded""" GENERAL = auto() DISPLAY = auto() ADVANCED = auto() DEBUG = auto() ALL = GENERAL | DISPLAY | ADVANCED | DEBUG class PreferencesDialogBase(QDialog): def __init__(self, parent, app, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self.app = app self.supportedLanguages = dict(sorted(get_langnames().items(), key=lambda item: item[1])) self._setupUi() self.filterHardnessSlider.valueChanged["int"].connect(self.filterHardnessLabel.setNum) self.debug_location_label.linkActivated.connect(desktop.open_path) self.buttonBox.clicked.connect(self.buttonClicked) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def _setupFilterHardnessBox(self): self.filterHardnessHLayout = QHBoxLayout() self.filterHardnessLabel = QLabel(self) self.filterHardnessLabel.setText(tr("Filter Hardness:")) self.filterHardnessLabel.setMinimumSize(QSize(0, 0)) self.filterHardnessHLayout.addWidget(self.filterHardnessLabel) self.filterHardnessVLayout = QVBoxLayout() self.filterHardnessVLayout.setSpacing(0) self.filterHardnessHLayoutSub1 = QHBoxLayout() self.filterHardnessHLayoutSub1.setSpacing(12) self.filterHardnessSlider = QSlider(self) size_policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) size_policy.setHorizontalStretch(0) size_policy.setVerticalStretch(0) size_policy.setHeightForWidth(self.filterHardnessSlider.sizePolicy().hasHeightForWidth()) self.filterHardnessSlider.setSizePolicy(size_policy) self.filterHardnessSlider.setMinimum(1) self.filterHardnessSlider.setMaximum(100) self.filterHardnessSlider.setTracking(True) self.filterHardnessSlider.setOrientation(Qt.Horizontal) self.filterHardnessHLayoutSub1.addWidget(self.filterHardnessSlider) self.filterHardnessLabel = QLabel(self) self.filterHardnessLabel.setText("100") self.filterHardnessLabel.setMinimumSize(QSize(21, 0)) self.filterHardnessHLayoutSub1.addWidget(self.filterHardnessLabel) self.filterHardnessVLayout.addLayout(self.filterHardnessHLayoutSub1) self.filterHardnessHLayoutSub2 = QHBoxLayout() self.filterHardnessHLayoutSub2.setContentsMargins(-1, 0, -1, -1) self.moreResultsLabel = QLabel(self) self.moreResultsLabel.setText(tr("More Results")) self.filterHardnessHLayoutSub2.addWidget(self.moreResultsLabel) spacer_item = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.filterHardnessHLayoutSub2.addItem(spacer_item) self.fewerResultsLabel = QLabel(self) self.fewerResultsLabel.setText(tr("Fewer Results")) self.filterHardnessHLayoutSub2.addWidget(self.fewerResultsLabel) self.filterHardnessVLayout.addLayout(self.filterHardnessHLayoutSub2) self.filterHardnessHLayout.addLayout(self.filterHardnessVLayout) def _setupBottomPart(self): # The bottom part of the pref panel is always the same in all editions. self.copyMoveLabel = QLabel(self) self.copyMoveLabel.setText(tr("Copy and Move:")) self.widgetsVLayout.addWidget(self.copyMoveLabel) self.copyMoveDestinationComboBox = QComboBox(self) self.copyMoveDestinationComboBox.addItem(tr("Right in destination")) self.copyMoveDestinationComboBox.addItem(tr("Recreate relative path")) self.copyMoveDestinationComboBox.addItem(tr("Recreate absolute path")) self.widgetsVLayout.addWidget(self.copyMoveDestinationComboBox) self.customCommandLabel = QLabel(self) self.customCommandLabel.setText(tr("Custom Command (arguments: %d for dupe, %r for ref):")) self.widgetsVLayout.addWidget(self.customCommandLabel) self.customCommandEdit = QLineEdit(self) self.widgetsVLayout.addWidget(self.customCommandEdit) def _setupDisplayPage(self): self.ui_groupbox = QGroupBox("&" + tr("General Interface")) layout = QVBoxLayout() self.languageLabel = QLabel(tr("Language:"), self) self.languageComboBox = QComboBox(self) for lang_code, lang_str in self.supportedLanguages.items(): self.languageComboBox.addItem(lang_str, userData=lang_code) layout.addLayout(horizontal_wrap([self.languageLabel, self.languageComboBox, None])) self._setupAddCheckbox( "tabs_default_pos", tr("Use default position for tab bar (requires restart)"), ) self.tabs_default_pos.setToolTip( tr( "Place the tab bar below the main menu instead of next to it\n\ On MacOS, the tab bar will fill up the window's width instead." ) ) layout.addWidget(self.tabs_default_pos) self._setupAddCheckbox( "use_native_dialogs", tr("Use native OS dialogs"), ) self.use_native_dialogs.setToolTip( tr( "For actions such as file/folder selection use the OS native dialogs.\n\ Some native dialogs have limited functionality." ) ) layout.addWidget(self.use_native_dialogs) if plat.ISWINDOWS: self._setupAddCheckbox("use_dark_style", tr("Use dark style")) layout.addWidget(self.use_dark_style) self.ui_groupbox.setLayout(layout) self.displayVLayout.addWidget(self.ui_groupbox) gridlayout = QGridLayout() gridlayout.setColumnStretch(2, 2) formlayout = QFormLayout() result_groupbox = QGroupBox("&" + tr("Result Table")) self.fontSizeSpinBox = QSpinBox() self.fontSizeSpinBox.setMinimum(5) formlayout.addRow(tr("Font size:"), self.fontSizeSpinBox) self._setupAddCheckbox("reference_bold_font", tr("Use bold font for references")) formlayout.addRow(self.reference_bold_font) self.result_table_ref_foreground_color = ColorPickerButton(self) formlayout.addRow(tr("Reference foreground color:"), self.result_table_ref_foreground_color) self.result_table_ref_background_color = ColorPickerButton(self) formlayout.addRow(tr("Reference background color:"), self.result_table_ref_background_color) self.result_table_delta_foreground_color = ColorPickerButton(self) formlayout.addRow(tr("Delta foreground color:"), self.result_table_delta_foreground_color) formlayout.setLabelAlignment(Qt.AlignLeft) # Keep same vertical spacing as parent layout for consistency formlayout.setVerticalSpacing(self.displayVLayout.spacing()) gridlayout.addLayout(formlayout, 0, 0) result_groupbox.setLayout(gridlayout) self.displayVLayout.addWidget(result_groupbox) details_groupbox = QGroupBox("&" + tr("Details Window")) self.details_groupbox_layout = QVBoxLayout() self._setupAddCheckbox( "details_dialog_titlebar_enabled", tr("Show the title bar and can be docked"), ) self.details_dialog_titlebar_enabled.setToolTip( tr( "While the title bar is hidden, \ use the modifier key to drag the floating window around" ) if ISLINUX else tr("The title bar can only be disabled while the window is docked") ) self.details_groupbox_layout.addWidget(self.details_dialog_titlebar_enabled) self._setupAddCheckbox("details_dialog_vertical_titlebar", tr("Vertical title bar")) self.details_dialog_vertical_titlebar.setToolTip( tr("Change the title bar from horizontal on top, to vertical on the left side") ) self.details_groupbox_layout.addWidget(self.details_dialog_vertical_titlebar) self.details_dialog_vertical_titlebar.setEnabled(self.details_dialog_titlebar_enabled.isChecked()) self.details_dialog_titlebar_enabled.stateChanged.connect(self.details_dialog_vertical_titlebar.setEnabled) gridlayout = QGridLayout() formlayout = QFormLayout() self.details_table_delta_foreground_color = ColorPickerButton(self) # Padding on the right side and space between label and widget to keep it somewhat consistent across themes gridlayout.setColumnStretch(1, 1) formlayout.setHorizontalSpacing(50) formlayout.addRow(tr("Delta foreground color:"), self.details_table_delta_foreground_color) gridlayout.addLayout(formlayout, 0, 0) self.details_groupbox_layout.addLayout(gridlayout) details_groupbox.setLayout(self.details_groupbox_layout) self.displayVLayout.addWidget(details_groupbox) def _setup_advanced_page(self): tab_label = QLabel( tr( "These options are for advanced users or for very specific situations, \ most users should not have to modify these." ), wordWrap=True, ) self.advanced_vlayout.addWidget(tab_label) self._setupAddCheckbox("include_exists_check_box", tr("Include existence check after scan completion")) self.advanced_vlayout.addWidget(self.include_exists_check_box) self._setupAddCheckbox("rehash_ignore_mtime_box", tr("Ignore difference in mtime when loading cached digests")) self.advanced_vlayout.addWidget(self.rehash_ignore_mtime_box) def _setupDebugPage(self): self._setupAddCheckbox("debugModeBox", tr("Debug mode (restart required)")) self._setupAddCheckbox("profile_scan_box", tr("Profile scan operation")) self.profile_scan_box.setToolTip(tr("Profile the scan operation and save logs for optimization.")) self.debugVLayout.addWidget(self.debugModeBox) self.debugVLayout.addWidget(self.profile_scan_box) self.debug_location_label = QLabel( tr('Logs located in: <a href="{}">{}</a>').format(self.app.model.appdata, self.app.model.appdata), wordWrap=True, ) self.debugVLayout.addWidget(self.debug_location_label) def _setupAddCheckbox(self, name, label, parent=None): if parent is None: parent = self cb = QCheckBox(parent) cb.setText(label) setattr(self, name, cb) def _setupPreferenceWidgets(self): # Edition-specific pass def _setupUi(self): self.setWindowTitle(tr("Options")) self.setSizeGripEnabled(False) self.setModal(True) self.mainVLayout = QVBoxLayout(self) self.tabwidget = QTabWidget() self.page_general = QWidget() self.page_display = QWidget() self.page_advanced = QWidget() self.page_debug = QWidget() self.widgetsVLayout = QVBoxLayout() self.page_general.setLayout(self.widgetsVLayout) self.displayVLayout = QVBoxLayout() self.displayVLayout.setSpacing(5) # arbitrary value, might conflict with style self.page_display.setLayout(self.displayVLayout) self.advanced_vlayout = QVBoxLayout() self.page_advanced.setLayout(self.advanced_vlayout) self.debugVLayout = QVBoxLayout() self.page_debug.setLayout(self.debugVLayout) self._setupPreferenceWidgets() self._setupDisplayPage() self._setup_advanced_page() self._setupDebugPage() # self.mainVLayout.addLayout(self.widgetsVLayout) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setStandardButtons( QDialogButtonBox.Cancel | QDialogButtonBox.Ok | QDialogButtonBox.RestoreDefaults ) self.mainVLayout.addWidget(self.tabwidget) self.mainVLayout.addWidget(self.buttonBox) self.layout().setSizeConstraint(QLayout.SetFixedSize) self.tabwidget.addTab(self.page_general, tr("General")) self.tabwidget.addTab(self.page_display, tr("Display")) self.tabwidget.addTab(self.page_advanced, tr("Advanced")) self.tabwidget.addTab(self.page_debug, tr("Debug")) self.displayVLayout.addStretch(0) self.widgetsVLayout.addStretch(0) self.advanced_vlayout.addStretch(0) self.debugVLayout.addStretch(0) def _load(self, prefs, setchecked, section): # Edition-specific pass def _save(self, prefs, ischecked): # Edition-specific pass def load(self, prefs=None, section=Sections.ALL): if prefs is None: prefs = self.app.prefs def setchecked(cb, b): cb.setCheckState(Qt.Checked if b else Qt.Unchecked) if section & Sections.GENERAL: self.filterHardnessSlider.setValue(prefs.filter_hardness) self.filterHardnessLabel.setNum(prefs.filter_hardness) setchecked(self.mixFileKindBox, prefs.mix_file_kind) setchecked(self.useRegexpBox, prefs.use_regexp) setchecked(self.removeEmptyFoldersBox, prefs.remove_empty_folders) setchecked(self.ignoreHardlinkMatches, prefs.ignore_hardlink_matches) self.copyMoveDestinationComboBox.setCurrentIndex(prefs.destination_type) self.customCommandEdit.setText(prefs.custom_command) if section & Sections.DISPLAY: setchecked(self.reference_bold_font, prefs.reference_bold_font) setchecked(self.tabs_default_pos, prefs.tabs_default_pos) setchecked(self.use_native_dialogs, prefs.use_native_dialogs) if plat.ISWINDOWS: setchecked(self.use_dark_style, prefs.use_dark_style) setchecked( self.details_dialog_titlebar_enabled, prefs.details_dialog_titlebar_enabled, ) setchecked( self.details_dialog_vertical_titlebar, prefs.details_dialog_vertical_titlebar, ) self.fontSizeSpinBox.setValue(prefs.tableFontSize) self.details_table_delta_foreground_color.setColor(prefs.details_table_delta_foreground_color) self.result_table_ref_foreground_color.setColor(prefs.result_table_ref_foreground_color) self.result_table_ref_background_color.setColor(prefs.result_table_ref_background_color) self.result_table_delta_foreground_color.setColor(prefs.result_table_delta_foreground_color) try: selected_lang = self.supportedLanguages[self.app.prefs.language] except KeyError: selected_lang = self.supportedLanguages["en"] self.languageComboBox.setCurrentText(selected_lang) if section & Sections.ADVANCED: setchecked(self.rehash_ignore_mtime_box, prefs.rehash_ignore_mtime) setchecked(self.include_exists_check_box, prefs.include_exists_check) if section & Sections.DEBUG: setchecked(self.debugModeBox, prefs.debug_mode) setchecked(self.profile_scan_box, prefs.profile_scan) self._load(prefs, setchecked, section) def save(self): prefs = self.app.prefs prefs.filter_hardness = self.filterHardnessSlider.value() def ischecked(cb): return cb.checkState() == Qt.Checked prefs.mix_file_kind = ischecked(self.mixFileKindBox) prefs.use_regexp = ischecked(self.useRegexpBox) prefs.remove_empty_folders = ischecked(self.removeEmptyFoldersBox) prefs.ignore_hardlink_matches = ischecked(self.ignoreHardlinkMatches) prefs.rehash_ignore_mtime = ischecked(self.rehash_ignore_mtime_box) prefs.include_exists_check = ischecked(self.include_exists_check_box) prefs.debug_mode = ischecked(self.debugModeBox) prefs.profile_scan = ischecked(self.profile_scan_box) prefs.reference_bold_font = ischecked(self.reference_bold_font) prefs.details_dialog_titlebar_enabled = ischecked(self.details_dialog_titlebar_enabled) prefs.details_dialog_vertical_titlebar = ischecked(self.details_dialog_vertical_titlebar) prefs.details_table_delta_foreground_color = self.details_table_delta_foreground_color.color prefs.result_table_ref_foreground_color = self.result_table_ref_foreground_color.color prefs.result_table_ref_background_color = self.result_table_ref_background_color.color prefs.result_table_delta_foreground_color = self.result_table_delta_foreground_color.color prefs.destination_type = self.copyMoveDestinationComboBox.currentIndex() prefs.custom_command = str(self.customCommandEdit.text()) prefs.tableFontSize = self.fontSizeSpinBox.value() prefs.tabs_default_pos = ischecked(self.tabs_default_pos) prefs.use_native_dialogs = ischecked(self.use_native_dialogs) if plat.ISWINDOWS: prefs.use_dark_style = ischecked(self.use_dark_style) lang_code = self.languageComboBox.currentData() old_lang_code = self.app.prefs.language if old_lang_code not in self.supportedLanguages.keys(): old_lang_code = "en" if lang_code != old_lang_code: QMessageBox.information( self, "", tr("dupeGuru has to restart for language changes to take effect."), ) self.app.prefs.language = lang_code self._save(prefs, ischecked) def resetToDefaults(self, section_to_update): self.load(Preferences(), section_to_update) # --- Events def buttonClicked(self, button): role = self.buttonBox.buttonRole(button) if role == QDialogButtonBox.ResetRole: current_tab = self.tabwidget.currentWidget() section_to_update = Sections.ALL if current_tab is self.page_general: section_to_update = Sections.GENERAL if current_tab is self.page_display: section_to_update = Sections.DISPLAY if current_tab is self.page_debug: section_to_update = Sections.DEBUG self.resetToDefaults(section_to_update) def showEvent(self, event): # have to do this here as the frameGeometry is not correct until shown move_to_screen_center(self) super().showEvent(event) class ColorPickerButton(QPushButton): def __init__(self, parent): super().__init__(parent) self.parent = parent self.color = None self.clicked.connect(self.onClicked) @pyqtSlot() def onClicked(self): color = QColorDialog.getColor(self.color if self.color is not None else Qt.white, self.parent) self.setColor(color) def setColor(self, color): size = QSize(16, 16) px = QPixmap(size) if color is None: size.width = 0 size.height = 0 elif not color.isValid(): return else: self.color = color px.fill(color) self.setIcon(QIcon(px))
20,141
Python
.py
402
40.920398
119
0.691656
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,051
util.py
arsenetar_dupeguru/qt/util.py
# Created By: Virgil Dupras # Created On: 2011-02-01 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import sys import io import os.path as op import os import logging from core.util import executable_folder from hscommon.util import first from hscommon.plat import ISWINDOWS from PyQt5.QtCore import QStandardPaths, QSettings from PyQt5.QtGui import QPixmap, QIcon, QGuiApplication from PyQt5.QtWidgets import ( QSpacerItem, QSizePolicy, QAction, QHBoxLayout, ) def move_to_screen_center(widget): frame = widget.frameGeometry() if QGuiApplication.screenAt(frame.center()) is None: # if center not on any screen use default screen screen = QGuiApplication.screens()[0].availableGeometry() else: screen = QGuiApplication.screenAt(frame.center()).availableGeometry() # moves to center of screen if partially off screen if screen.contains(frame) is False: # make sure the frame is not larger than screen # resize does not seem to take frame size into account (move does) widget.resize(frame.size().boundedTo(screen.size() - (frame.size() - widget.size()))) frame = widget.frameGeometry() frame.moveCenter(screen.center()) widget.move(frame.topLeft()) def vertical_spacer(size=None): if size: return QSpacerItem(1, size, QSizePolicy.Fixed, QSizePolicy.Fixed) else: return QSpacerItem(1, 1, QSizePolicy.Fixed, QSizePolicy.MinimumExpanding) def horizontal_spacer(size=None): if size: return QSpacerItem(size, 1, QSizePolicy.Fixed, QSizePolicy.Fixed) else: return QSpacerItem(1, 1, QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) def horizontal_wrap(widgets): """Wrap all widgets in `widgets` in a horizontal layout. If, instead of placing a widget in your list, you place an int or None, an horizontal spacer with the width corresponding to the int will be placed (0 or None means an expanding spacer). """ layout = QHBoxLayout() for widget in widgets: if widget is None or isinstance(widget, int): layout.addItem(horizontal_spacer(size=widget)) else: layout.addWidget(widget) return layout def create_actions(actions, target): # actions are list of (name, shortcut, icon, desc, func) for name, shortcut, icon, desc, func in actions: action = QAction(target) if icon: action.setIcon(QIcon(QPixmap(":/" + icon))) if shortcut: action.setShortcut(shortcut) action.setText(desc) action.triggered.connect(func) setattr(target, name, action) def set_accel_keys(menu): actions = menu.actions() titles = [a.text() for a in actions] available_characters = {c.lower() for s in titles for c in s if c.isalpha()} for action in actions: text = action.text() c = first(c for c in text if c.lower() in available_characters) if c is None: continue i = text.index(c) newtext = text[:i] + "&" + text[i:] available_characters.remove(c.lower()) action.setText(newtext) def get_appdata(portable=False): if portable: return op.join(executable_folder(), "data") else: return QStandardPaths.standardLocations(QStandardPaths.AppDataLocation)[0] class SysWrapper(io.IOBase): def write(self, s): if s.strip(): # don't log empty stuff logging.warning(s) def setup_qt_logging(level=logging.WARNING, log_to_stdout=False): # Under Qt, we log in "debug.log" in appdata. Moreover, when under cx_freeze, we have a # problem because sys.stdout and sys.stderr are None, so we need to replace them with a # wrapper that logs with the logging module. appdata = get_appdata() if not op.exists(appdata): os.makedirs(appdata) # Setup logging # Have to use full configuration over basicConfig as FileHandler encoding was not being set. filename = op.join(appdata, "debug.log") if not log_to_stdout else None log = logging.getLogger() handler = logging.FileHandler(filename, "a", "utf-8") formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) log.addHandler(handler) if sys.stderr is None: # happens under a cx_freeze environment sys.stderr = SysWrapper() if sys.stdout is None: sys.stdout = SysWrapper() def escape_amp(s): # Returns `s` with escaped ampersand (& --> &&). QAction text needs to have & escaped because # that character is used to define "accel keys". return s.replace("&", "&&") def create_qsettings(): # Create a QSettings instance with the correct arguments. config_location = op.join(executable_folder(), "settings.ini") if op.isfile(config_location): settings = QSettings(config_location, QSettings.IniFormat) settings.setValue("Portable", True) elif ISWINDOWS: # On windows use an ini file in the AppDataLocation instead of registry if possible as it # makes it easier for a user to clear it out when there are issues. locations = QStandardPaths.standardLocations(QStandardPaths.AppDataLocation) if locations: settings = QSettings(op.join(locations[0], "settings.ini"), QSettings.IniFormat) else: settings = QSettings() settings.setValue("Portable", False) else: settings = QSettings() settings.setValue("Portable", False) return settings
5,781
Python
.py
135
36.740741
97
0.695196
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,052
recent.py
arsenetar_dupeguru/qt/recent.py
# Created By: Virgil Dupras # Created On: 2009-11-12 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from collections import namedtuple from PyQt5.QtCore import pyqtSignal, QObject from PyQt5.QtWidgets import QAction from hscommon.trans import trget from hscommon.util import dedupe tr = trget("ui") MenuEntry = namedtuple("MenuEntry", "menu fixedItemCount") class Recent(QObject): def __init__(self, app, pref_name, max_item_count=10, **kwargs): super().__init__(**kwargs) self._app = app self._menuEntries = [] self._prefName = pref_name self._maxItemCount = max_item_count self._items = [] self._loadFromPrefs() self._app.willSavePrefs.connect(self._saveToPrefs) # --- Private def _loadFromPrefs(self): items = getattr(self._app.prefs, self._prefName) if not isinstance(items, list): items = [] self._items = items def _insertItem(self, item): self._items = dedupe([item] + self._items)[: self._maxItemCount] def _refreshMenu(self, menu_entry): menu, fixed_item_count = menu_entry for action in menu.actions()[fixed_item_count:]: menu.removeAction(action) for item in self._items: action = QAction(item, menu) action.setData(item) action.triggered.connect(self.menuItemWasClicked) menu.addAction(action) menu.addSeparator() action = QAction(tr("Clear List"), menu) action.triggered.connect(self.clear) menu.addAction(action) def _refreshAllMenus(self): for menu_entry in self._menuEntries: self._refreshMenu(menu_entry) def _saveToPrefs(self): setattr(self._app.prefs, self._prefName, self._items) # --- Public def addMenu(self, menu): menu_entry = MenuEntry(menu, len(menu.actions())) self._menuEntries.append(menu_entry) self._refreshMenu(menu_entry) def clear(self): self._items = [] self._refreshAllMenus() self.itemsChanged.emit() def insertItem(self, item): self._insertItem(str(item)) self._refreshAllMenus() self.itemsChanged.emit() def isEmpty(self): return not bool(self._items) # --- Event Handlers def menuItemWasClicked(self): action = self.sender() if action is not None: item = action.data() self.mustOpenItem.emit(item) self._refreshAllMenus() # --- Signals mustOpenItem = pyqtSignal(str) itemsChanged = pyqtSignal()
2,835
Python
.py
75
30.52
89
0.648304
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,053
exclude_list_table.py
arsenetar_dupeguru/qt/exclude_list_table.py
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import Qt from PyQt5.QtGui import QFont, QFontMetrics, QIcon, QColor from qt.column import Column from qt.table import Table from hscommon.trans import trget tr = trget("ui") class ExcludeListTable(Table): """Model for exclude list""" COLUMNS = [Column("marked", default_width=15), Column("regex", default_width=230)] def __init__(self, app, view, **kwargs): model = app.model.exclude_list_dialog.exclude_list_table # pointer to GUITable super().__init__(model, view, **kwargs) font = view.font() font.setPointSize(app.prefs.tableFontSize) view.setFont(font) fm = QFontMetrics(font) view.verticalHeader().setDefaultSectionSize(fm.height() + 2) def _getData(self, row, column, role): if column.name == "marked": if role == Qt.CheckStateRole and row.markable: return Qt.Checked if row.marked else Qt.Unchecked if role == Qt.ToolTipRole and not row.markable: return tr("Compilation error: ") + row.get_cell_value("error") if role == Qt.DecorationRole and not row.markable: return QIcon.fromTheme("dialog-error", QIcon(":/error")) return None if role == Qt.DisplayRole: return row.data[column.name] elif role == Qt.FontRole: return QFont(self.view.font()) elif role == Qt.BackgroundRole and column.name == "regex": if row.highlight: return QColor(10, 200, 10) # green elif role == Qt.EditRole and column.name == "regex": return row.data[column.name] return None def _getFlags(self, row, column): flags = Qt.ItemIsEnabled if column.name == "marked": if row.markable: flags |= Qt.ItemIsUserCheckable elif column.name == "regex": flags |= Qt.ItemIsEditable | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled | Qt.ItemIsDropEnabled return flags def _setData(self, row, column, value, role): if role == Qt.CheckStateRole: if column.name == "marked": row.marked = bool(value) return True elif role == Qt.EditRole and column.name == "regex": return self.model.rename_selected(value) return False
2,560
Python
.py
55
37.363636
106
0.630461
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,054
tree_model.py
arsenetar_dupeguru/qt/tree_model.py
# Created By: Virgil Dupras # Created On: 2009-09-14 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import logging from PyQt5.QtCore import QAbstractItemModel, QModelIndex class NodeContainer: def __init__(self): self._subnodes = None self._ref2node = {} # --- Protected def _create_node(self, ref, row): # This returns a TreeNode instance from ref raise NotImplementedError() def _get_children(self): # This returns a list of ref instances, not TreeNode instances raise NotImplementedError() # --- Public def invalidate(self): # Invalidates cached data and list of subnodes without resetting ref2node. self._subnodes = None # --- Properties @property def subnodes(self): if self._subnodes is None: children = self._get_children() self._subnodes = [] for index, child in enumerate(children): if child in self._ref2node: node = self._ref2node[child] node.row = index else: node = self._create_node(child, index) self._ref2node[child] = node self._subnodes.append(node) return self._subnodes class TreeNode(NodeContainer): def __init__(self, model, parent, row): NodeContainer.__init__(self) self.model = model self.parent = parent self.row = row @property def index(self): return self.model.createIndex(self.row, 0, self) class RefNode(TreeNode): """Node pointing to a reference node. Use this if your Qt model wraps around a tree model that has iterable nodes. """ def __init__(self, model, parent, ref, row): TreeNode.__init__(self, model, parent, row) self.ref = ref def _create_node(self, ref, row): return RefNode(self.model, self, ref, row) def _get_children(self): return list(self.ref) # We use a specific TreeNode subclass to easily spot dummy nodes, especially in exception tracebacks. class DummyNode(TreeNode): pass class TreeModel(QAbstractItemModel, NodeContainer): def __init__(self, **kwargs): super().__init__(**kwargs) self._dummy_nodes = set() # dummy nodes' reference have to be kept to avoid segfault # --- Private def _create_dummy_node(self, parent, row): # In some cases (drag & drop row removal, to be precise), there's a temporary discrepancy # between a node's subnodes and what the model think it has. This leads to invalid indexes # being queried. Rather than going through complicated row removal crap, it's simpler to # just have rows with empty data replacing removed rows for the millisecond that the drag & # drop lasts. Override this to return a node of the correct type. return DummyNode(self, parent, row) def _last_index(self): """Index of the very last item in the tree.""" current_index = QModelIndex() row_count = self.rowCount(current_index) while row_count > 0: current_index = self.index(row_count - 1, 0, current_index) row_count = self.rowCount(current_index) return current_index # --- Overrides def index(self, row, column, parent): if not self.subnodes: return QModelIndex() node = parent.internalPointer() if parent.isValid() else self try: return self.createIndex(row, column, node.subnodes[row]) except IndexError: logging.debug( "Wrong tree index called (%r, %r, %r). Returning DummyNode", row, column, node, ) parent_node = parent.internalPointer() if parent.isValid() else None dummy = self._create_dummy_node(parent_node, row) self._dummy_nodes.add(dummy) return self.createIndex(row, column, dummy) def parent(self, index): if not index.isValid(): return QModelIndex() node = index.internalPointer() if node.parent is None: return QModelIndex() else: return self.createIndex(node.parent.row, 0, node.parent) def reset(self): super().beginResetModel() self.invalidate() self._ref2node = {} self._dummy_nodes = set() super().endResetModel() def rowCount(self, parent=QModelIndex()): node = parent.internalPointer() if parent.isValid() else self return len(node.subnodes) # --- Public def findIndex(self, row_path): """Returns the QModelIndex at `row_path` `row_path` is a sequence of node rows. For example, [1, 2, 1] is the 2nd child of the 3rd child of the 2nd child of the root. """ result = QModelIndex() for row in row_path: result = self.index(row, 0, result) return result @staticmethod def pathForIndex(index): reversed_path = [] while index.isValid(): reversed_path.append(index.row()) index = index.parent() return list(reversed(reversed_path)) def refreshData(self): """Updates the data on all nodes, but without having to perform a full reset. A full reset on a tree makes us lose selection and expansion states. When all we ant to do is to refresh the data on the nodes without adding or removing a node, a call on dataChanged() is better. But of course, Qt makes our life complicated by asking us topLeft and bottomRight indexes. This is a convenience method refreshing the whole tree. """ column_count = self.columnCount() top_left = self.index(0, 0, QModelIndex()) bottom_left = self._last_index() bottom_right = self.sibling(bottom_left.row(), column_count - 1, bottom_left) self.dataChanged.emit(top_left, bottom_right)
6,250
Python
.py
146
34.082192
101
0.631423
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,055
problem_dialog.py
arsenetar_dupeguru/qt/problem_dialog.py
# Created By: Virgil Dupras # Created On: 2010-04-12 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import Qt from PyQt5.QtWidgets import ( QDialog, QVBoxLayout, QHBoxLayout, QPushButton, QSpacerItem, QSizePolicy, QLabel, QTableView, QAbstractItemView, ) from qt.util import move_to_screen_center from hscommon.trans import trget from qt.problem_table import ProblemTable tr = trget("ui") class ProblemDialog(QDialog): def __init__(self, parent, model, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self._setupUi() self.model = model self.model.view = self self.table = ProblemTable(self.model.problem_table, view=self.tableView) self.revealButton.clicked.connect(self.model.reveal_selected_dupe) self.closeButton.clicked.connect(self.accept) def _setupUi(self): self.setWindowTitle(tr("Problems!")) self.resize(413, 323) self.verticalLayout = QVBoxLayout(self) self.label = QLabel(self) msg = tr( "There were problems processing some (or all) of the files. The cause of " "these problems are described in the table below. Those files were not " "removed from your results." ) self.label.setText(msg) self.label.setWordWrap(True) self.verticalLayout.addWidget(self.label) self.tableView = QTableView(self) self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers) self.tableView.setSelectionMode(QAbstractItemView.SingleSelection) self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows) self.tableView.setShowGrid(False) self.tableView.horizontalHeader().setStretchLastSection(True) self.tableView.verticalHeader().setDefaultSectionSize(18) self.tableView.verticalHeader().setHighlightSections(False) self.verticalLayout.addWidget(self.tableView) self.horizontalLayout = QHBoxLayout() self.revealButton = QPushButton(self) self.revealButton.setText(tr("Reveal Selected")) self.horizontalLayout.addWidget(self.revealButton) spacer_item = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacer_item) self.closeButton = QPushButton(self) self.closeButton.setText(tr("Close")) self.closeButton.setDefault(True) self.horizontalLayout.addWidget(self.closeButton) self.verticalLayout.addLayout(self.horizontalLayout) def showEvent(self, event): # have to do this here as the frameGeometry is not correct until shown move_to_screen_center(self) super().showEvent(event)
3,069
Python
.py
70
36.957143
89
0.716148
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,056
about_box.py
arsenetar_dupeguru/qt/about_box.py
# Created By: Virgil Dupras # Created On: 2009-05-09 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import Qt, QCoreApplication, QTimer from PyQt5.QtGui import QPixmap, QFont from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QSizePolicy, QHBoxLayout, QVBoxLayout, QLabel from core.util import check_for_update from qt.util import move_to_screen_center from hscommon.trans import trget tr = trget("ui") class AboutBox(QDialog): def __init__(self, parent, app, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint | Qt.MSWindowsFixedSizeDialogHint super().__init__(parent, flags, **kwargs) self.app = app self._setupUi() self.button_box.accepted.connect(self.accept) self.button_box.rejected.connect(self.reject) def _setupUi(self): self.setWindowTitle(tr("About {}").format(QCoreApplication.instance().applicationName())) size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.setSizePolicy(size_policy) main_layout = QHBoxLayout(self) logo_label = QLabel() logo_label.setPixmap(QPixmap(":/%s_big" % self.app.LOGO_NAME)) main_layout.addWidget(logo_label) detail_layout = QVBoxLayout() name_label = QLabel() font = QFont() font.setWeight(75) font.setBold(True) name_label.setFont(font) name_label.setText(QCoreApplication.instance().applicationName()) detail_layout.addWidget(name_label) version_label = QLabel() version_label.setText(tr("Version {}").format(QCoreApplication.instance().applicationVersion())) detail_layout.addWidget(version_label) self.update_label = QLabel(tr("Checking for updates...")) self.update_label.setTextInteractionFlags(Qt.TextBrowserInteraction) self.update_label.setOpenExternalLinks(True) detail_layout.addWidget(self.update_label) license_label = QLabel() license_label.setText(tr("Licensed under GPLv3")) detail_layout.addWidget(license_label) spacer_label = QLabel() spacer_label.setFont(font) detail_layout.addWidget(spacer_label) self.button_box = QDialogButtonBox() self.button_box.setOrientation(Qt.Horizontal) self.button_box.setStandardButtons(QDialogButtonBox.Ok) detail_layout.addWidget(self.button_box) main_layout.addLayout(detail_layout) def _check_for_update(self): update = check_for_update(QCoreApplication.instance().applicationVersion(), include_prerelease=False) if update is None: self.update_label.setText(tr("No update available.")) else: self.update_label.setText( tr('New version {} available, download <a href="{}">here</a>.').format(update["version"], update["url"]) ) def showEvent(self, event): self.update_label.setText(tr("Checking for updates...")) # have to do this here as the frameGeometry is not correct until shown move_to_screen_center(self) super().showEvent(event) QTimer.singleShot(0, self._check_for_update)
3,435
Python
.py
70
41.6
120
0.694875
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,057
result_window.py
arsenetar_dupeguru/qt/result_window.py
# Created By: Virgil Dupras # Created On: 2009-04-25 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import Qt, QRect from PyQt5.QtWidgets import ( QMainWindow, QMenu, QLabel, QFileDialog, QMenuBar, QWidget, QVBoxLayout, QAbstractItemView, QStatusBar, QDialog, QPushButton, QCheckBox, QDesktopWidget, ) from hscommon.trans import trget from qt.util import move_to_screen_center, horizontal_wrap, create_actions from qt.search_edit import SearchEdit from core.app import AppMode from qt.results_model import ResultsView from qt.stats_label import StatsLabel from qt.prioritize_dialog import PrioritizeDialog from qt.se.results_model import ResultsModel as ResultsModelStandard from qt.me.results_model import ResultsModel as ResultsModelMusic from qt.pe.results_model import ResultsModel as ResultsModelPicture tr = trget("ui") class ResultWindow(QMainWindow): def __init__(self, parent, app, **kwargs): super().__init__(parent, **kwargs) self.app = app self.specific_actions = set() self._setupUi() if app.model.app_mode == AppMode.PICTURE: MODEL_CLASS = ResultsModelPicture elif app.model.app_mode == AppMode.MUSIC: MODEL_CLASS = ResultsModelMusic else: MODEL_CLASS = ResultsModelStandard self.resultsModel = MODEL_CLASS(self.app, self.resultsView) self.stats = StatsLabel(app.model.stats_label, self.statusLabel) self._update_column_actions_status() self.menuColumns.triggered.connect(self.columnToggled) self.resultsView.doubleClicked.connect(self.resultsDoubleClicked) self.resultsView.spacePressed.connect(self.resultsSpacePressed) self.detailsButton.clicked.connect(self.actionDetails.triggered) self.dupesOnlyCheckBox.stateChanged.connect(self.powerMarkerTriggered) self.deltaValuesCheckBox.stateChanged.connect(self.deltaTriggered) self.searchEdit.searchChanged.connect(self.searchChanged) self.app.willSavePrefs.connect(self.appWillSavePrefs) def _setupActions(self): # (name, shortcut, icon, desc, func) ACTIONS = [ ("actionDetails", "Ctrl+I", "", tr("Details"), self.detailsTriggered), ("actionActions", "", "", tr("Actions"), self.actionsTriggered), ( "actionPowerMarker", "Ctrl+1", "", tr("Show Dupes Only"), self.powerMarkerTriggered, ), ("actionDelta", "Ctrl+2", "", tr("Show Delta Values"), self.deltaTriggered), ( "actionDeleteMarked", "Ctrl+D", "", tr("Send Marked to Recycle Bin..."), self.deleteTriggered, ), ( "actionMoveMarked", "Ctrl+M", "", tr("Move Marked to..."), self.moveTriggered, ), ( "actionCopyMarked", "Ctrl+Shift+M", "", tr("Copy Marked to..."), self.copyTriggered, ), ( "actionRemoveMarked", "Ctrl+R", "", tr("Remove Marked from Results"), self.removeMarkedTriggered, ), ( "actionReprioritize", "", "", tr("Re-Prioritize Results..."), self.reprioritizeTriggered, ), ( "actionRemoveSelected", "Ctrl+Del", "", tr("Remove Selected from Results"), self.removeSelectedTriggered, ), ( "actionIgnoreSelected", "Ctrl+Shift+Del", "", tr("Add Selected to Ignore List"), self.addToIgnoreListTriggered, ), ( "actionMakeSelectedReference", "Ctrl+Space", "", tr("Make Selected into Reference"), self.app.model.make_selected_reference, ), ( "actionOpenSelected", "Ctrl+O", "", tr("Open Selected with Default Application"), self.openTriggered, ), ( "actionRevealSelected", "Ctrl+Shift+O", "", tr("Open Containing Folder of Selected"), self.revealTriggered, ), ( "actionRenameSelected", "F2", "", tr("Rename Selected"), self.renameTriggered, ), ("actionMarkAll", "Ctrl+A", "", tr("Mark All"), self.markAllTriggered), ( "actionMarkNone", "Ctrl+Shift+A", "", tr("Mark None"), self.markNoneTriggered, ), ( "actionInvertMarking", "Ctrl+Alt+A", "", tr("Invert Marking"), self.markInvertTriggered, ), ( "actionMarkSelected", Qt.Key_Space, "", tr("Mark Selected"), self.markSelectedTriggered, ), ( "actionExportToHTML", "", "", tr("Export To HTML"), self.app.model.export_to_xhtml, ), ( "actionExportToCSV", "", "", tr("Export To CSV"), self.app.model.export_to_csv, ), ( "actionSaveResults", "Ctrl+S", "", tr("Save Results..."), self.saveResultsTriggered, ), ( "actionInvokeCustomCommand", "Ctrl+Alt+I", "", tr("Invoke Custom Command"), self.app.invokeCustomCommand, ), ] create_actions(ACTIONS, self) self.actionDelta.setCheckable(True) self.actionPowerMarker.setCheckable(True) if self.app.main_window: # We use tab widgets in this case # Keep track of actions which should only be accessible from this class for action, _, _, _, _ in ACTIONS: self.specific_actions.add(getattr(self, action)) def _setupMenu(self): if not self.app.use_tabs: # we are our own QMainWindow, we need our own menu bar self.menubar = QMenuBar() # self.menuBar() works as well here self.menubar.setGeometry(QRect(0, 0, 630, 22)) self.menuFile = QMenu(self.menubar) self.menuFile.setTitle(tr("File")) self.menuMark = QMenu(self.menubar) self.menuMark.setTitle(tr("Mark")) self.menuActions = QMenu(self.menubar) self.menuActions.setTitle(tr("Actions")) self.menuColumns = QMenu(self.menubar) self.menuColumns.setTitle(tr("Columns")) self.menuView = QMenu(self.menubar) self.menuView.setTitle(tr("View")) self.menuHelp = QMenu(self.menubar) self.menuHelp.setTitle(tr("Help")) self.setMenuBar(self.menubar) menubar = self.menubar else: # we are part of a tab widget, we populate its window's menubar instead self.menuFile = self.app.main_window.menuFile self.menuMark = self.app.main_window.menuMark self.menuActions = self.app.main_window.menuActions self.menuColumns = self.app.main_window.menuColumns self.menuView = self.app.main_window.menuView self.menuHelp = self.app.main_window.menuHelp menubar = self.app.main_window.menubar self.menuActions.addAction(self.actionDeleteMarked) self.menuActions.addAction(self.actionMoveMarked) self.menuActions.addAction(self.actionCopyMarked) self.menuActions.addAction(self.actionRemoveMarked) self.menuActions.addAction(self.actionReprioritize) self.menuActions.addSeparator() self.menuActions.addAction(self.actionRemoveSelected) self.menuActions.addAction(self.actionIgnoreSelected) self.menuActions.addAction(self.actionMakeSelectedReference) self.menuActions.addSeparator() self.menuActions.addAction(self.actionOpenSelected) self.menuActions.addAction(self.actionRevealSelected) self.menuActions.addAction(self.actionInvokeCustomCommand) self.menuActions.addAction(self.actionRenameSelected) self.menuMark.addAction(self.actionMarkAll) self.menuMark.addAction(self.actionMarkNone) self.menuMark.addAction(self.actionInvertMarking) self.menuMark.addAction(self.actionMarkSelected) self.menuView.addAction(self.actionDetails) self.menuView.addSeparator() self.menuView.addAction(self.actionPowerMarker) self.menuView.addAction(self.actionDelta) self.menuView.addSeparator() if not self.app.use_tabs: self.menuView.addAction(self.app.actionIgnoreList) # This also pushes back the options entry to the bottom of the menu self.menuView.addSeparator() self.menuView.addAction(self.app.actionPreferences) self.menuHelp.addAction(self.app.actionShowHelp) self.menuHelp.addAction(self.app.actionOpenDebugLog) self.menuHelp.addAction(self.app.actionAbout) self.menuFile.addAction(self.actionSaveResults) self.menuFile.addAction(self.actionExportToHTML) self.menuFile.addAction(self.actionExportToCSV) self.menuFile.addSeparator() self.menuFile.addAction(self.app.actionQuit) menubar.addAction(self.menuFile.menuAction()) menubar.addAction(self.menuMark.menuAction()) menubar.addAction(self.menuActions.menuAction()) menubar.addAction(self.menuColumns.menuAction()) menubar.addAction(self.menuView.menuAction()) menubar.addAction(self.menuHelp.menuAction()) # Columns menu menu = self.menuColumns # Avoid adding duplicate actions in tab widget menu in case we recreated # the Result Window instance. if menu.actions(): menu.clear() self._column_actions = [] for index, (display, visible) in enumerate(self.app.model.result_table._columns.menu_items()): action = menu.addAction(display) action.setCheckable(True) action.setChecked(visible) action.item_index = index self._column_actions.append(action) menu.addSeparator() action = menu.addAction(tr("Reset to Defaults")) action.item_index = -1 # Action menu action_menu = QMenu(tr("Actions"), menubar) action_menu.addAction(self.actionDeleteMarked) action_menu.addAction(self.actionMoveMarked) action_menu.addAction(self.actionCopyMarked) action_menu.addAction(self.actionRemoveMarked) action_menu.addSeparator() action_menu.addAction(self.actionRemoveSelected) action_menu.addAction(self.actionIgnoreSelected) action_menu.addAction(self.actionMakeSelectedReference) action_menu.addSeparator() action_menu.addAction(self.actionOpenSelected) action_menu.addAction(self.actionRevealSelected) action_menu.addAction(self.actionInvokeCustomCommand) action_menu.addAction(self.actionRenameSelected) self.actionActions.setMenu(action_menu) self.actionsButton.setMenu(self.actionActions.menu()) def _setupUi(self): self.setWindowTitle(tr("{} Results").format(self.app.NAME)) self.resize(630, 514) self.centralwidget = QWidget(self) self.verticalLayout = QVBoxLayout(self.centralwidget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setSpacing(0) self.actionsButton = QPushButton(tr("Actions")) self.detailsButton = QPushButton(tr("Details")) self.dupesOnlyCheckBox = QCheckBox(tr("Dupes Only")) self.deltaValuesCheckBox = QCheckBox(tr("Delta Values")) self.searchEdit = SearchEdit() self.searchEdit.setMaximumWidth(300) self.horizontalLayout = horizontal_wrap( [ self.actionsButton, self.detailsButton, self.dupesOnlyCheckBox, self.deltaValuesCheckBox, None, self.searchEdit, 8, ] ) self.horizontalLayout.setSpacing(8) self.verticalLayout.addLayout(self.horizontalLayout) self.resultsView = ResultsView(self.centralwidget) self.resultsView.setSelectionMode(QAbstractItemView.ExtendedSelection) self.resultsView.setSelectionBehavior(QAbstractItemView.SelectRows) self.resultsView.setSortingEnabled(True) self.resultsView.setWordWrap(False) self.resultsView.verticalHeader().setVisible(False) h = self.resultsView.horizontalHeader() h.setHighlightSections(False) h.setSectionsMovable(True) h.setStretchLastSection(False) h.setDefaultAlignment(Qt.AlignLeft) self.verticalLayout.addWidget(self.resultsView) self.setCentralWidget(self.centralwidget) self._setupActions() self._setupMenu() self.statusbar = QStatusBar(self) self.statusbar.setSizeGripEnabled(True) self.setStatusBar(self.statusbar) self.statusLabel = QLabel(self) self.statusbar.addPermanentWidget(self.statusLabel, 1) if self.app.prefs.resultWindowIsMaximized: self.setWindowState(self.windowState() | Qt.WindowMaximized) else: if self.app.prefs.resultWindowRect is not None: self.setGeometry(self.app.prefs.resultWindowRect) # if not on any screen move to center of default screen # moves to center of closest screen if partially off screen frame = self.frameGeometry() if QDesktopWidget().screenNumber(self) == -1: move_to_screen_center(self) elif QDesktopWidget().availableGeometry(self).contains(frame) is False: frame.moveCenter(QDesktopWidget().availableGeometry(self).center()) self.move(frame.topLeft()) else: move_to_screen_center(self) # --- Private def _update_column_actions_status(self): # Update menu checked state menu_items = self.app.model.result_table._columns.menu_items() for action, (display, visible) in zip(self._column_actions, menu_items): action.setChecked(visible) # --- Actions def actionsTriggered(self): self.actionsButton.showMenu() def addToIgnoreListTriggered(self): self.app.model.add_selected_to_ignore_list() def copyTriggered(self): self.app.model.copy_or_move_marked(True) def deleteTriggered(self): self.app.model.delete_marked() def deltaTriggered(self, state=None): # The sender can be either the action or the checkbox, but both have a isChecked() method. self.resultsModel.delta_values = self.sender().isChecked() self.actionDelta.setChecked(self.resultsModel.delta_values) self.deltaValuesCheckBox.setChecked(self.resultsModel.delta_values) def detailsTriggered(self): self.app.show_details() def markAllTriggered(self): self.app.model.mark_all() def markInvertTriggered(self): self.app.model.mark_invert() def markNoneTriggered(self): self.app.model.mark_none() def markSelectedTriggered(self): self.app.model.toggle_selected_mark_state() def moveTriggered(self): self.app.model.copy_or_move_marked(False) def openTriggered(self): self.app.model.open_selected() def powerMarkerTriggered(self, state=None): # see deltaTriggered self.resultsModel.power_marker = self.sender().isChecked() self.actionPowerMarker.setChecked(self.resultsModel.power_marker) self.dupesOnlyCheckBox.setChecked(self.resultsModel.power_marker) def preferencesTriggered(self): self.app.show_preferences() def removeMarkedTriggered(self): self.app.model.remove_marked() def removeSelectedTriggered(self): self.app.model.remove_selected() def renameTriggered(self): index = self.resultsView.selectionModel().currentIndex() # Our index is the current row, with column set to 0. Our filename column is 1 and that's # what we want. index = index.sibling(index.row(), 1) self.resultsView.edit(index) def reprioritizeTriggered(self): dlg = PrioritizeDialog(self, self.app) result = dlg.exec() if result == QDialog.Accepted: dlg.model.perform_reprioritization() def revealTriggered(self): self.app.model.reveal_selected() def saveResultsTriggered(self): title = tr("Select a file to save your results to") files = tr("dupeGuru Results (*.dupeguru)") destination, chosen_filter = QFileDialog.getSaveFileName(self, title, "", files) if destination: if not destination.endswith(".dupeguru"): destination = f"{destination}.dupeguru" self.app.model.save_as(destination) self.app.recentResults.insertItem(destination) # --- Events def appWillSavePrefs(self): prefs = self.app.prefs prefs.resultWindowIsMaximized = self.isMaximized() prefs.resultWindowRect = self.geometry() def columnToggled(self, action): index = action.item_index if index == -1: self.app.model.result_table._columns.reset_to_defaults() self._update_column_actions_status() else: visible = self.app.model.result_table._columns.toggle_menu_item(index) action.setChecked(visible) def contextMenuEvent(self, event): self.actionActions.menu().exec_(event.globalPos()) def resultsDoubleClicked(self, model_index): self.app.model.open_selected() def resultsSpacePressed(self): self.app.model.toggle_selected_mark_state() def searchChanged(self): self.app.model.apply_filter(self.searchEdit.text()) def closeEvent(self, event): # this saves the location of the results window when it is closed self.appWillSavePrefs()
19,339
Python
.py
460
30.923913
102
0.617745
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,058
app.py
arsenetar_dupeguru/qt/app.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import sys import os.path as op from PyQt5.QtCore import QTimer, QObject, QUrl, pyqtSignal, Qt from PyQt5.QtGui import QColor, QDesktopServices, QPalette from PyQt5.QtWidgets import QApplication, QFileDialog, QDialog, QMessageBox, QStyleFactory, QToolTip from hscommon.trans import trget from hscommon import desktop, plat from qt.about_box import AboutBox from qt.recent import Recent from qt.util import create_actions from qt.progress_window import ProgressWindow from core.app import AppMode, DupeGuru as DupeGuruModel import core.pe.photo from qt import platform from qt.preferences import Preferences from qt.result_window import ResultWindow from qt.directories_dialog import DirectoriesDialog from qt.problem_dialog import ProblemDialog from qt.ignore_list_dialog import IgnoreListDialog from qt.exclude_list_dialog import ExcludeListDialog from qt.deletion_options import DeletionOptions from qt.se.details_dialog import DetailsDialog as DetailsDialogStandard from qt.me.details_dialog import DetailsDialog as DetailsDialogMusic from qt.pe.details_dialog import DetailsDialog as DetailsDialogPicture from qt.se.preferences_dialog import PreferencesDialog as PreferencesDialogStandard from qt.me.preferences_dialog import PreferencesDialog as PreferencesDialogMusic from qt.pe.preferences_dialog import PreferencesDialog as PreferencesDialogPicture from qt.pe.photo import File as PlatSpecificPhoto from qt.tabbed_window import TabBarWindow, TabWindow tr = trget("ui") class DupeGuru(QObject): LOGO_NAME = "logo_se" NAME = "dupeGuru" def __init__(self, **kwargs): super().__init__(**kwargs) self.prefs = Preferences() self.prefs.load() # Enable tabs instead of separate floating windows for each dialog # Could be passed as an argument to this class if we wanted self.use_tabs = True self.model = DupeGuruModel(view=self, portable=self.prefs.portable) self._setup() # --- Private def _setup(self): core.pe.photo.PLAT_SPECIFIC_PHOTO_CLASS = PlatSpecificPhoto self._setupActions() self.details_dialog = None self._update_options() self.recentResults = Recent(self, "recentResults") self.recentResults.mustOpenItem.connect(self.model.load_from) self.resultWindow = None if self.use_tabs: self.main_window = TabBarWindow(self) if not self.prefs.tabs_default_pos else TabWindow(self) parent_window = self.main_window self.directories_dialog = self.main_window.createPage("DirectoriesDialog", app=self) self.main_window.addTab(self.directories_dialog, tr("Directories"), switch=False) self.actionDirectoriesWindow.setEnabled(False) else: # floating windows only self.main_window = None self.directories_dialog = DirectoriesDialog(self) parent_window = self.directories_dialog self.progress_window = ProgressWindow(parent_window, self.model.progress_window) self.problemDialog = ProblemDialog(parent=parent_window, model=self.model.problem_dialog) if self.use_tabs: self.ignoreListDialog = self.main_window.createPage( "IgnoreListDialog", parent=self.main_window, model=self.model.ignore_list_dialog, ) self.excludeListDialog = self.main_window.createPage( "ExcludeListDialog", app=self, parent=self.main_window, model=self.model.exclude_list_dialog, ) else: self.ignoreListDialog = IgnoreListDialog(parent=parent_window, model=self.model.ignore_list_dialog) self.excludeDialog = ExcludeListDialog(app=self, parent=parent_window, model=self.model.exclude_list_dialog) self.deletionOptions = DeletionOptions(parent=parent_window, model=self.model.deletion_options) self.about_box = AboutBox(parent_window, self) parent_window.show() self.model.load() self.SIGTERM.connect(self.handleSIGTERM) # The timer scheme is because if the nag is not shown before the application is # completely initialized, the nag will be shown before the app shows up in the task bar # In some circumstances, the nag is hidden by other window, which may make the user think # that the application haven't launched. QTimer.singleShot(0, self.finishedLaunching) def _setupActions(self): # Setup actions that are common to both the directory dialog and the results window. # (name, shortcut, icon, desc, func) ACTIONS = [ ("actionQuit", "Ctrl+Q", "", tr("Quit"), self.quitTriggered), ( "actionPreferences", "Ctrl+P", "", tr("Options"), self.preferencesTriggered, ), ("actionIgnoreList", "", "", tr("Ignore List"), self.ignoreListTriggered), ( "actionDirectoriesWindow", "", "", tr("Directories"), self.showDirectoriesWindow, ), ( "actionClearCache", "Ctrl+Shift+P", "", tr("Clear Cache"), self.clearCacheTriggered, ), ( "actionExcludeList", "", "", tr("Exclusion Filters"), self.excludeListTriggered, ), ("actionShowHelp", "F1", "", tr("dupeGuru Help"), self.showHelpTriggered), ("actionAbout", "", "", tr("About dupeGuru"), self.showAboutBoxTriggered), ( "actionOpenDebugLog", "", "", tr("Open Debug Log"), self.openDebugLogTriggered, ), ] create_actions(ACTIONS, self) def _update_options(self): self.model.options["mix_file_kind"] = self.prefs.mix_file_kind self.model.options["escape_filter_regexp"] = not self.prefs.use_regexp self.model.options["clean_empty_dirs"] = self.prefs.remove_empty_folders self.model.options["ignore_hardlink_matches"] = self.prefs.ignore_hardlink_matches self.model.options["copymove_dest_type"] = self.prefs.destination_type self.model.options["scan_type"] = self.prefs.get_scan_type(self.model.app_mode) self.model.options["min_match_percentage"] = self.prefs.filter_hardness self.model.options["word_weighting"] = self.prefs.word_weighting self.model.options["match_similar_words"] = self.prefs.match_similar threshold = self.prefs.small_file_threshold if self.prefs.ignore_small_files else 0 self.model.options["size_threshold"] = threshold * 1024 # threshold is in KB. The scanner wants bytes large_threshold = self.prefs.large_file_threshold if self.prefs.ignore_large_files else 0 self.model.options["large_size_threshold"] = ( large_threshold * 1024 * 1024 ) # threshold is in MB. The Scanner wants bytes big_file_size_threshold = self.prefs.big_file_size_threshold if self.prefs.big_file_partial_hashes else 0 self.model.options["big_file_size_threshold"] = ( big_file_size_threshold * 1024 * 1024 # threshold is in MiB. The scanner wants bytes ) scanned_tags = set() if self.prefs.scan_tag_track: scanned_tags.add("track") if self.prefs.scan_tag_artist: scanned_tags.add("artist") if self.prefs.scan_tag_album: scanned_tags.add("album") if self.prefs.scan_tag_title: scanned_tags.add("title") if self.prefs.scan_tag_genre: scanned_tags.add("genre") if self.prefs.scan_tag_year: scanned_tags.add("year") self.model.options["scanned_tags"] = scanned_tags self.model.options["match_scaled"] = self.prefs.match_scaled self.model.options["match_rotated"] = self.prefs.match_rotated self.model.options["include_exists_check"] = self.prefs.include_exists_check self.model.options["rehash_ignore_mtime"] = self.prefs.rehash_ignore_mtime if self.details_dialog: self.details_dialog.update_options() self._set_style("dark" if self.prefs.use_dark_style else "light") # --- Private def _get_details_dialog_class(self): if self.model.app_mode == AppMode.PICTURE: return DetailsDialogPicture elif self.model.app_mode == AppMode.MUSIC: return DetailsDialogMusic else: return DetailsDialogStandard def _get_preferences_dialog_class(self): if self.model.app_mode == AppMode.PICTURE: return PreferencesDialogPicture elif self.model.app_mode == AppMode.MUSIC: return PreferencesDialogMusic else: return PreferencesDialogStandard def _set_style(self, style="light"): # Only support this feature on windows for now if not plat.ISWINDOWS: return if style == "dark": QApplication.setStyle(QStyleFactory.create("Fusion")) palette = QApplication.style().standardPalette() palette.setColor(QPalette.ColorRole.Window, QColor(53, 53, 53)) palette.setColor(QPalette.ColorRole.WindowText, Qt.white) palette.setColor(QPalette.ColorRole.Base, QColor(25, 25, 25)) palette.setColor(QPalette.ColorRole.AlternateBase, QColor(53, 53, 53)) palette.setColor(QPalette.ColorRole.ToolTipBase, QColor(53, 53, 53)) palette.setColor(QPalette.ColorRole.ToolTipText, Qt.white) palette.setColor(QPalette.ColorRole.Text, Qt.white) palette.setColor(QPalette.ColorRole.Button, QColor(53, 53, 53)) palette.setColor(QPalette.ColorRole.ButtonText, Qt.white) palette.setColor(QPalette.ColorRole.BrightText, Qt.red) palette.setColor(QPalette.ColorRole.Link, QColor(42, 130, 218)) palette.setColor(QPalette.ColorRole.Highlight, QColor(42, 130, 218)) palette.setColor(QPalette.ColorRole.HighlightedText, Qt.black) palette.setColor(QPalette.ColorGroup.Disabled, QPalette.ColorRole.Text, QColor(164, 166, 168)) palette.setColor(QPalette.ColorGroup.Disabled, QPalette.ColorRole.WindowText, QColor(164, 166, 168)) palette.setColor(QPalette.ColorGroup.Disabled, QPalette.ColorRole.ButtonText, QColor(164, 166, 168)) palette.setColor(QPalette.ColorGroup.Disabled, QPalette.ColorRole.HighlightedText, QColor(164, 166, 168)) palette.setColor(QPalette.ColorGroup.Disabled, QPalette.ColorRole.Base, QColor(68, 68, 68)) palette.setColor(QPalette.ColorGroup.Disabled, QPalette.ColorRole.Window, QColor(68, 68, 68)) palette.setColor(QPalette.ColorGroup.Disabled, QPalette.ColorRole.Highlight, QColor(68, 68, 68)) else: QApplication.setStyle(QStyleFactory.create("windowsvista" if plat.ISWINDOWS else "Fusion")) palette = QApplication.style().standardPalette() QToolTip.setPalette(palette) QApplication.setPalette(palette) # --- Public def add_selected_to_ignore_list(self): self.model.add_selected_to_ignore_list() def remove_selected(self): self.model.remove_selected(self) def confirm(self, title, msg, default_button=QMessageBox.Yes): active = QApplication.activeWindow() buttons = QMessageBox.Yes | QMessageBox.No answer = QMessageBox.question(active, title, msg, buttons, default_button) return answer == QMessageBox.Yes def invokeCustomCommand(self): self.model.invoke_custom_command() def show_details(self): if self.details_dialog is not None: if not self.details_dialog.isVisible(): self.details_dialog.show() else: self.details_dialog.hide() def showResultsWindow(self): if self.resultWindow is not None: if self.use_tabs: if self.main_window.indexOfWidget(self.resultWindow) < 0: self.main_window.addTab(self.resultWindow, tr("Results"), switch=True) return self.main_window.showTab(self.resultWindow) else: self.resultWindow.show() def showDirectoriesWindow(self): if self.directories_dialog is not None: if self.use_tabs: self.main_window.showTab(self.directories_dialog) else: self.directories_dialog.show() def shutdown(self): self.willSavePrefs.emit() self.prefs.save() self.model.save() self.model.close() # Workaround for #857, hide() or close(). if self.details_dialog is not None: self.details_dialog.close() QApplication.quit() # --- Signals willSavePrefs = pyqtSignal() SIGTERM = pyqtSignal() # --- Events def finishedLaunching(self): if sys.getfilesystemencoding() == "ascii": # No need to localize this, it's a debugging message. msg = ( "Something is wrong with the way your system locale is set. If the files you're " "scanning have accented letters, you'll probably get a crash. It is advised that " "you set your system locale properly." ) QMessageBox.warning( self.main_window if self.main_window else self.directories_dialog, "Wrong Locale", msg, ) # Load results on open if passed a .dupeguru file if len(sys.argv) > 1: results = sys.argv[1] if results.endswith(".dupeguru"): self.model.load_from(results) self.recentResults.insertItem(results) def clearCacheTriggered(self): title = tr("Clear Cache") msg = tr("Do you really want to clear the cache? This will remove all cached file hashes and picture analysis.") if self.confirm(title, msg, QMessageBox.No): self.model.clear_picture_cache() self.model.clear_hash_cache() active = QApplication.activeWindow() QMessageBox.information(active, title, tr("Cache cleared.")) def ignoreListTriggered(self): if self.use_tabs: self.showTriggeredTabbedDialog(self.ignoreListDialog, tr("Ignore List")) else: # floating windows self.model.ignore_list_dialog.show() def excludeListTriggered(self): if self.use_tabs: self.showTriggeredTabbedDialog(self.excludeListDialog, tr("Exclusion Filters")) else: # floating windows self.model.exclude_list_dialog.show() def showTriggeredTabbedDialog(self, dialog, desc_string): """Add tab for dialog, name the tab with desc_string, then show it.""" index = self.main_window.indexOfWidget(dialog) # Create the tab if it doesn't exist already if index < 0: # or (not dialog.isVisible() and not self.main_window.isTabVisible(index)): index = self.main_window.addTab(dialog, desc_string, switch=True) # Show the tab for that widget self.main_window.setCurrentIndex(index) def openDebugLogTriggered(self): debug_log_path = op.join(self.model.appdata, "debug.log") desktop.open_path(debug_log_path) def preferencesTriggered(self): preferences_dialog = self._get_preferences_dialog_class()( self.main_window if self.main_window else self.directories_dialog, self ) preferences_dialog.load() result = preferences_dialog.exec() if result == QDialog.Accepted: preferences_dialog.save() self.prefs.save() self._update_options() preferences_dialog.setParent(None) def quitTriggered(self): if self.details_dialog is not None: self.details_dialog.close() if self.main_window: self.main_window.close() else: self.directories_dialog.close() def showAboutBoxTriggered(self): self.about_box.show() def showHelpTriggered(self): base_path = platform.HELP_PATH help_path = op.abspath(op.join(base_path, "index.html")) if op.exists(help_path): url = QUrl.fromLocalFile(help_path) else: url = QUrl("https://dupeguru.voltaicideas.net/help/en/") QDesktopServices.openUrl(url) def handleSIGTERM(self): self.shutdown() # --- model --> view def get_default(self, key): return self.prefs.get_value(key) def set_default(self, key, value): self.prefs.set_value(key, value) def show_message(self, msg): window = QApplication.activeWindow() QMessageBox.information(window, "", msg) def ask_yes_no(self, prompt): return self.confirm("", prompt) def create_results_window(self): """Creates resultWindow and details_dialog depending on the selected ``app_mode``.""" if self.details_dialog is not None: # The object is not deleted entirely, avoid saving its geometry in the future # self.willSavePrefs.disconnect(self.details_dialog.appWillSavePrefs) # or simply delete it on close which is probably cleaner: self.details_dialog.setAttribute(Qt.WA_DeleteOnClose) self.details_dialog.close() # if we don't do the following, Qt will crash when we recreate the Results dialog self.details_dialog.setParent(None) if self.resultWindow is not None: self.resultWindow.close() # This is better for tabs, as it takes care of duplicate items in menu bar self.resultWindow.deleteLater() if self.use_tabs else self.resultWindow.setParent(None) if self.use_tabs: self.resultWindow = self.main_window.createPage("ResultWindow", parent=self.main_window, app=self) else: # We don't use a tab widget, regular floating QMainWindow self.resultWindow = ResultWindow(self.directories_dialog, self) self.directories_dialog._updateActionsState() self.details_dialog = self._get_details_dialog_class()(self.resultWindow, self) def show_results_window(self): self.showResultsWindow() def show_problem_dialog(self): self.problemDialog.show() def select_dest_folder(self, prompt): flags = QFileDialog.ShowDirsOnly return QFileDialog.getExistingDirectory(self.resultWindow, prompt, "", flags) def select_dest_file(self, prompt, extension): files = tr("{} file (*.{})").format(extension.upper(), extension) destination, chosen_filter = QFileDialog.getSaveFileName(self.resultWindow, prompt, "", files) if not destination.endswith(f".{extension}"): destination = f"{destination}.{extension}" return destination
19,602
Python
.py
396
39.356061
120
0.654153
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,059
details_dialog.py
arsenetar_dupeguru/qt/details_dialog.py
# Created By: Virgil Dupras # Created On: 2010-02-05 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QDockWidget, QWidget from qt.util import move_to_screen_center from qt.details_table import DetailsModel from hscommon.plat import ISLINUX class DetailsDialog(QDockWidget): def __init__(self, parent, app, **kwargs): super().__init__(parent, Qt.Tool, **kwargs) self.parent = parent self.app = app self.model = app.model.details_panel self.setAllowedAreas(Qt.AllDockWidgetAreas) self._setupUi() # To avoid saving uninitialized geometry on appWillSavePrefs, we track whether our dialog # has been shown. If it has, we know that our geometry should be saved. self._shown_once = False self._wasDocked, area = self.app.prefs.restoreGeometry("DetailsWindowRect", self) self.tableModel = DetailsModel(self.model, app) # tableView is defined in subclasses self.tableView.setModel(self.tableModel) self.model.view = self self.app.willSavePrefs.connect(self.appWillSavePrefs) # self.setAttribute(Qt.WA_DeleteOnClose) parent.addDockWidget(area if self._wasDocked else Qt.BottomDockWidgetArea, self) def _setupUi(self): # Virtual pass def show(self): if not self._shown_once and self._wasDocked: self.setFloating(False) self._shown_once = True super().show() self.update_options() def update_options(self): # This disables the title bar (if we had not set one before already) # essentially making it a simple floating window, not dockable anymore if not self.app.prefs.details_dialog_titlebar_enabled: if not self.titleBarWidget(): # default title bar self.setTitleBarWidget(QWidget()) # disables title bar # Windows (and MacOS?) users cannot move a floating window which # has no native decoration so we force it to dock for now if not ISLINUX: self.setFloating(False) elif self.titleBarWidget() is not None: # title bar is disabled self.setTitleBarWidget(None) # resets to the default title bar elif not self.titleBarWidget() and not self.app.prefs.details_dialog_titlebar_enabled: self.setTitleBarWidget(QWidget()) features = self.features() if self.app.prefs.details_dialog_vertical_titlebar: self.setFeatures(features | QDockWidget.DockWidgetVerticalTitleBar) elif features & QDockWidget.DockWidgetVerticalTitleBar: self.setFeatures(features ^ QDockWidget.DockWidgetVerticalTitleBar) # --- Events def appWillSavePrefs(self): if self._shown_once: self.app.prefs.saveGeometry("DetailsWindowRect", self) # --- model --> view def refresh(self): self.tableModel.beginResetModel() self.tableModel.endResetModel() def showEvent(self, event): if self._wasDocked is False: # have to do this here as the frameGeometry is not correct until shown move_to_screen_center(self) super().showEvent(event)
3,489
Python
.py
71
40.830986
97
0.684767
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,060
column.py
arsenetar_dupeguru/qt/column.py
# Created By: Virgil Dupras # Created On: 2009-11-25 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QHeaderView class Column: def __init__( self, attrname, default_width, editor=None, alignment=Qt.AlignLeft, cant_truncate=False, painter=None, resize_to_fit=False, ): self.attrname = attrname self.default_width = default_width self.editor = editor # See moneyguru #15. Painter attribute was added to allow custom painting of amount value and # currency information. Can be used as a pattern for custom painting of any column. self.painter = painter self.alignment = alignment # This is to indicate, during printing, that a column can't have its data truncated. self.cant_truncate = cant_truncate self.resize_to_fit = resize_to_fit class Columns: def __init__(self, model, columns, header_view): self.model = model self._header_view = header_view self._header_view.setDefaultAlignment(Qt.AlignLeft) def setspecs(col, modelcol): modelcol.default_width = col.default_width modelcol.editor = col.editor modelcol.painter = col.painter modelcol.resize_to_fit = col.resize_to_fit modelcol.alignment = col.alignment modelcol.cant_truncate = col.cant_truncate if columns: for col in columns: modelcol = self.model.column_by_name(col.attrname) setspecs(col, modelcol) else: col = Column("", 100) for modelcol in self.model.column_list: setspecs(col, modelcol) self.model.view = self self._header_view.sectionMoved.connect(self.header_section_moved) self._header_view.sectionResized.connect(self.header_section_resized) # See moneyguru #14 and #15. This was added in order to allow automatic resizing of columns. for column in self.model.column_list: if column.resize_to_fit: self._header_view.setSectionResizeMode(column.logical_index, QHeaderView.ResizeToContents) # --- Public def set_columns_width(self, widths): # `widths` can be None. If it is, then default widths are set. columns = self.model.column_list if not widths: widths = [column.default_width for column in columns] for column, width in zip(columns, widths): if width == 0: # column was hidden before. width = column.default_width self._header_view.resizeSection(column.logical_index, width) def set_columns_order(self, column_indexes): if not column_indexes: return for dest_index, column_index in enumerate(column_indexes): # moveSection takes 2 visual index arguments, so we have to get our visual index first visual_index = self._header_view.visualIndex(column_index) self._header_view.moveSection(visual_index, dest_index) # --- Events def header_section_moved(self, logical_index, old_visual_index, new_visual_index): attrname = self.model.column_by_index(logical_index).name self.model.move_column(attrname, new_visual_index) def header_section_resized(self, logical_index, old_size, new_size): attrname = self.model.column_by_index(logical_index).name self.model.resize_column(attrname, new_size) # --- model --> view def restore_columns(self): columns = self.model.ordered_columns indexes = [col.logical_index for col in columns] self.set_columns_order(indexes) widths = [col.width for col in self.model.column_list] if not any(widths): widths = None self.set_columns_width(widths) for column in self.model.column_list: visible = self.model.column_is_visible(column.name) self._header_view.setSectionHidden(column.logical_index, not visible) def set_column_visible(self, colname, visible): column = self.model.column_by_name(colname) self._header_view.setSectionHidden(column.logical_index, not visible)
4,521
Python
.py
96
38.114583
106
0.661301
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,061
details_table.py
arsenetar_dupeguru/qt/details_table.py
# Created By: Virgil Dupras # Created On: 2009-05-17 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import Qt, QAbstractTableModel from PyQt5.QtWidgets import QHeaderView, QTableView from PyQt5.QtGui import QFont, QBrush from hscommon.trans import trget tr = trget("ui") HEADER = [tr("Selected"), tr("Reference")] class DetailsModel(QAbstractTableModel): def __init__(self, model, app, **kwargs): super().__init__(**kwargs) self.model = model self.prefs = app.prefs def columnCount(self, parent): return len(HEADER) def data(self, index, role): if not index.isValid(): return None # Skip first value "Attribute" column = index.column() + 1 row = index.row() ignored_fields = ["Dupe Count"] if ( self.model.row(row)[0] in ignored_fields or self.model.row(row)[1] == "---" or self.model.row(row)[2] == "---" ): if role != Qt.DisplayRole: return None return self.model.row(row)[column] if role == Qt.DisplayRole: return self.model.row(row)[column] if role == Qt.ForegroundRole and self.model.row(row)[1] != self.model.row(row)[2]: return QBrush(self.prefs.details_table_delta_foreground_color) if role == Qt.FontRole and self.model.row(row)[1] != self.model.row(row)[2]: font = QFont(self.model.view.font()) # or simply QFont() font.setBold(True) return font return None # QVariant() def headerData(self, section, orientation, role): if orientation == Qt.Horizontal and role == Qt.DisplayRole and section < len(HEADER): return HEADER[section] elif orientation == Qt.Vertical and role == Qt.DisplayRole and section < self.model.row_count(): # Read "Attribute" cell for horizontal header return self.model.row(section)[0] return None def rowCount(self, parent): return self.model.row_count() class DetailsTable(QTableView): def __init__(self, *args): QTableView.__init__(self, *args) self.setAlternatingRowColors(True) self.setSelectionBehavior(QTableView.SelectRows) self.setSelectionMode(QTableView.NoSelection) self.setShowGrid(False) self.setWordWrap(False) self.setCornerButtonEnabled(False) def setModel(self, model): QTableView.setModel(self, model) # The model needs to be set to set header stuff hheader = self.horizontalHeader() hheader.setHighlightSections(False) hheader.setSectionResizeMode(0, QHeaderView.Stretch) hheader.setSectionResizeMode(1, QHeaderView.Stretch) vheader = self.verticalHeader() vheader.setVisible(True) vheader.setDefaultSectionSize(18) # hardcoded value above is not ideal, perhaps resize to contents first? # vheader.setSectionResizeMode(QHeaderView.ResizeToContents) vheader.setSectionResizeMode(QHeaderView.Fixed) vheader.setSectionsMovable(True)
3,369
Python
.py
76
36.236842
104
0.660464
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,062
error_report_dialog.py
arsenetar_dupeguru/qt/error_report_dialog.py
# Created By: Virgil Dupras # Created On: 2009-05-23 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import traceback import sys import os import platform from PyQt5.QtCore import Qt, QCoreApplication, QSize from PyQt5.QtWidgets import ( QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPlainTextEdit, QPushButton, ) from hscommon.trans import trget from hscommon.desktop import open_url from qt.util import horizontal_spacer tr = trget("ui") class ErrorReportDialog(QDialog): def __init__(self, parent, github_url, error, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self._setupUi() name = QCoreApplication.applicationName() version = QCoreApplication.applicationVersion() error_text = "Application Name: {}\nVersion: {}\nPython: {}\nOperating System: {}\n\n{}".format( name, version, platform.python_version(), platform.platform(), error ) # Under windows, we end up with an error report without linesep if we don't mangle it error_text = error_text.replace("\n", os.linesep) self.errorTextEdit.setPlainText(error_text) self.github_url = github_url self.sendButton.clicked.connect(self.goToGitHub) self.dontSendButton.clicked.connect(self.reject) def _setupUi(self): self.setWindowTitle(tr("Error Report")) self.resize(553, 349) self.verticalLayout = QVBoxLayout(self) self.label = QLabel(self) self.label.setText(tr("Something went wrong. How about reporting the error?")) self.label.setWordWrap(True) self.verticalLayout.addWidget(self.label) self.errorTextEdit = QPlainTextEdit(self) self.errorTextEdit.setReadOnly(True) self.verticalLayout.addWidget(self.errorTextEdit) msg = tr( "Error reports should be reported as GitHub issues. You can copy the error traceback " "above and paste it in a new issue.\n\nPlease make sure to run a search for any already " "existing issues beforehand. Also make sure to test the very latest version available from the repository, " "since the bug you are experiencing might have already been patched.\n\n" "What usually really helps is if you add a description of how you got the error. Thanks!" "\n\n" "Although the application should continue to run after this error, it may be in an " "unstable state, so it is recommended that you restart the application." ) self.label2 = QLabel(msg) self.label2.setWordWrap(True) self.verticalLayout.addWidget(self.label2) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.addItem(horizontal_spacer()) self.dontSendButton = QPushButton(self) self.dontSendButton.setText(tr("Close")) self.dontSendButton.setMinimumSize(QSize(110, 0)) self.horizontalLayout.addWidget(self.dontSendButton) self.sendButton = QPushButton(self) self.sendButton.setText(tr("Go to GitHub")) self.sendButton.setMinimumSize(QSize(110, 0)) self.sendButton.setDefault(True) self.horizontalLayout.addWidget(self.sendButton) self.verticalLayout.addLayout(self.horizontalLayout) def goToGitHub(self): open_url(self.github_url) def install_excepthook(github_url): def my_excepthook(exctype, value, tb): s = "".join(traceback.format_exception(exctype, value, tb)) dialog = ErrorReportDialog(None, github_url, s) dialog.exec_() sys.excepthook = my_excepthook
3,938
Python
.py
84
39.738095
120
0.700156
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,063
selectable_list.py
arsenetar_dupeguru/qt/selectable_list.py
# Created By: Virgil Dupras # Created On: 2011-09-06 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import Qt, QAbstractListModel, QItemSelection, QItemSelectionModel class SelectableList(QAbstractListModel): def __init__(self, model, view, **kwargs): super().__init__(**kwargs) self._updating = False self.view = view self.model = model self.view.setModel(self) self.model.view = self # --- Override def data(self, index, role): if not index.isValid(): return None # We need EditRole for QComboBoxes with setEditable(True) if role in {Qt.DisplayRole, Qt.EditRole}: return self.model[index.row()] return None def rowCount(self, index): if index.isValid(): return 0 return len(self.model) # --- Virtual def _updateSelection(self): raise NotImplementedError() def _restoreSelection(self): raise NotImplementedError() # --- model --> view def refresh(self): self._updating = True self.beginResetModel() self.endResetModel() self._updating = False self._restoreSelection() def update_selection(self): self._restoreSelection() class ComboboxModel(SelectableList): def __init__(self, model, view, **kwargs): super().__init__(model, view, **kwargs) self.view.currentIndexChanged[int].connect(self.selectionChanged) # --- Override def _updateSelection(self): index = self.view.currentIndex() if index != self.model.selected_index: self.model.select(index) def _restoreSelection(self): index = self.model.selected_index if index is not None: self.view.setCurrentIndex(index) # --- Events def selectionChanged(self, index): if not self._updating: self._updateSelection() class ListviewModel(SelectableList): def __init__(self, model, view, **kwargs): super().__init__(model, view, **kwargs) self.view.selectionModel().selectionChanged[(QItemSelection, QItemSelection)].connect(self.selectionChanged) # --- Override def _updateSelection(self): new_indexes = [modelIndex.row() for modelIndex in self.view.selectionModel().selectedRows()] if new_indexes != self.model.selected_indexes: self.model.select(new_indexes) def _restoreSelection(self): new_selection = QItemSelection() for index in self.model.selected_indexes: new_selection.select(self.createIndex(index, 0), self.createIndex(index, 0)) self.view.selectionModel().select(new_selection, QItemSelectionModel.ClearAndSelect) if len(new_selection.indexes()): current_index = new_selection.indexes()[0] self.view.selectionModel().setCurrentIndex(current_index, QItemSelectionModel.Current) self.view.scrollTo(current_index) # --- Events def selectionChanged(self, index): if not self._updating: self._updateSelection()
3,348
Python
.py
81
33.679012
116
0.661638
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,064
table.py
arsenetar_dupeguru/qt/table.py
# Created By: Virgil Dupras # Created On: 2009-11-01 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import typing from PyQt5.QtCore import ( Qt, QAbstractTableModel, QModelIndex, QItemSelectionModel, QItemSelection, ) from qt.column import Columns, Column class Table(QAbstractTableModel): # Flags you want when index.isValid() is False. In those cases, _getFlags() is never called. INVALID_INDEX_FLAGS = Qt.ItemFlag.ItemIsEnabled COLUMNS: typing.List[Column] = [] def __init__(self, model, view, **kwargs): super().__init__(**kwargs) self.model = model self.view = view self.view.setModel(self) self.model.view = self if hasattr(self.model, "_columns"): self._columns = Columns(self.model._columns, self.COLUMNS, view.horizontalHeader()) self.view.selectionModel().selectionChanged[(QItemSelection, QItemSelection)].connect(self.selectionChanged) def _updateModelSelection(self): # Takes the selection on the view's side and update the model with it. # an _updateViewSelection() call will normally result in an _updateModelSelection() call. # to avoid infinite loops, we check that the selection will actually change before calling # model.select() new_indexes = [modelIndex.row() for modelIndex in self.view.selectionModel().selectedRows()] if new_indexes != self.model.selected_indexes: self.model.select(new_indexes) def _updateViewSelection(self): # Takes the selection on the model's side and update the view with it. new_selection = QItemSelection() column_count = self.columnCount(QModelIndex()) for index in self.model.selected_indexes: new_selection.select(self.createIndex(index, 0), self.createIndex(index, column_count - 1)) self.view.selectionModel().select(new_selection, QItemSelectionModel.ClearAndSelect) if len(new_selection.indexes()): current_index = new_selection.indexes()[0] self.view.selectionModel().setCurrentIndex(current_index, QItemSelectionModel.Current) self.view.scrollTo(current_index) # --- Data Model methods # Virtual def _getData(self, row, column, role): if role in (Qt.DisplayRole, Qt.EditRole): attrname = column.name return row.get_cell_value(attrname) elif role == Qt.TextAlignmentRole: return column.alignment return None # Virtual def _getFlags(self, row, column): flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable if row.can_edit_cell(column.name): flags |= Qt.ItemIsEditable return flags # Virtual def _setData(self, row, column, value, role): if role == Qt.EditRole: attrname = column.name if attrname == "from": attrname = "from_" setattr(row, attrname, value) return True return False def columnCount(self, index): return self.model._columns.columns_count() def data(self, index, role): if not index.isValid(): return None row = self.model[index.row()] column = self.model._columns.column_by_index(index.column()) return self._getData(row, column, role) def flags(self, index): if not index.isValid(): return self.INVALID_INDEX_FLAGS row = self.model[index.row()] column = self.model._columns.column_by_index(index.column()) return self._getFlags(row, column) def headerData(self, section, orientation, role): if orientation != Qt.Horizontal: return None if section >= self.model._columns.columns_count(): return None column = self.model._columns.column_by_index(section) if role == Qt.DisplayRole: return column.display elif role == Qt.TextAlignmentRole: return column.alignment else: return None def revert(self): self.model.cancel_edits() def rowCount(self, index): if index.isValid(): return 0 return len(self.model) def setData(self, index, value, role): if not index.isValid(): return False row = self.model[index.row()] column = self.model._columns.column_by_index(index.column()) return self._setData(row, column, value, role) def sort(self, section, order): column = self.model._columns.column_by_index(section) attrname = column.name self.model.sort_by(attrname, desc=order == Qt.DescendingOrder) def submit(self): self.model.save_edits() return True # --- Events def selectionChanged(self, selected, deselected): self._updateModelSelection() # --- model --> view def refresh(self): self.beginResetModel() self.endResetModel() self._updateViewSelection() def show_selected_row(self): if self.model.selected_index is not None: self.view.showRow(self.model.selected_index) def start_editing(self): self.view.editSelected() def stop_editing(self): self.view.setFocus() # enough to stop editing def update_selection(self): self._updateViewSelection()
5,600
Python
.py
134
33.58209
116
0.652757
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,065
platform.py
arsenetar_dupeguru/qt/platform.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import os.path as op from hscommon.plat import ISWINDOWS, ISOSX, ISLINUX if op.exists(__file__): # We want to get the absolute path or our root folder. We know that in that folder we're # inside qt/, so we just go back one level. BASE_PATH = op.abspath(op.join(op.dirname(__file__), "..")) else: # Should be a frozen environment if ISOSX: BASE_PATH = op.abspath(op.join(op.dirname(__file__), "..", "..", "Resources")) else: # For others our base path is ''. BASE_PATH = "" HELP_PATH = op.join(BASE_PATH, "help", "en") if ISWINDOWS: INITIAL_FOLDER_IN_DIALOGS = "C:\\" elif ISOSX: INITIAL_FOLDER_IN_DIALOGS = "/" elif ISLINUX: INITIAL_FOLDER_IN_DIALOGS = "/" else: # unsupported platform, however '/' is a good guess for a path which is available INITIAL_FOLDER_IN_DIALOGS = "/"
1,124
Python
.py
28
36.607143
92
0.682525
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,066
prioritize_dialog.py
arsenetar_dupeguru/qt/prioritize_dialog.py
# Created By: Virgil Dupras # Created On: 2011-09-06 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import Qt, QMimeData, QByteArray from PyQt5.QtWidgets import ( QDialog, QVBoxLayout, QHBoxLayout, QPushButton, QComboBox, QListView, QDialogButtonBox, QAbstractItemView, QLabel, QStyle, QSplitter, QWidget, QSizePolicy, ) from hscommon.trans import trget from qt.selectable_list import ComboboxModel, ListviewModel from qt.util import vertical_spacer from core.gui.prioritize_dialog import PrioritizeDialog as PrioritizeDialogModel tr = trget("ui") MIME_INDEXES = "application/dupeguru.rowindexes" class PrioritizationList(ListviewModel): def flags(self, index): if not index.isValid(): return Qt.ItemIsEnabled | Qt.ItemIsDropEnabled return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled # --- Drag & Drop def dropMimeData(self, mime_data, action, row, column, parent_index): if not mime_data.hasFormat(MIME_INDEXES): return False # Since we only drop in between items, parentIndex must be invalid, and we use the row arg # to know where the drop took place. if parent_index.isValid(): return False # "When row and column are -1 it means that the dropped data should be considered as # dropped directly on parent." # Moving items to row -1 would put them before the last item. Fix the row to drop the # dragged items after the last item. if row < 0: row = len(self.model) - 1 str_mime_data = bytes(mime_data.data(MIME_INDEXES)).decode() indexes = list(map(int, str_mime_data.split(","))) self.model.move_indexes(indexes, row) self.view.selectionModel().clearSelection() return True def mimeData(self, indexes): rows = {str(index.row()) for index in indexes} data = ",".join(rows) mime_data = QMimeData() mime_data.setData(MIME_INDEXES, QByteArray(data.encode())) return mime_data def mimeTypes(self): return [MIME_INDEXES] def supportedDropActions(self): return Qt.MoveAction class PrioritizeDialog(QDialog): def __init__(self, parent, app, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self._setupUi() self.model = PrioritizeDialogModel(app=app.model) self.categoryList = ComboboxModel(model=self.model.category_list, view=self.categoryCombobox) self.criteriaList = ListviewModel(model=self.model.criteria_list, view=self.criteriaListView) self.prioritizationList = PrioritizationList( model=self.model.prioritization_list, view=self.prioritizationListView ) self.model.view = self self.addCriteriaButton.clicked.connect(self.model.add_selected) self.criteriaListView.doubleClicked.connect(self.model.add_selected) self.removeCriteriaButton.clicked.connect(self.model.remove_selected) self.prioritizationListView.doubleClicked.connect(self.model.remove_selected) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def _setupUi(self): self.setWindowTitle(tr("Re-Prioritize duplicates")) self.resize(700, 400) # widgets msg = tr( "Add criteria to the right box and click OK to send the dupes that correspond the " "best to these criteria to their respective group's " "reference position. Read the help file for more information." ) self.promptLabel = QLabel(msg) self.promptLabel.setWordWrap(True) self.categoryCombobox = QComboBox() self.criteriaListView = QListView() self.criteriaListView.setSelectionMode(QAbstractItemView.ExtendedSelection) self.addCriteriaButton = QPushButton(self.style().standardIcon(QStyle.SP_ArrowRight), "") self.removeCriteriaButton = QPushButton(self.style().standardIcon(QStyle.SP_ArrowLeft), "") self.prioritizationListView = QListView() self.prioritizationListView.setAcceptDrops(True) self.prioritizationListView.setDragEnabled(True) self.prioritizationListView.setDragDropMode(QAbstractItemView.InternalMove) self.prioritizationListView.setSelectionBehavior(QAbstractItemView.SelectRows) self.prioritizationListView.setSelectionMode(QAbstractItemView.ExtendedSelection) self.buttonBox = QDialogButtonBox() self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) # layout self.mainLayout = QVBoxLayout(self) self.mainLayout.addWidget(self.promptLabel) self.splitter = QSplitter() sp = self.splitter.sizePolicy() sp.setVerticalPolicy(QSizePolicy.Expanding) self.splitter.setSizePolicy(sp) self.leftSide = QWidget() self.leftWidgetsLayout = QVBoxLayout() self.leftWidgetsLayout.addWidget(self.categoryCombobox) self.leftWidgetsLayout.addWidget(self.criteriaListView) self.leftSide.setLayout(self.leftWidgetsLayout) self.splitter.addWidget(self.leftSide) self.rightSide = QWidget() self.rightWidgetsLayout = QHBoxLayout() self.addRemoveButtonsLayout = QVBoxLayout() self.addRemoveButtonsLayout.addItem(vertical_spacer()) self.addRemoveButtonsLayout.addWidget(self.addCriteriaButton) self.addRemoveButtonsLayout.addWidget(self.removeCriteriaButton) self.addRemoveButtonsLayout.addItem(vertical_spacer()) self.rightWidgetsLayout.addLayout(self.addRemoveButtonsLayout) self.rightWidgetsLayout.addWidget(self.prioritizationListView) self.rightSide.setLayout(self.rightWidgetsLayout) self.splitter.addWidget(self.rightSide) self.mainLayout.addWidget(self.splitter) self.mainLayout.addWidget(self.buttonBox)
6,311
Python
.py
131
40.549618
101
0.718527
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,067
search_edit.py
arsenetar_dupeguru/qt/search_edit.py
# Created By: Virgil Dupras # Created On: 2009-12-10 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import pyqtSignal, Qt from PyQt5.QtGui import QIcon, QPixmap, QPainter, QPalette from PyQt5.QtWidgets import QToolButton, QLineEdit, QStyle, QStyleOptionFrame from hscommon.trans import trget tr = trget("ui") # IMPORTANT: For this widget to work propertly, you have to add "search_clear_13" from the # "images" folder in your resources. class LineEditButton(QToolButton): def __init__(self, parent, **kwargs): super().__init__(parent, **kwargs) pixmap = QPixmap(":/search_clear_13") self.setIcon(QIcon(pixmap)) self.setIconSize(pixmap.size()) self.setCursor(Qt.ArrowCursor) self.setPopupMode(QToolButton.InstantPopup) stylesheet = "QToolButton { border: none; padding: 0px; }" self.setStyleSheet(stylesheet) class ClearableEdit(QLineEdit): def __init__(self, parent=None, is_clearable=True, **kwargs): super().__init__(parent, **kwargs) self._is_clearable = is_clearable if is_clearable: self._clearButton = LineEditButton(self) frame_width = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth) padding_right = self._clearButton.sizeHint().width() + frame_width + 1 stylesheet = f"QLineEdit {{ padding-right:{padding_right}px; }}" self.setStyleSheet(stylesheet) self._updateClearButton() self._clearButton.clicked.connect(self._clearSearch) self.textChanged.connect(self._textChanged) # --- Private def _clearSearch(self): self.clear() def _updateClearButton(self): self._clearButton.setVisible(self._hasClearableContent()) def _hasClearableContent(self): return bool(self.text()) # --- QLineEdit overrides def resizeEvent(self, event): if self._is_clearable: frame_width = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth) rect = self.rect() right_hint = self._clearButton.sizeHint() right_x = rect.right() - frame_width - right_hint.width() right_y = (rect.bottom() - right_hint.height()) // 2 self._clearButton.move(right_x, right_y) # --- Event Handlers def _textChanged(self, text): if self._is_clearable: self._updateClearButton() class SearchEdit(ClearableEdit): def __init__(self, parent=None, immediate=False): # immediate: send searchChanged signals at each keystroke. ClearableEdit.__init__(self, parent, is_clearable=True) self.inactiveText = tr("Search...") self.immediate = immediate self.returnPressed.connect(self._returnPressed) # --- Overrides def _clearSearch(self): ClearableEdit._clearSearch(self) self.searchChanged.emit() def _textChanged(self, text): ClearableEdit._textChanged(self, text) if self.immediate: self.searchChanged.emit() def keyPressEvent(self, event): key = event.key() if key == Qt.Key_Escape: self._clearSearch() else: ClearableEdit.keyPressEvent(self, event) def paintEvent(self, event): ClearableEdit.paintEvent(self, event) if not bool(self.text()) and self.inactiveText and not self.hasFocus(): panel = QStyleOptionFrame() self.initStyleOption(panel) text_rect = self.style().subElementRect(QStyle.SE_LineEditContents, panel, self) left_margin = 2 right_margin = self._clearButton.iconSize().width() text_rect.adjust(left_margin, 0, -right_margin, 0) painter = QPainter(self) disabled_color = self.palette().brush(QPalette.Disabled, QPalette.Text).color() painter.setPen(disabled_color) painter.drawText(text_rect, Qt.AlignLeft | Qt.AlignVCenter, self.inactiveText) # --- Event Handlers def _returnPressed(self): if not self.immediate: self.searchChanged.emit() # --- Signals searchChanged = pyqtSignal() # Emitted when return is pressed or when the test is cleared
4,460
Python
.py
97
37.814433
94
0.661751
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,068
stats_label.py
arsenetar_dupeguru/qt/stats_label.py
# Created By: Virgil Dupras # Created On: 2010-02-12 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html class StatsLabel: def __init__(self, model, view): self.view = view self.model = model self.model.view = self def refresh(self): self.view.setText(self.model.display)
539
Python
.py
14
34.428571
89
0.710728
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,069
preferences.py
arsenetar_dupeguru/qt/preferences.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtWidgets import QApplication, QDockWidget from PyQt5.QtCore import Qt, QRect, QObject, pyqtSignal from PyQt5.QtGui import QColor from hscommon import trans from hscommon.plat import ISLINUX from core.app import AppMode from core.scanner import ScanType from hscommon.util import tryint from qt.util import create_qsettings def get_langnames(): tr = trans.trget("ui") return { "cs": tr("Czech"), "de": tr("German"), "el": tr("Greek"), "en": tr("English"), "es": tr("Spanish"), "fr": tr("French"), "hy": tr("Armenian"), "it": tr("Italian"), "ja": tr("Japanese"), "ko": tr("Korean"), "ms": tr("Malay"), "nl": tr("Dutch"), "pl_PL": tr("Polish"), "pt_BR": tr("Brazilian"), "ru": tr("Russian"), "tr": tr("Turkish"), "uk": tr("Ukrainian"), "vi": tr("Vietnamese"), "zh_CN": tr("Chinese (Simplified)"), } def _normalize_for_serialization(v): # QSettings doesn't consider set/tuple as "native" typs for serialization, so if we don't # change them into a list, we get a weird serialized QVariant value which isn't a very # "portable" value. if isinstance(v, (set, tuple)): v = list(v) if isinstance(v, list): v = [_normalize_for_serialization(item) for item in v] return v def _adjust_after_deserialization(v): # In some cases, when reading from prefs, we end up with strings that are supposed to be # bool or int. Convert these. if isinstance(v, list): return [_adjust_after_deserialization(sub) for sub in v] if isinstance(v, str): # might be bool or int, try them if v == "true": return True elif v == "false": return False else: return tryint(v, v) return v class PreferencesBase(QObject): prefsChanged = pyqtSignal() def __init__(self): QObject.__init__(self) self.reset() self._settings = create_qsettings() def _load_values(self, settings): # Implemented in subclasses pass def get_rect(self, name, default=None): r = self.get_value(name, default) if r is not None: return QRect(*r) else: return None def get_value(self, name, default=None): if self._settings.contains(name): result = _adjust_after_deserialization(self._settings.value(name)) if result is not None: return result else: # If result is None, but still present in self._settings, it usually means a value # like "@Invalid". return default else: return default def load(self): self.reset() self._load_values(self._settings) def reset(self): # Implemented in subclasses pass def _save_values(self, settings): # Implemented in subclasses pass def save(self): self._save_values(self._settings) self._settings.sync() def set_rect(self, name, r): # About QRect conversion: # I think Qt supports putting basic structures like QRect directly in QSettings, but I prefer not # to rely on it and stay with generic structures. if isinstance(r, QRect): rect_as_list = [r.x(), r.y(), r.width(), r.height()] self.set_value(name, rect_as_list) def set_value(self, name, value): self._settings.setValue(name, _normalize_for_serialization(value)) def saveGeometry(self, name, widget): # We save geometry under a 7-sized int array: first item is a flag # for whether the widget is maximized, second item is a flag for whether # the widget is docked, third item is a Qt::DockWidgetArea enum value, # and the other 4 are (x, y, w, h). m = 1 if widget.isMaximized() else 0 d = 1 if isinstance(widget, QDockWidget) and not widget.isFloating() else 0 area = widget.parent.dockWidgetArea(widget) if d else 0 r = widget.geometry() rect_as_list = [r.x(), r.y(), r.width(), r.height()] self.set_value(name, [m, d, area] + rect_as_list) def restoreGeometry(self, name, widget): geometry = self.get_value(name) if geometry and len(geometry) == 7: m, d, area, x, y, w, h = geometry if m: widget.setWindowState(Qt.WindowMaximized) else: r = QRect(x, y, w, h) widget.setGeometry(r) if isinstance(widget, QDockWidget): # Inform of the previous dock state and the area used return bool(d), area return False, 0 class Preferences(PreferencesBase): def _load_values(self, settings): get = self.get_value self.filter_hardness = get("FilterHardness", self.filter_hardness) self.mix_file_kind = get("MixFileKind", self.mix_file_kind) self.ignore_hardlink_matches = get("IgnoreHardlinkMatches", self.ignore_hardlink_matches) self.use_regexp = get("UseRegexp", self.use_regexp) self.remove_empty_folders = get("RemoveEmptyFolders", self.remove_empty_folders) self.rehash_ignore_mtime = get("RehashIgnoreMTime", self.rehash_ignore_mtime) self.include_exists_check = get("IncludeExistsCheck", self.include_exists_check) self.debug_mode = get("DebugMode", self.debug_mode) self.profile_scan = get("ProfileScan", self.profile_scan) self.destination_type = get("DestinationType", self.destination_type) self.custom_command = get("CustomCommand", self.custom_command) self.language = get("Language", self.language) if not self.language and trans.installed_lang: self.language = trans.installed_lang self.portable = get("Portable", False) self.use_dark_style = get("UseDarkStyle", False) self.use_native_dialogs = get("UseNativeDialogs", True) self.tableFontSize = get("TableFontSize", self.tableFontSize) self.reference_bold_font = get("ReferenceBoldFont", self.reference_bold_font) self.details_dialog_titlebar_enabled = get("DetailsDialogTitleBarEnabled", self.details_dialog_titlebar_enabled) self.details_dialog_vertical_titlebar = get( "DetailsDialogVerticalTitleBar", self.details_dialog_vertical_titlebar ) # On Windows and MacOS, use internal icons by default self.details_dialog_override_theme_icons = ( get("DetailsDialogOverrideThemeIcons", self.details_dialog_override_theme_icons) if ISLINUX else True ) self.details_table_delta_foreground_color = get( "DetailsTableDeltaForegroundColor", self.details_table_delta_foreground_color ) self.details_dialog_viewers_show_scrollbars = get( "DetailsDialogViewersShowScrollbars", self.details_dialog_viewers_show_scrollbars ) self.result_table_ref_foreground_color = get( "ResultTableRefForegroundColor", self.result_table_ref_foreground_color ) self.result_table_ref_background_color = get( "ResultTableRefBackgroundColor", self.result_table_ref_background_color ) self.result_table_delta_foreground_color = get( "ResultTableDeltaForegroundColor", self.result_table_delta_foreground_color ) self.resultWindowIsMaximized = get("ResultWindowIsMaximized", self.resultWindowIsMaximized) self.resultWindowRect = self.get_rect("ResultWindowRect", self.resultWindowRect) self.mainWindowIsMaximized = get("MainWindowIsMaximized", self.mainWindowIsMaximized) self.mainWindowRect = self.get_rect("MainWindowRect", self.mainWindowRect) self.directoriesWindowRect = self.get_rect("DirectoriesWindowRect", self.directoriesWindowRect) self.recentResults = get("RecentResults", self.recentResults) self.recentFolders = get("RecentFolders", self.recentFolders) self.tabs_default_pos = get("TabsDefaultPosition", self.tabs_default_pos) self.word_weighting = get("WordWeighting", self.word_weighting) self.match_similar = get("MatchSimilar", self.match_similar) self.ignore_small_files = get("IgnoreSmallFiles", self.ignore_small_files) self.small_file_threshold = get("SmallFileThreshold", self.small_file_threshold) self.ignore_large_files = get("IgnoreLargeFiles", self.ignore_large_files) self.large_file_threshold = get("LargeFileThreshold", self.large_file_threshold) self.big_file_partial_hashes = get("BigFilePartialHashes", self.big_file_partial_hashes) self.big_file_size_threshold = get("BigFileSizeThreshold", self.big_file_size_threshold) self.scan_tag_track = get("ScanTagTrack", self.scan_tag_track) self.scan_tag_artist = get("ScanTagArtist", self.scan_tag_artist) self.scan_tag_album = get("ScanTagAlbum", self.scan_tag_album) self.scan_tag_title = get("ScanTagTitle", self.scan_tag_title) self.scan_tag_genre = get("ScanTagGenre", self.scan_tag_genre) self.scan_tag_year = get("ScanTagYear", self.scan_tag_year) self.match_scaled = get("MatchScaled", self.match_scaled) self.match_rotated = get("MatchRotated", self.match_rotated) def reset(self): self.filter_hardness = 95 self.mix_file_kind = True self.use_regexp = False self.ignore_hardlink_matches = False self.remove_empty_folders = False self.rehash_ignore_mtime = False self.include_exists_check = True self.debug_mode = False self.profile_scan = False self.destination_type = 1 self.custom_command = "" self.language = trans.installed_lang if trans.installed_lang else "" self.use_dark_style = False self.use_native_dialogs = True self.tableFontSize = QApplication.font().pointSize() self.reference_bold_font = True self.details_dialog_titlebar_enabled = True self.details_dialog_vertical_titlebar = True self.details_table_delta_foreground_color = QColor(250, 20, 20) # red # By default use internal icons on platforms other than Linux for now self.details_dialog_override_theme_icons = False if not ISLINUX else True self.details_dialog_viewers_show_scrollbars = True self.result_table_ref_foreground_color = QColor(Qt.blue) self.result_table_ref_background_color = QColor(Qt.lightGray) self.result_table_delta_foreground_color = QColor(255, 142, 40) # orange self.resultWindowIsMaximized = False self.resultWindowRect = None self.directoriesWindowRect = None self.mainWindowRect = None self.mainWindowIsMaximized = False self.recentResults = [] self.recentFolders = [] self.tabs_default_pos = True self.word_weighting = True self.match_similar = False self.ignore_small_files = True self.small_file_threshold = 10 # KB self.ignore_large_files = False self.large_file_threshold = 1000 # MB self.big_file_partial_hashes = False self.big_file_size_threshold = 100 # MB self.scan_tag_track = False self.scan_tag_artist = True self.scan_tag_album = True self.scan_tag_title = True self.scan_tag_genre = False self.scan_tag_year = False self.match_scaled = False self.match_rotated = False def _save_values(self, settings): set_ = self.set_value set_("FilterHardness", self.filter_hardness) set_("MixFileKind", self.mix_file_kind) set_("IgnoreHardlinkMatches", self.ignore_hardlink_matches) set_("UseRegexp", self.use_regexp) set_("RemoveEmptyFolders", self.remove_empty_folders) set_("RehashIgnoreMTime", self.rehash_ignore_mtime) set_("IncludeExistsCheck", self.include_exists_check) set_("DebugMode", self.debug_mode) set_("ProfileScan", self.profile_scan) set_("DestinationType", self.destination_type) set_("CustomCommand", self.custom_command) set_("Language", self.language) set_("Portable", self.portable) set_("UseDarkStyle", self.use_dark_style) set_("UseNativeDialogs", self.use_native_dialogs) set_("TableFontSize", self.tableFontSize) set_("ReferenceBoldFont", self.reference_bold_font) set_("DetailsDialogTitleBarEnabled", self.details_dialog_titlebar_enabled) set_("DetailsDialogVerticalTitleBar", self.details_dialog_vertical_titlebar) set_("DetailsDialogOverrideThemeIcons", self.details_dialog_override_theme_icons) set_("DetailsDialogViewersShowScrollbars", self.details_dialog_viewers_show_scrollbars) set_("DetailsTableDeltaForegroundColor", self.details_table_delta_foreground_color) set_("ResultTableRefForegroundColor", self.result_table_ref_foreground_color) set_("ResultTableRefBackgroundColor", self.result_table_ref_background_color) set_("ResultTableDeltaForegroundColor", self.result_table_delta_foreground_color) set_("ResultWindowIsMaximized", self.resultWindowIsMaximized) set_("MainWindowIsMaximized", self.mainWindowIsMaximized) self.set_rect("ResultWindowRect", self.resultWindowRect) self.set_rect("MainWindowRect", self.mainWindowRect) self.set_rect("DirectoriesWindowRect", self.directoriesWindowRect) set_("RecentResults", self.recentResults) set_("RecentFolders", self.recentFolders) set_("TabsDefaultPosition", self.tabs_default_pos) set_("WordWeighting", self.word_weighting) set_("MatchSimilar", self.match_similar) set_("IgnoreSmallFiles", self.ignore_small_files) set_("SmallFileThreshold", self.small_file_threshold) set_("IgnoreLargeFiles", self.ignore_large_files) set_("LargeFileThreshold", self.large_file_threshold) set_("BigFilePartialHashes", self.big_file_partial_hashes) set_("BigFileSizeThreshold", self.big_file_size_threshold) set_("ScanTagTrack", self.scan_tag_track) set_("ScanTagArtist", self.scan_tag_artist) set_("ScanTagAlbum", self.scan_tag_album) set_("ScanTagTitle", self.scan_tag_title) set_("ScanTagGenre", self.scan_tag_genre) set_("ScanTagYear", self.scan_tag_year) set_("MatchScaled", self.match_scaled) set_("MatchRotated", self.match_rotated) # scan_type is special because we save it immediately when we set it. def get_scan_type(self, app_mode): if app_mode == AppMode.PICTURE: return self.get_value("ScanTypePicture", ScanType.FUZZYBLOCK) elif app_mode == AppMode.MUSIC: return self.get_value("ScanTypeMusic", ScanType.TAG) else: return self.get_value("ScanTypeStandard", ScanType.CONTENTS) def set_scan_type(self, app_mode, value): if app_mode == AppMode.PICTURE: self.set_value("ScanTypePicture", value) elif app_mode == AppMode.MUSIC: self.set_value("ScanTypeMusic", value) else: self.set_value("ScanTypeStandard", value)
15,700
Python
.py
316
40.835443
120
0.661845
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,070
deletion_options.py
arsenetar_dupeguru/qt/deletion_options.py
# Created By: Virgil Dupras # Created On: 2012-05-30 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QDialog, QVBoxLayout, QLabel, QCheckBox, QDialogButtonBox from hscommon.trans import trget from qt.radio_box import RadioBox tr = trget("ui") class DeletionOptions(QDialog): def __init__(self, parent, model, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self.model = model self._setupUi() self.model.view = self self.linkCheckbox.stateChanged.connect(self.linkCheckboxChanged) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def _setupUi(self): self.setWindowTitle(tr("Deletion Options")) self.resize(400, 270) self.verticalLayout = QVBoxLayout(self) self.msgLabel = QLabel() self.verticalLayout.addWidget(self.msgLabel) self.linkCheckbox = QCheckBox(tr("Link deleted files")) self.verticalLayout.addWidget(self.linkCheckbox) text = tr( "After having deleted a duplicate, place a link targeting the reference file " "to replace the deleted file." ) self.linkMessageLabel = QLabel(text) self.linkMessageLabel.setWordWrap(True) self.verticalLayout.addWidget(self.linkMessageLabel) self.linkTypeRadio = RadioBox(items=[tr("Symlink"), tr("Hardlink")], spread=False) self.verticalLayout.addWidget(self.linkTypeRadio) if not self.model.supports_links(): self.linkCheckbox.setEnabled(False) self.linkCheckbox.setText(self.linkCheckbox.text() + tr(" (unsupported)")) self.directCheckbox = QCheckBox(tr("Directly delete files")) self.verticalLayout.addWidget(self.directCheckbox) text = tr( "Instead of sending files to trash, delete them directly. This option is usually " "used as a workaround when the normal deletion method doesn't work." ) self.directMessageLabel = QLabel(text) self.directMessageLabel.setWordWrap(True) self.verticalLayout.addWidget(self.directMessageLabel) self.buttonBox = QDialogButtonBox() self.buttonBox.addButton(tr("Proceed"), QDialogButtonBox.AcceptRole) self.buttonBox.addButton(tr("Cancel"), QDialogButtonBox.RejectRole) self.verticalLayout.addWidget(self.buttonBox) # --- Signals def linkCheckboxChanged(self, changed: int): self.model.link_deleted = bool(changed) # --- model --> view def update_msg(self, msg: str): self.msgLabel.setText(msg) def show(self): self.linkCheckbox.setChecked(self.model.link_deleted) self.linkTypeRadio.selected_index = 1 if self.model.use_hardlinks else 0 self.directCheckbox.setChecked(self.model.direct) result = self.exec() self.model.link_deleted = self.linkCheckbox.isChecked() self.model.use_hardlinks = self.linkTypeRadio.selected_index == 1 self.model.direct = self.directCheckbox.isChecked() return result == QDialog.Accepted def set_hardlink_option_enabled(self, is_enabled: bool): self.linkTypeRadio.setEnabled(is_enabled)
3,578
Python
.py
72
42.097222
94
0.70329
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,071
directories_dialog.py
arsenetar_dupeguru/qt/directories_dialog.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import QRect, Qt from PyQt5.QtWidgets import ( QListView, QWidget, QFileDialog, QHeaderView, QVBoxLayout, QHBoxLayout, QTreeView, QAbstractItemView, QSpacerItem, QSizePolicy, QPushButton, QMainWindow, QMenuBar, QMenu, QLabel, QComboBox, ) from PyQt5.QtGui import QPixmap, QIcon from hscommon.trans import trget from core.app import AppMode from qt.radio_box import RadioBox from qt.recent import Recent from qt.util import move_to_screen_center, create_actions from qt import platform from qt.directories_model import DirectoriesModel, DirectoriesDelegate tr = trget("ui") class DirectoriesDialog(QMainWindow): def __init__(self, app, **kwargs): super().__init__(None, **kwargs) self.app = app self.specific_actions = set() self.lastAddedFolder = platform.INITIAL_FOLDER_IN_DIALOGS self.recentFolders = Recent(self.app, "recentFolders") self._setupUi() self._updateScanTypeList() self.directoriesModel = DirectoriesModel(self.app.model.directory_tree, view=self.treeView) self.directoriesDelegate = DirectoriesDelegate() self.treeView.setItemDelegate(self.directoriesDelegate) self._setupColumns() self.app.recentResults.addMenu(self.menuLoadRecent) self.app.recentResults.addMenu(self.menuRecentResults) self.recentFolders.addMenu(self.menuRecentFolders) self._updateAddButton() self._updateRemoveButton() self._updateLoadResultsButton() self._updateActionsState() self._setupBindings() def _setupBindings(self): self.appModeRadioBox.itemSelected.connect(self.appModeButtonSelected) self.showPreferencesButton.clicked.connect(self.app.actionPreferences.trigger) self.scanButton.clicked.connect(self.scanButtonClicked) self.loadResultsButton.clicked.connect(self.actionLoadResults.trigger) self.addFolderButton.clicked.connect(self.actionAddFolder.trigger) self.removeFolderButton.clicked.connect(self.removeFolderButtonClicked) self.treeView.selectionModel().selectionChanged.connect(self.selectionChanged) self.app.recentResults.itemsChanged.connect(self._updateLoadResultsButton) self.recentFolders.itemsChanged.connect(self._updateAddButton) self.recentFolders.mustOpenItem.connect(self.app.model.add_directory) self.directoriesModel.foldersAdded.connect(self.directoriesModelAddedFolders) self.app.willSavePrefs.connect(self.appWillSavePrefs) def _setupActions(self): # (name, shortcut, icon, desc, func) ACTIONS = [ ( "actionLoadResults", "Ctrl+L", "", tr("Load Results..."), self.loadResultsTriggered, ), ( "actionShowResultsWindow", "", "", tr("Scan Results"), self.app.showResultsWindow, ), ("actionAddFolder", "", "", tr("Add Folder..."), self.addFolderTriggered), ("actionLoadDirectories", "", "", tr("Load Directories..."), self.loadDirectoriesTriggered), ("actionSaveDirectories", "", "", tr("Save Directories..."), self.saveDirectoriesTriggered), ] create_actions(ACTIONS, self) if self.app.use_tabs: # Keep track of actions which should only be accessible from this window self.specific_actions.add(self.actionLoadDirectories) self.specific_actions.add(self.actionSaveDirectories) def _setupMenu(self): if not self.app.use_tabs: # we are our own QMainWindow, we need our own menu bar self.menubar = QMenuBar(self) self.menubar.setGeometry(QRect(0, 0, 42, 22)) self.menuFile = QMenu(self.menubar) self.menuFile.setTitle(tr("File")) self.menuView = QMenu(self.menubar) self.menuView.setTitle(tr("View")) self.menuHelp = QMenu(self.menubar) self.menuHelp.setTitle(tr("Help")) self.setMenuBar(self.menubar) menubar = self.menubar else: # we are part of a tab widget, we populate its window's menubar instead self.menuFile = self.app.main_window.menuFile self.menuView = self.app.main_window.menuView self.menuHelp = self.app.main_window.menuHelp menubar = self.app.main_window.menubar self.menuLoadRecent = QMenu(self.menuFile) self.menuLoadRecent.setTitle(tr("Load Recent Results")) self.menuFile.addAction(self.actionLoadResults) self.menuFile.addAction(self.menuLoadRecent.menuAction()) self.menuFile.addSeparator() self.menuFile.addAction(self.app.actionClearCache) self.menuFile.addSeparator() self.menuFile.addAction(self.actionLoadDirectories) self.menuFile.addAction(self.actionSaveDirectories) self.menuFile.addSeparator() self.menuFile.addAction(self.app.actionQuit) self.menuView.addAction(self.app.actionDirectoriesWindow) self.menuView.addAction(self.actionShowResultsWindow) self.menuView.addAction(self.app.actionIgnoreList) self.menuView.addAction(self.app.actionExcludeList) self.menuView.addSeparator() self.menuView.addAction(self.app.actionPreferences) self.menuHelp.addAction(self.app.actionShowHelp) self.menuHelp.addAction(self.app.actionOpenDebugLog) self.menuHelp.addAction(self.app.actionAbout) menubar.addAction(self.menuFile.menuAction()) menubar.addAction(self.menuView.menuAction()) menubar.addAction(self.menuHelp.menuAction()) # Recent folders menu self.menuRecentFolders = QMenu() self.menuRecentFolders.addAction(self.actionAddFolder) self.menuRecentFolders.addSeparator() # Recent results menu self.menuRecentResults = QMenu() self.menuRecentResults.addAction(self.actionLoadResults) self.menuRecentResults.addSeparator() def _setupUi(self): self.setWindowTitle(self.app.NAME) self.resize(420, 338) self.centralwidget = QWidget(self) self.verticalLayout = QVBoxLayout(self.centralwidget) self.verticalLayout.setContentsMargins(4, 0, 4, 0) self.verticalLayout.setSpacing(0) hl = QHBoxLayout() label = QLabel(tr("Application Mode:"), self) label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) hl.addWidget(label) self.appModeRadioBox = RadioBox(self, items=[tr("Standard"), tr("Music"), tr("Picture")], spread=False) hl.addWidget(self.appModeRadioBox) self.verticalLayout.addLayout(hl) hl = QHBoxLayout() hl.setAlignment(Qt.AlignLeft) label = QLabel(tr("Scan Type:"), self) label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) hl.addWidget(label) self.scanTypeComboBox = QComboBox(self) self.scanTypeComboBox.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)) self.scanTypeComboBox.setMaximumWidth(400) hl.addWidget(self.scanTypeComboBox) self.showPreferencesButton = QPushButton(tr("More Options"), self.centralwidget) self.showPreferencesButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) hl.addWidget(self.showPreferencesButton) self.verticalLayout.addLayout(hl) self.promptLabel = QLabel(tr('Select folders to scan and press "Scan".'), self.centralwidget) self.verticalLayout.addWidget(self.promptLabel) self.treeView = QTreeView(self.centralwidget) self.treeView.setSelectionMode(QAbstractItemView.ExtendedSelection) self.treeView.setSelectionBehavior(QAbstractItemView.SelectRows) self.treeView.setAcceptDrops(True) triggers = ( QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed | QAbstractItemView.SelectedClicked ) self.treeView.setEditTriggers(triggers) self.treeView.setDragDropOverwriteMode(True) self.treeView.setDragDropMode(QAbstractItemView.DropOnly) self.treeView.setUniformRowHeights(True) self.verticalLayout.addWidget(self.treeView) self.horizontalLayout = QHBoxLayout() self.removeFolderButton = QPushButton(self.centralwidget) self.removeFolderButton.setIcon(QIcon(QPixmap(":/minus"))) self.removeFolderButton.setShortcut("Del") self.horizontalLayout.addWidget(self.removeFolderButton) self.addFolderButton = QPushButton(self.centralwidget) self.addFolderButton.setIcon(QIcon(QPixmap(":/plus"))) self.horizontalLayout.addWidget(self.addFolderButton) spacer_item = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacer_item) self.loadResultsButton = QPushButton(self.centralwidget) self.loadResultsButton.setText(tr("Load Results")) self.horizontalLayout.addWidget(self.loadResultsButton) self.scanButton = QPushButton(self.centralwidget) self.scanButton.setText(tr("Scan")) self.scanButton.setDefault(True) self.horizontalLayout.addWidget(self.scanButton) self.verticalLayout.addLayout(self.horizontalLayout) self.setCentralWidget(self.centralwidget) self._setupActions() self._setupMenu() if self.app.prefs.directoriesWindowRect is not None: self.setGeometry(self.app.prefs.directoriesWindowRect) else: move_to_screen_center(self) def _setupColumns(self): header = self.treeView.header() header.setStretchLastSection(False) header.setSectionResizeMode(0, QHeaderView.Stretch) header.setSectionResizeMode(1, QHeaderView.Fixed) header.resizeSection(1, 100) def _updateActionsState(self): self.actionShowResultsWindow.setEnabled(self.app.resultWindow is not None) def _updateAddButton(self): if self.recentFolders.isEmpty(): self.addFolderButton.setMenu(None) else: self.addFolderButton.setMenu(self.menuRecentFolders) def _updateRemoveButton(self): indexes = self.treeView.selectedIndexes() if not indexes: self.removeFolderButton.setEnabled(False) return self.removeFolderButton.setEnabled(True) def _updateLoadResultsButton(self): if self.app.recentResults.isEmpty(): self.loadResultsButton.setMenu(None) else: self.loadResultsButton.setMenu(self.menuRecentResults) def _updateScanTypeList(self): try: self.scanTypeComboBox.currentIndexChanged[int].disconnect(self.scanTypeChanged) except TypeError: # Not connected, ignore pass self.scanTypeComboBox.clear() scan_options = self.app.model.SCANNER_CLASS.get_scan_options() for scan_option in scan_options: self.scanTypeComboBox.addItem(scan_option.label) SCAN_TYPE_ORDER = [so.scan_type for so in scan_options] selected_scan_type = self.app.prefs.get_scan_type(self.app.model.app_mode) scan_type_index = SCAN_TYPE_ORDER.index(selected_scan_type) self.scanTypeComboBox.setCurrentIndex(scan_type_index) self.scanTypeComboBox.currentIndexChanged[int].connect(self.scanTypeChanged) self.app._update_options() # --- QWidget overrides def closeEvent(self, event): event.accept() if self.app.model.results.is_modified: title = tr("Unsaved results") msg = tr("You have unsaved results, do you really want to quit?") if not self.app.confirm(title, msg): event.ignore() if event.isAccepted(): self.app.shutdown() # --- Events def addFolderTriggered(self): no_native = not self.app.prefs.use_native_dialogs title = tr("Select a folder to add to the scanning list") file_dialog = QFileDialog(self, title, self.lastAddedFolder) file_dialog.setFileMode(QFileDialog.DirectoryOnly) file_dialog.setOption(QFileDialog.DontUseNativeDialog, no_native) if no_native: file_view = file_dialog.findChild(QListView, "listView") if file_view: file_view.setSelectionMode(QAbstractItemView.MultiSelection) f_tree_view = file_dialog.findChild(QTreeView) if f_tree_view: f_tree_view.setSelectionMode(QAbstractItemView.MultiSelection) if not file_dialog.exec(): return paths = file_dialog.selectedFiles() self.lastAddedFolder = paths[-1] [self.app.model.add_directory(path) for path in paths] [self.recentFolders.insertItem(path) for path in paths] def appModeButtonSelected(self, index): if index == 2: mode = AppMode.PICTURE elif index == 1: mode = AppMode.MUSIC else: mode = AppMode.STANDARD self.app.model.app_mode = mode self._updateScanTypeList() def appWillSavePrefs(self): self.app.prefs.directoriesWindowRect = self.geometry() def directoriesModelAddedFolders(self, folders): for folder in folders: self.recentFolders.insertItem(folder) def loadResultsTriggered(self): title = tr("Select a results file to load") files = ";;".join([tr("dupeGuru Results (*.dupeguru)"), tr("All Files (*.*)")]) destination = QFileDialog.getOpenFileName(self, title, "", files)[0] if destination: self.app.model.load_from(destination) self.app.recentResults.insertItem(destination) def loadDirectoriesTriggered(self): title = tr("Select a directories file to load") files = ";;".join([tr("dupeGuru Directories (*.dupegurudirs)"), tr("All Files (*.*)")]) destination = QFileDialog.getOpenFileName(self, title, "", files)[0] if destination: self.app.model.load_directories(destination) def removeFolderButtonClicked(self): self.directoriesModel.model.remove_selected() def saveDirectoriesTriggered(self): title = tr("Select a file to save your directories to") files = tr("dupeGuru Directories (*.dupegurudirs)") destination, chosen_filter = QFileDialog.getSaveFileName(self, title, "", files) if destination: if not destination.endswith(".dupegurudirs"): destination = f"{destination}.dupegurudirs" self.app.model.save_directories_as(destination) def scanButtonClicked(self): if self.app.model.results.is_modified: title = tr("Start a new scan") msg = tr("You have unsaved results, do you really want to continue?") if not self.app.confirm(title, msg): return self.app.model.start_scanning(self.app.prefs.profile_scan) def scanTypeChanged(self, index): scan_options = self.app.model.SCANNER_CLASS.get_scan_options() self.app.prefs.set_scan_type(self.app.model.app_mode, scan_options[index].scan_type) self.app._update_options() def selectionChanged(self, selected, deselected): self._updateRemoveButton()
15,794
Python
.py
329
38.732523
114
0.68607
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,072
problem_table.py
arsenetar_dupeguru/qt/problem_table.py
# Created By: Virgil Dupras # Created On: 2010-04-12 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from qt.column import Column from qt.table import Table class ProblemTable(Table): COLUMNS = [ Column("path", default_width=150), Column("msg", default_width=150), ] def __init__(self, model, view, **kwargs): super().__init__(model, view, **kwargs) # we have to prevent Return from initiating editing. # self.view.editSelected = lambda: None
727
Python
.py
18
36.277778
89
0.700709
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,073
results_model.py
arsenetar_dupeguru/qt/results_model.py
# Created By: Virgil Dupras # Created On: 2009-04-23 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import Qt, pyqtSignal, QModelIndex from PyQt5.QtGui import QBrush, QFont, QFontMetrics from PyQt5.QtWidgets import QTableView from qt.table import Table class ResultsModel(Table): def __init__(self, app, view, **kwargs): model = app.model.result_table super().__init__(model, view, **kwargs) view.horizontalHeader().setSortIndicator(1, Qt.AscendingOrder) font = view.font() font.setPointSize(app.prefs.tableFontSize) view.setFont(font) fm = QFontMetrics(font) view.verticalHeader().setDefaultSectionSize(fm.height() + 2) app.willSavePrefs.connect(self.appWillSavePrefs) self.prefs = app.prefs def _getData(self, row, column, role): if column.name == "marked": if role == Qt.BackgroundRole and row.isref: return QBrush(self.prefs.result_table_ref_background_color) if role == Qt.CheckStateRole and row.markable: return Qt.Checked if row.marked else Qt.Unchecked return None if role == Qt.DisplayRole: data = row.data_delta if self.model.delta_values else row.data return data[column.name] elif role == Qt.ForegroundRole: if row.isref: return QBrush(self.prefs.result_table_ref_foreground_color) elif row.is_cell_delta(column.name): return QBrush(self.prefs.result_table_delta_foreground_color) elif role == Qt.BackgroundRole: if row.isref: return QBrush(self.prefs.result_table_ref_background_color) elif role == Qt.FontRole: font = QFont(self.view.font()) if self.prefs.reference_bold_font: font.setBold(row.isref) return font elif role == Qt.EditRole and column.name == "name": return row.data[column.name] return None def _getFlags(self, row, column): flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable if column.name == "marked": if row.markable: flags |= Qt.ItemIsUserCheckable elif column.name == "name": flags |= Qt.ItemIsEditable return flags def _setData(self, row, column, value, role): if role == Qt.CheckStateRole: if column.name == "marked": row.marked = bool(value) return True elif role == Qt.EditRole and column.name == "name": return self.model.rename_selected(value) return False def sort(self, column, order): column = self.model.COLUMNS[column] self.model.sort(column.name, order == Qt.AscendingOrder) # --- Properties @property def power_marker(self): return self.model.power_marker @power_marker.setter def power_marker(self, value): self.model.power_marker = value @property def delta_values(self): return self.model.delta_values @delta_values.setter def delta_values(self, value): self.model.delta_values = value # --- Events def appWillSavePrefs(self): self.model._columns.save_columns() # --- model --> view def invalidate_markings(self): # redraw view # HACK. this is the only way I found to update the widget without reseting everything self.view.scroll(0, 1) self.view.scroll(0, -1) class ResultsView(QTableView): # --- Override def keyPressEvent(self, event): if event.text() == " ": self.spacePressed.emit() return super().keyPressEvent(event) def mouseDoubleClickEvent(self, event): self.doubleClicked.emit(QModelIndex()) # We don't call the superclass' method because the default behavior is to rename the cell. # --- Signals spacePressed = pyqtSignal()
4,212
Python
.py
102
32.617647
98
0.638964
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,074
ignore_list_dialog.py
arsenetar_dupeguru/qt/ignore_list_dialog.py
# Created By: Virgil Dupras # Created On: 2012-03-13 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import Qt from PyQt5.QtWidgets import ( QDialog, QVBoxLayout, QPushButton, QTableView, QAbstractItemView, ) from hscommon.trans import trget from qt.util import horizontal_wrap from qt.ignore_list_table import IgnoreListTable tr = trget("ui") class IgnoreListDialog(QDialog): def __init__(self, parent, model, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self.specific_actions = frozenset() self._setupUi() self.model = model self.model.view = self self.table = IgnoreListTable(self.model.ignore_list_table, view=self.tableView) self.removeSelectedButton.clicked.connect(self.model.remove_selected) self.clearButton.clicked.connect(self.model.clear) self.closeButton.clicked.connect(self.accept) def _setupUi(self): self.setWindowTitle(tr("Ignore List")) self.resize(540, 330) self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.tableView = QTableView() self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers) self.tableView.setSelectionMode(QAbstractItemView.ExtendedSelection) self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows) self.tableView.setShowGrid(False) self.tableView.horizontalHeader().setStretchLastSection(True) self.tableView.verticalHeader().setDefaultSectionSize(18) self.tableView.verticalHeader().setHighlightSections(False) self.tableView.verticalHeader().setVisible(False) self.tableView.setWordWrap(False) self.verticalLayout.addWidget(self.tableView) self.removeSelectedButton = QPushButton(tr("Remove Selected")) self.clearButton = QPushButton(tr("Clear")) self.closeButton = QPushButton(tr("Close")) self.verticalLayout.addLayout( horizontal_wrap([self.removeSelectedButton, self.clearButton, None, self.closeButton]) ) # --- model --> view def show(self): super().show()
2,502
Python
.py
56
38.25
98
0.723544
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,075
tabbed_window.py
arsenetar_dupeguru/qt/tabbed_window.py
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import QRect, pyqtSlot, Qt, QEvent from PyQt5.QtWidgets import ( QWidget, QVBoxLayout, QHBoxLayout, QMainWindow, QTabWidget, QMenu, QTabBar, QStackedWidget, ) from hscommon.trans import trget from qt.util import move_to_screen_center, create_actions from qt.directories_dialog import DirectoriesDialog from qt.result_window import ResultWindow from qt.ignore_list_dialog import IgnoreListDialog from qt.exclude_list_dialog import ExcludeListDialog tr = trget("ui") class TabWindow(QMainWindow): def __init__(self, app, **kwargs): super().__init__(None, **kwargs) self.app = app self.pages = {} # This is currently not used anywhere self.menubar = None self.menuList = set() self.last_index = -1 self.previous_widget_actions = set() self._setupUi() self.app.willSavePrefs.connect(self.appWillSavePrefs) def _setupActions(self): # (name, shortcut, icon, desc, func) ACTIONS = [ ( "actionToggleTabs", "", "", tr("Show tab bar"), self.toggleTabBar, ), ] create_actions(ACTIONS, self) self.actionToggleTabs.setCheckable(True) self.actionToggleTabs.setChecked(True) def _setupUi(self): self.setWindowTitle(self.app.NAME) self.resize(640, 480) self.tabWidget = QTabWidget() # self.tabWidget.setTabPosition(QTabWidget.South) self.tabWidget.setContentsMargins(0, 0, 0, 0) # self.tabWidget.setTabBarAutoHide(True) # This gets rid of the annoying margin around the TabWidget: self.tabWidget.setDocumentMode(True) self._setupActions() self._setupMenu() # This should be the same as self.centralWidget.setLayout(self.verticalLayout) self.verticalLayout = QVBoxLayout(self.tabWidget) # self.verticalLayout.addWidget(self.tabWidget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.tabWidget.setTabsClosable(True) self.setCentralWidget(self.tabWidget) # only for QMainWindow self.tabWidget.currentChanged.connect(self.updateMenuBar) self.tabWidget.tabCloseRequested.connect(self.onTabCloseRequested) self.updateMenuBar(self.tabWidget.currentIndex()) self.restoreGeometry() def restoreGeometry(self): if self.app.prefs.mainWindowRect is not None: self.setGeometry(self.app.prefs.mainWindowRect) if self.app.prefs.mainWindowIsMaximized: self.showMaximized() def _setupMenu(self): """Setup the menubar boiler plates which will be filled by the underlying tab's widgets whenever they are instantiated.""" self.menubar = self.menuBar() # QMainWindow, similar to just QMenuBar() here # self.setMenuBar(self.menubar) # already set if QMainWindow class self.menubar.setGeometry(QRect(0, 0, 100, 22)) self.menuFile = QMenu(self.menubar) self.menuFile.setTitle(tr("File")) self.menuMark = QMenu(self.menubar) self.menuMark.setTitle(tr("Mark")) self.menuActions = QMenu(self.menubar) self.menuActions.setTitle(tr("Actions")) self.menuColumns = QMenu(self.menubar) self.menuColumns.setTitle(tr("Columns")) self.menuView = QMenu(self.menubar) self.menuView.setTitle(tr("View")) self.menuHelp = QMenu(self.menubar) self.menuHelp.setTitle(tr("Help")) self.menuView.addAction(self.actionToggleTabs) self.menuView.addSeparator() self.menuList.add(self.menuFile) self.menuList.add(self.menuMark) self.menuList.add(self.menuActions) self.menuList.add(self.menuColumns) self.menuList.add(self.menuView) self.menuList.add(self.menuHelp) @pyqtSlot(int) def updateMenuBar(self, page_index=-1): if page_index < 0: return current_index = self.getCurrentIndex() active_widget = self.getWidgetAtIndex(current_index) if self.last_index < 0: self.last_index = current_index self.previous_widget_actions = active_widget.specific_actions return page_type = type(active_widget).__name__ for menu in self.menuList: if menu is self.menuColumns or menu is self.menuActions or menu is self.menuMark: if not isinstance(active_widget, ResultWindow): menu.setEnabled(False) continue else: menu.setEnabled(True) for action in menu.actions(): if action not in active_widget.specific_actions: if action in self.previous_widget_actions: action.setEnabled(False) continue action.setEnabled(True) self.app.directories_dialog.actionShowResultsWindow.setEnabled( False if page_type == "ResultWindow" else self.app.resultWindow is not None ) self.app.actionIgnoreList.setEnabled( True if self.app.ignoreListDialog is not None and not page_type == "IgnoreListDialog" else False ) self.app.actionDirectoriesWindow.setEnabled(False if page_type == "DirectoriesDialog" else True) self.app.actionExcludeList.setEnabled( True if self.app.excludeListDialog is not None and not page_type == "ExcludeListDialog" else False ) self.previous_widget_actions = active_widget.specific_actions self.last_index = current_index def createPage(self, cls, **kwargs): app = kwargs.get("app", self.app) page = None if cls == "DirectoriesDialog": page = DirectoriesDialog(app) elif cls == "ResultWindow": parent = kwargs.get("parent", self) page = ResultWindow(parent, app) elif cls == "IgnoreListDialog": parent = kwargs.get("parent", self) model = kwargs.get("model") page = IgnoreListDialog(parent, model) page.accepted.connect(self.onDialogAccepted) elif cls == "ExcludeListDialog": app = kwargs.get("app", app) parent = kwargs.get("parent", self) model = kwargs.get("model") page = ExcludeListDialog(app, parent, model) page.accepted.connect(self.onDialogAccepted) self.pages[cls] = page # Not used, might remove return page def addTab(self, page, title, switch=False): # Warning: this supposedly takes ownership of the page index = self.tabWidget.addTab(page, title) if isinstance(page, DirectoriesDialog): self.tabWidget.tabBar().setTabButton(index, QTabBar.RightSide, None) if switch: self.setCurrentIndex(index) return index def showTab(self, page): index = self.indexOfWidget(page) self.setCurrentIndex(index) def indexOfWidget(self, widget): return self.tabWidget.indexOf(widget) def setCurrentIndex(self, index): return self.tabWidget.setCurrentIndex(index) def removeTab(self, index): return self.tabWidget.removeTab(index) def isTabVisible(self, index): return self.tabWidget.isTabVisible(index) def getCurrentIndex(self): return self.tabWidget.currentIndex() def getWidgetAtIndex(self, index): return self.tabWidget.widget(index) def getCount(self): return self.tabWidget.count() # --- Events def appWillSavePrefs(self): # Right now this is useless since the first spawned dialog inside the # QTabWidget will assign its geometry after restoring it prefs = self.app.prefs prefs.mainWindowIsMaximized = self.isMaximized() if not self.isMaximized(): prefs.mainWindowRect = self.geometry() def showEvent(self, event): if not self.isMaximized(): # have to do this here as the frameGeometry is not correct until shown move_to_screen_center(self) super().showEvent(event) def changeEvent(self, event): if event.type() == QEvent.WindowStateChange and not self.isMaximized(): move_to_screen_center(self) super().changeEvent(event) def closeEvent(self, close_event): # Force closing of our tabbed widgets in reverse order so that the # directories dialog (which usually is at index 0) will be called last for index in range(self.getCount() - 1, -1, -1): self.getWidgetAtIndex(index).closeEvent(close_event) self.appWillSavePrefs() @pyqtSlot(int) def onTabCloseRequested(self, index): current_widget = self.getWidgetAtIndex(index) if isinstance(current_widget, DirectoriesDialog): # if we close this one, the application quits. Force user to use the # menu or shortcut. But this is useless if we don't have a button # set up to make a close request anyway. This check could be removed. return self.removeTab(index) @pyqtSlot() def onDialogAccepted(self): """Remove tabbed dialog when Accepted/Done (close button clicked).""" widget = self.sender() index = self.indexOfWidget(widget) if index > -1: self.removeTab(index) @pyqtSlot() def toggleTabBar(self): value = self.sender().isChecked() self.actionToggleTabs.setChecked(value) self.tabWidget.tabBar().setVisible(value) class TabBarWindow(TabWindow): """Implementation which uses a separate QTabBar and QStackedWidget. The Tab bar is placed next to the menu bar to save real estate.""" def __init__(self, app, **kwargs): super().__init__(app, **kwargs) def _setupUi(self): self.setWindowTitle(self.app.NAME) self.resize(640, 480) self.tabBar = QTabBar() self.verticalLayout = QVBoxLayout() self.verticalLayout.setContentsMargins(0, 0, 0, 0) self._setupActions() self._setupMenu() self.centralWidget = QWidget(self) self.setCentralWidget(self.centralWidget) self.stackedWidget = QStackedWidget() self.centralWidget.setLayout(self.verticalLayout) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.addWidget(self.menubar, 0, Qt.AlignTop) self.horizontalLayout.addWidget(self.tabBar, 0, Qt.AlignTop) self.verticalLayout.addLayout(self.horizontalLayout) self.verticalLayout.addWidget(self.stackedWidget) self.tabBar.currentChanged.connect(self.showTabIndex) self.tabBar.tabCloseRequested.connect(self.onTabCloseRequested) self.stackedWidget.currentChanged.connect(self.updateMenuBar) self.stackedWidget.widgetRemoved.connect(self.onRemovedWidget) self.tabBar.setTabsClosable(True) self.restoreGeometry() def addTab(self, page, title, switch=True): stack_index = self.stackedWidget.addWidget(page) self.tabBar.insertTab(stack_index, title) if isinstance(page, DirectoriesDialog): self.tabBar.setTabButton(stack_index, QTabBar.RightSide, None) if switch: # switch to the added tab immediately upon creation self.setTabIndex(stack_index) return stack_index @pyqtSlot(int) def showTabIndex(self, index): # The tab bar's indices should be aligned with the stackwidget's if index >= 0 and index <= self.stackedWidget.count(): self.stackedWidget.setCurrentIndex(index) def indexOfWidget(self, widget): # Warning: this may return -1 if widget is not a child of stackedwidget return self.stackedWidget.indexOf(widget) def setCurrentIndex(self, tab_index): self.setTabIndex(tab_index) # The signal will handle switching the stackwidget's widget # self.stackedWidget.setCurrentWidget(self.stackedWidget.widget(tab_index)) def setCurrentWidget(self, widget): """Sets the current Tab on TabBar for this widget.""" self.tabBar.setCurrentIndex(self.indexOfWidget(widget)) @pyqtSlot(int) def setTabIndex(self, index): if index is None: return self.tabBar.setCurrentIndex(index) @pyqtSlot(int) def onRemovedWidget(self, index): self.removeTab(index) @pyqtSlot(int) def removeTab(self, index): """Remove the tab, but not the widget (it should already be removed)""" return self.tabBar.removeTab(index) @pyqtSlot(int) def removeWidget(self, widget): return self.stackedWidget.removeWidget(widget) def isTabVisible(self, index): return self.tabBar.isTabVisible(index) def getCurrentIndex(self): return self.stackedWidget.currentIndex() def getWidgetAtIndex(self, index): return self.stackedWidget.widget(index) def getCount(self): return self.stackedWidget.count() @pyqtSlot() def toggleTabBar(self): value = self.sender().isChecked() self.actionToggleTabs.setChecked(value) self.tabBar.setVisible(value) @pyqtSlot(int) def onTabCloseRequested(self, index): target_widget = self.getWidgetAtIndex(index) if isinstance(target_widget, DirectoriesDialog): # On MacOS, the tab has a close button even though we explicitely # set it to None in order to hide it. This should prevent # the "Directories" tab from closing by mistake. return # target_widget.close() # seems unnecessary # Removing the widget should trigger tab removal via the signal self.removeWidget(self.getWidgetAtIndex(index)) @pyqtSlot() def onDialogAccepted(self): """Remove tabbed dialog when Accepted/Done (close button clicked).""" widget = self.sender() self.removeWidget(widget)
14,307
Python
.py
319
35.818182
110
0.666403
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,076
radio_box.py
arsenetar_dupeguru/qt/radio_box.py
# Created On: 2010-06-02 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import pyqtSignal from PyQt5.QtWidgets import QWidget, QHBoxLayout, QRadioButton from qt.util import horizontal_spacer class RadioBox(QWidget): def __init__(self, parent=None, items=None, spread=True, **kwargs): # If spread is False, insert a spacer in the layout so that the items don't use all the # space they're given but rather align left. if items is None: items = [] super().__init__(parent, **kwargs) self._buttons = [] self._labels = items self._selected_index = 0 self._spacer = horizontal_spacer() if not spread else None self._layout = QHBoxLayout(self) self._update_buttons() # --- Private def _update_buttons(self): if self._spacer is not None: self._layout.removeItem(self._spacer) to_remove = self._buttons[len(self._labels) :] for button in to_remove: self._layout.removeWidget(button) button.setParent(None) del self._buttons[len(self._labels) :] to_add = self._labels[len(self._buttons) :] for _ in to_add: button = QRadioButton(self) self._buttons.append(button) self._layout.addWidget(button) button.toggled.connect(self.buttonToggled) if self._spacer is not None: self._layout.addItem(self._spacer) if not self._buttons: return for button, label in zip(self._buttons, self._labels): button.setText(label) self._update_selection() def _update_selection(self): self._selected_index = max(0, min(self._selected_index, len(self._buttons) - 1)) selected = self._buttons[self._selected_index] selected.setChecked(True) # --- Event Handlers def buttonToggled(self): for i, button in enumerate(self._buttons): if button.isChecked(): self._selected_index = i self.itemSelected.emit(i) break # --- Signals itemSelected = pyqtSignal(int) # --- Properties @property def buttons(self): return self._buttons[:] @property def items(self): return self._labels[:] @items.setter def items(self, value): self._labels = value self._update_buttons() @property def selected_index(self): return self._selected_index @selected_index.setter def selected_index(self, value): self._selected_index = value self._update_selection()
2,873
Python
.py
75
30.253333
95
0.628725
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,077
exclude_list_dialog.py
arsenetar_dupeguru/qt/exclude_list_dialog.py
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import re from PyQt5.QtCore import Qt, pyqtSlot from PyQt5.QtWidgets import ( QPushButton, QLineEdit, QVBoxLayout, QGridLayout, QDialog, QTableView, QAbstractItemView, QSpacerItem, QSizePolicy, QHeaderView, ) from qt.exclude_list_table import ExcludeListTable from core.exclude import AlreadyThereException from hscommon.trans import trget tr = trget("ui") class ExcludeListDialog(QDialog): def __init__(self, app, parent, model, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self.app = app self.specific_actions = frozenset() self._setupUI() self.model = model # ExcludeListDialogCore self.model.view = self self.table = ExcludeListTable(app, view=self.tableView) # Qt ExcludeListTable self._row_matched = False # test if at least one row matched our test string self._input_styled = False self.buttonAdd.clicked.connect(self.addStringFromLineEdit) self.buttonRemove.clicked.connect(self.removeSelected) self.buttonRestore.clicked.connect(self.restoreDefaults) self.buttonClose.clicked.connect(self.accept) self.buttonHelp.clicked.connect(self.display_help_message) self.buttonTestString.clicked.connect(self.onTestStringButtonClicked) self.inputLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_table_style) def _setupUI(self): layout = QVBoxLayout(self) gridlayout = QGridLayout() self.buttonAdd = QPushButton(tr("Add")) self.buttonRemove = QPushButton(tr("Remove Selected")) self.buttonRestore = QPushButton(tr("Restore defaults")) self.buttonTestString = QPushButton(tr("Test string")) self.buttonClose = QPushButton(tr("Close")) self.buttonHelp = QPushButton(tr("Help")) self.inputLine = QLineEdit() self.testLine = QLineEdit() self.tableView = QTableView() triggers = ( QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed | QAbstractItemView.SelectedClicked ) self.tableView.setEditTriggers(triggers) self.tableView.setSelectionMode(QTableView.ExtendedSelection) self.tableView.setSelectionBehavior(QTableView.SelectRows) self.tableView.setShowGrid(False) vheader = self.tableView.verticalHeader() vheader.setSectionsMovable(True) vheader.setVisible(False) hheader = self.tableView.horizontalHeader() hheader.setSectionsMovable(False) hheader.setSectionResizeMode(QHeaderView.Fixed) hheader.setStretchLastSection(True) hheader.setHighlightSections(False) hheader.setVisible(True) gridlayout.addWidget(self.inputLine, 0, 0) gridlayout.addWidget(self.buttonAdd, 0, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRemove, 1, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRestore, 2, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonHelp, 3, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonClose, 4, 1) gridlayout.addWidget(self.tableView, 1, 0, 6, 1) gridlayout.addItem(QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding), 4, 1) gridlayout.addWidget(self.buttonTestString, 6, 1) gridlayout.addWidget(self.testLine, 6, 0) layout.addLayout(gridlayout) self.inputLine.setPlaceholderText(tr("Type a python regular expression here...")) self.inputLine.setFocus() self.testLine.setPlaceholderText(tr("Type a file system path or filename here...")) self.testLine.setClearButtonEnabled(True) # --- model --> view def show(self): super().show() self.inputLine.setFocus() @pyqtSlot() def addStringFromLineEdit(self): text = self.inputLine.text() if not text: return try: self.model.add(text) except AlreadyThereException: self.app.show_message("Expression already in the list.") return except Exception as e: self.app.show_message(f"Expression is invalid: {e}") return self.inputLine.clear() def removeSelected(self): self.model.remove_selected() def restoreDefaults(self): self.model.restore_defaults() def onTestStringButtonClicked(self): input_text = self.testLine.text() if not input_text: self.reset_input_style() return # If at least one row matched, we know whether table is highlighted or not self._row_matched = self.model.test_string(input_text) self.table.refresh() # Test the string currently in the input text box as well input_regex = self.inputLine.text() if not input_regex: self.reset_input_style() return compiled = None try: compiled = re.compile(input_regex) except re.error: self.reset_input_style() return if self.model.is_match(input_text, compiled): self.inputLine.setStyleSheet("background-color: rgb(10, 200, 10);") self._input_styled = True else: self.reset_input_style() def reset_input_style(self): """Reset regex input line background""" if self._input_styled: self.inputLine.setStyleSheet(self.styleSheet()) self._input_styled = False def reset_table_style(self): if self._row_matched: self._row_matched = False self.model.reset_rows_highlight() self.table.refresh() def display_help_message(self): self.app.show_message( tr( """\ These (case sensitive) python regular expressions will filter out files during scans.<br>\ Directores will also have their <strong>default state</strong> set to Excluded \ in the Directories tab if their name happens to match one of the selected regular expressions.<br>\ For each file collected, two tests are performed to determine whether or not to completely ignore it:<br>\ <li>1. Regular expressions with no path separator in them will be compared to the file name only.</li> <li>2. Regular expressions with at least one path separator in them will be compared to the full path to the file.</li>\ <br>Example: if you want to filter out .PNG files from the "My Pictures" directory only:<br>\ <code>.*My\\sPictures\\\\.*\\.png</code><br><br>\ You can test the regular expression with the "test string" button after pasting a fake path in the test field:<br>\ <code>C:\\\\User\\My Pictures\\test.png</code><br><br> Matching regular expressions will be highlighted.<br>\ If there is at least one highlight, the path or filename tested will be ignored during scans.<br><br>\ Directories and files starting with a period '.' are filtered out by default.<br><br>""" ) )
7,362
Python
.py
160
38.08125
120
0.685038
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,078
preferences_dialog.py
arsenetar_dupeguru/qt/pe/preferences_dialog.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from hscommon.trans import trget from hscommon.plat import ISLINUX from core.scanner import ScanType from core.app import AppMode from qt.preferences_dialog import PreferencesDialogBase tr = trget("ui") class PreferencesDialog(PreferencesDialogBase): def _setupPreferenceWidgets(self): self._setupFilterHardnessBox() self.widgetsVLayout.addLayout(self.filterHardnessHLayout) self._setupAddCheckbox("matchScaledBox", tr("Match pictures of different dimensions")) self.widgetsVLayout.addWidget(self.matchScaledBox) self._setupAddCheckbox("matchRotatedBox", tr("Match pictures of different rotations")) self.widgetsVLayout.addWidget(self.matchRotatedBox) self._setupAddCheckbox("mixFileKindBox", tr("Can mix file kind")) self.widgetsVLayout.addWidget(self.mixFileKindBox) self._setupAddCheckbox("useRegexpBox", tr("Use regular expressions when filtering")) self.widgetsVLayout.addWidget(self.useRegexpBox) self._setupAddCheckbox("removeEmptyFoldersBox", tr("Remove empty folders on delete or move")) self.widgetsVLayout.addWidget(self.removeEmptyFoldersBox) self._setupAddCheckbox( "ignoreHardlinkMatches", tr("Ignore duplicates hardlinking to the same file"), ) self.widgetsVLayout.addWidget(self.ignoreHardlinkMatches) self._setupBottomPart() def _setupDisplayPage(self): super()._setupDisplayPage() self._setupAddCheckbox("details_dialog_override_theme_icons", tr("Override theme icons in viewer toolbar")) self.details_dialog_override_theme_icons.setToolTip( tr("Use our own internal icons instead of those provided by the theme engine") ) # Prevent changing this on platforms where themes are unpredictable self.details_dialog_override_theme_icons.setEnabled(False if not ISLINUX else True) # Insert this right after the vertical title bar option index = self.details_groupbox_layout.indexOf(self.details_dialog_vertical_titlebar) self.details_groupbox_layout.insertWidget(index + 1, self.details_dialog_override_theme_icons) self._setupAddCheckbox("details_dialog_viewers_show_scrollbars", tr("Show scrollbars in image viewers")) self.details_dialog_viewers_show_scrollbars.setToolTip( tr( "When the image displayed doesn't fit the viewport, \ show scrollbars to span the view around" ) ) self.details_groupbox_layout.insertWidget(index + 2, self.details_dialog_viewers_show_scrollbars) def _load(self, prefs, setchecked, section): setchecked(self.matchScaledBox, prefs.match_scaled) setchecked(self.matchRotatedBox, prefs.match_rotated) # Update UI state based on selected scan type scan_type = prefs.get_scan_type(AppMode.PICTURE) fuzzy_scan = scan_type == ScanType.FUZZYBLOCK self.filterHardnessSlider.setEnabled(fuzzy_scan) setchecked(self.details_dialog_override_theme_icons, prefs.details_dialog_override_theme_icons) setchecked(self.details_dialog_viewers_show_scrollbars, prefs.details_dialog_viewers_show_scrollbars) def _save(self, prefs, ischecked): prefs.match_scaled = ischecked(self.matchScaledBox) prefs.match_rotated = ischecked(self.matchRotatedBox) prefs.details_dialog_override_theme_icons = ischecked(self.details_dialog_override_theme_icons) prefs.details_dialog_viewers_show_scrollbars = ischecked(self.details_dialog_viewers_show_scrollbars)
3,875
Python
.py
64
52.8125
115
0.740789
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,079
block.pyi
arsenetar_dupeguru/qt/pe/block.pyi
from typing import Tuple, List, Union from PyQt5.QtGui import QImage _block = Tuple[int, int, int] def getblock(image: QImage) -> _block: ... # noqa: E302 def getblocks(image: QImage, block_count_per_side: int) -> Union[List[_block], None]: ...
248
Python
.py
5
48.2
89
0.709544
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,080
block.py
arsenetar_dupeguru/qt/pe/block.py
# Created By: Virgil Dupras # Created On: 2009-05-10 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from qt.pe._block_qt import getblocks # NOQA # Converted to C # def getblock(image): # width = image.width() # height = image.height() # if width: # pixel_count = width * height # red = green = blue = 0 # s = image.bits().asstring(image.numBytes()) # for i in xrange(pixel_count): # offset = i * 3 # red += ord(s[offset]) # green += ord(s[offset + 1]) # blue += ord(s[offset + 2]) # return (red // pixel_count, green // pixel_count, blue // pixel_count) # else: # return (0, 0, 0) # # def getblocks(image, block_count_per_side): # width = image.width() # height = image.height() # if not width: # return [] # block_width = max(width // block_count_per_side, 1) # block_height = max(height // block_count_per_side, 1) # result = [] # for ih in xrange(block_count_per_side): # top = min(ih * block_height, height - block_height) # for iw in range(block_count_per_side): # left = min(iw * block_width, width - block_width) # crop = image.copy(left, top, block_width, block_height) # result.append(getblock(crop)) # return result
1,562
Python
.py
40
38
89
0.603289
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,081
details_dialog.py
arsenetar_dupeguru/qt/pe/details_dialog.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import Qt, QSize, pyqtSignal, pyqtSlot from PyQt5.QtWidgets import QAbstractItemView, QSizePolicy, QGridLayout, QSplitter, QFrame from PyQt5.QtGui import QResizeEvent from hscommon.trans import trget from qt.details_dialog import DetailsDialog as DetailsDialogBase from qt.details_table import DetailsTable from qt.pe.image_viewer import ViewerToolBar, ScrollAreaImageViewer, ScrollAreaController tr = trget("ui") class DetailsDialog(DetailsDialogBase): def __init__(self, parent, app): self.vController = None super().__init__(parent, app) def _setupUi(self): self.setWindowTitle(tr("Details")) self.resize(502, 502) self.setMinimumSize(QSize(250, 250)) self.splitter = QSplitter(Qt.Vertical) self.topFrame = EmittingFrame() self.topFrame.setFrameShape(QFrame.StyledPanel) self.horizontalLayout = QGridLayout() # Minimum width for the toolbar in the middle: self.horizontalLayout.setColumnMinimumWidth(1, 10) self.horizontalLayout.setContentsMargins(0, 0, 0, 0) self.horizontalLayout.setColumnStretch(0, 32) # Smaller value for the toolbar in the middle to avoid excessive resize self.horizontalLayout.setColumnStretch(1, 2) self.horizontalLayout.setColumnStretch(2, 32) # This avoids toolbar getting incorrectly partially hidden when window resizes self.horizontalLayout.setRowStretch(0, 1) self.horizontalLayout.setRowStretch(1, 24) self.horizontalLayout.setRowStretch(2, 1) self.horizontalLayout.setSpacing(1) # probably not important self.selectedImageViewer = ScrollAreaImageViewer(self, "selectedImage") self.horizontalLayout.addWidget(self.selectedImageViewer, 0, 0, 3, 1) # Use a specific type of controller depending on the underlying viewer type self.vController = ScrollAreaController(self) self.verticalToolBar = ViewerToolBar(self, self.vController) self.verticalToolBar.setOrientation(Qt.Orientation(Qt.Vertical)) self.horizontalLayout.addWidget(self.verticalToolBar, 1, 1, 1, 1, Qt.AlignCenter) self.referenceImageViewer = ScrollAreaImageViewer(self, "referenceImage") self.horizontalLayout.addWidget(self.referenceImageViewer, 0, 2, 3, 1) self.topFrame.setLayout(self.horizontalLayout) self.splitter.addWidget(self.topFrame) self.splitter.setStretchFactor(0, 8) self.tableView = DetailsTable(self) size_policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum) size_policy.setHorizontalStretch(0) size_policy.setVerticalStretch(0) self.tableView.setSizePolicy(size_policy) self.tableView.setAlternatingRowColors(True) self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows) self.tableView.setShowGrid(False) self.splitter.addWidget(self.tableView) self.splitter.setStretchFactor(1, 1) # Late population needed here for connections to the toolbar self.vController.setupViewers(self.selectedImageViewer, self.referenceImageViewer) # self.setCentralWidget(self.splitter) # only as QMainWindow self.setWidget(self.splitter) # only as QDockWidget self.topFrame.resized.connect(self.resizeEvent) def _update(self): if self.vController is None: # Not yet constructed! return if not self.app.model.selected_dupes: # No item from the model, disable and clear everything. self.vController.resetViewersState() return dupe = self.app.model.selected_dupes[0] group = self.app.model.results.get_group_of_duplicate(dupe) ref = group.ref self.vController.updateView(ref, dupe, group) # --- Override @pyqtSlot(QResizeEvent) def resizeEvent(self, event): self.ensure_same_sizes() if self.vController is None or not self.vController.bestFit: return # Only update the scaled down pixmaps self.vController.updateBothImages() def show(self): # Give the splitter a maximum height to reach. This is assuming that # all rows below their headers have the same height self.tableView.setMaximumHeight( self.tableView.rowHeight(1) * self.tableModel.model.row_count() + self.tableView.verticalHeader().sectionSize(0) # looks like the handle is taken into account by the splitter + self.splitter.handle(1).size().height() ) DetailsDialogBase.show(self) self.ensure_same_sizes() self._update() def ensure_same_sizes(self): # HACK This ensures same size while shrinking. # ReferenceViewer might be 1 pixel shorter in width # due to the toolbar in the middle keeping the same width, # so resizing in the GridLayout's engine leads to not enough space # left for the panel on the right. # This work as a QMainWindow, but doesn't work as a QDockWidget: # resize can only grow. Might need some custom sizeHint somewhere... # self.horizontalLayout.setColumnMinimumWidth( # 0, self.selectedImageViewer.size().width()) # self.horizontalLayout.setColumnMinimumWidth( # 2, self.selectedImageViewer.size().width()) # This works when expanding but it's ugly: if self.selectedImageViewer.size().width() > self.referenceImageViewer.size().width(): self.selectedImageViewer.resize(self.referenceImageViewer.size()) # model --> view def refresh(self): DetailsDialogBase.refresh(self) if self.isVisible(): self._update() class EmittingFrame(QFrame): """Emits a signal whenever is resized""" resized = pyqtSignal(QResizeEvent) def resizeEvent(self, event): self.resized.emit(event)
6,224
Python
.py
120
43.758333
94
0.709847
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,082
image_viewer.py
arsenetar_dupeguru/qt/pe/image_viewer.py
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import QObject, Qt, QSize, QRectF, QPointF, QPoint, pyqtSlot, pyqtSignal, QEvent from PyQt5.QtGui import QPixmap, QPainter, QPalette, QCursor, QIcon, QKeySequence from PyQt5.QtWidgets import ( QGraphicsView, QGraphicsScene, QGraphicsPixmapItem, QToolBar, QToolButton, QAction, QWidget, QScrollArea, QApplication, QAbstractScrollArea, QStyle, ) from hscommon.trans import trget from hscommon.plat import ISLINUX tr = trget("ui") MAX_SCALE = 12.0 MIN_SCALE = 0.1 def create_actions(actions, target): # actions are list of (name, shortcut, icon, desc, func) for name, shortcut, icon, desc, func in actions: action = QAction(target) if icon: action.setIcon(icon) if shortcut: action.setShortcut(shortcut) action.setText(desc) action.triggered.connect(func) setattr(target, name, action) class ViewerToolBar(QToolBar): def __init__(self, parent, controller): super().__init__(parent) self.parent = parent self.controller = controller self.setupActions(controller) self.createButtons() self.buttonImgSwap.setEnabled(False) self.buttonZoomIn.setEnabled(False) self.buttonZoomOut.setEnabled(False) self.buttonNormalSize.setEnabled(False) self.buttonBestFit.setEnabled(False) def setupActions(self, controller): # actions are list of (name, shortcut, icon, desc, func) ACTIONS = [ ( "actionZoomIn", QKeySequence.ZoomIn, ( QIcon.fromTheme("zoom-in") if ISLINUX and not self.parent.app.prefs.details_dialog_override_theme_icons else QIcon(QPixmap(":/" + "zoom_in")) ), tr("Increase zoom"), controller.zoomIn, ), ( "actionZoomOut", QKeySequence.ZoomOut, ( QIcon.fromTheme("zoom-out") if ISLINUX and not self.parent.app.prefs.details_dialog_override_theme_icons else QIcon(QPixmap(":/" + "zoom_out")) ), tr("Decrease zoom"), controller.zoomOut, ), ( "actionNormalSize", tr("Ctrl+/"), ( QIcon.fromTheme("zoom-original") if ISLINUX and not self.parent.app.prefs.details_dialog_override_theme_icons else QIcon(QPixmap(":/" + "zoom_original")) ), tr("Normal size"), controller.zoomNormalSize, ), ( "actionBestFit", tr("Ctrl+*"), ( QIcon.fromTheme("zoom-best-fit") if ISLINUX and not self.parent.app.prefs.details_dialog_override_theme_icons else QIcon(QPixmap(":/" + "zoom_best_fit")) ), tr("Best fit"), controller.zoomBestFit, ), ] # TODO try with QWidgetAction() instead in order to have # the popup menu work in the toolbar (if resized below minimum height) create_actions(ACTIONS, self) def createButtons(self): self.buttonImgSwap = QToolButton(self) self.buttonImgSwap.setToolButtonStyle(Qt.ToolButtonIconOnly) self.buttonImgSwap.setIcon( QIcon.fromTheme("view-refresh", self.style().standardIcon(QStyle.SP_BrowserReload)) if ISLINUX and not self.parent.app.prefs.details_dialog_override_theme_icons else QIcon(QPixmap(":/" + "exchange")) ) self.buttonImgSwap.setText("Swap images") self.buttonImgSwap.setToolTip("Swap images") self.buttonImgSwap.pressed.connect(self.controller.swapImages) self.buttonImgSwap.released.connect(self.controller.swapImages) self.buttonZoomIn = QToolButton(self) self.buttonZoomIn.setToolButtonStyle(Qt.ToolButtonIconOnly) self.buttonZoomIn.setDefaultAction(self.actionZoomIn) self.buttonZoomIn.setEnabled(False) self.buttonZoomOut = QToolButton(self) self.buttonZoomOut.setToolButtonStyle(Qt.ToolButtonIconOnly) self.buttonZoomOut.setDefaultAction(self.actionZoomOut) self.buttonZoomOut.setEnabled(False) self.buttonNormalSize = QToolButton(self) self.buttonNormalSize.setToolButtonStyle(Qt.ToolButtonIconOnly) self.buttonNormalSize.setDefaultAction(self.actionNormalSize) self.buttonNormalSize.setEnabled(True) self.buttonBestFit = QToolButton(self) self.buttonBestFit.setToolButtonStyle(Qt.ToolButtonIconOnly) self.buttonBestFit.setDefaultAction(self.actionBestFit) self.buttonBestFit.setEnabled(False) self.addWidget(self.buttonImgSwap) self.addWidget(self.buttonZoomIn) self.addWidget(self.buttonZoomOut) self.addWidget(self.buttonNormalSize) self.addWidget(self.buttonBestFit) class BaseController(QObject): """Abstract Base class. Singleton. Base proxy interface to keep image viewers synchronized. Relays function calls, keep tracks of things.""" def __init__(self, parent): super().__init__() self.selectedViewer = None self.referenceViewer = None # cached pixmaps self.selectedPixmap = QPixmap() self.referencePixmap = QPixmap() self.scaledSelectedPixmap = QPixmap() self.scaledReferencePixmap = QPixmap() self.current_scale = 1.0 self.bestFit = True self.parent = parent # To change buttons' states self.cached_group = None self.same_dimensions = True def setupViewers(self, selected_viewer, reference_viewer): self.selectedViewer = selected_viewer self.referenceViewer = reference_viewer self.selectedViewer.controller = self self.referenceViewer.controller = self self._setupConnections() def _setupConnections(self): self.selectedViewer.connectMouseSignals() self.referenceViewer.connectMouseSignals() def updateView(self, ref, dupe, group): # To keep current scale accross dupes from the same group previous_same_dimensions = self.same_dimensions self.same_dimensions = True same_group = True if group != self.cached_group: same_group = False self.resetState() self.cached_group = group self.selectedPixmap = QPixmap(str(dupe.path)) if ref is dupe: # currently selected file is the actual reference file self.referencePixmap = QPixmap() self.scaledReferencePixmap = QPixmap() self.parent.verticalToolBar.buttonImgSwap.setEnabled(False) self.parent.verticalToolBar.buttonNormalSize.setEnabled(True) else: self.referencePixmap = QPixmap(str(ref.path)) self.parent.verticalToolBar.buttonImgSwap.setEnabled(True) if ref.dimensions != dupe.dimensions: self.same_dimensions = False self.parent.verticalToolBar.buttonNormalSize.setEnabled(True) self.updateButtonsAsPerDimensions(previous_same_dimensions) self.updateBothImages(same_group) self.centerViews(same_group and self.referencePixmap.isNull()) def updateBothImages(self, same_group=False): # WARNING this is called on every resize event, ignore_update = self.referencePixmap.isNull() if ignore_update: self.selectedViewer.ignore_signal = True # the SelectedImageViewer widget sometimes ends up being bigger # than the ReferenceImageViewer by one pixel, which distorts the # scaled down pixmap for the reference, hence we'll reuse its size here. self._updateImage(self.selectedPixmap, self.selectedViewer, same_group) self._updateImage(self.referencePixmap, self.referenceViewer, same_group) if ignore_update: self.selectedViewer.ignore_signal = False def _updateImage(self, pixmap, viewer, same_group=False): # WARNING this is called on every resize event, might need to split # into a separate function depending on the implementation used if pixmap.isNull(): # This should disable the blank widget viewer.setImage(pixmap) return target_size = viewer.size() if not viewer.bestFit: if same_group: viewer.setImage(pixmap) return target_size # zoomed in state, expand # only if not same_group, we need full update scaledpixmap = pixmap.scaled(target_size, Qt.KeepAspectRatioByExpanding, Qt.FastTransformation) else: # best fit, keep ratio always scaledpixmap = pixmap.scaled(target_size, Qt.KeepAspectRatio, Qt.FastTransformation) viewer.setImage(scaledpixmap) return target_size def resetState(self): """Only called when the group of dupes has changed. We reset our controller internal state and buttons, center view on viewers.""" self.selectedPixmap = QPixmap() self.scaledSelectedPixmap = QPixmap() self.referencePixmap = QPixmap() self.scaledReferencePixmap = QPixmap() self.setBestFit(True) self.current_scale = 1.0 self.selectedViewer.current_scale = 1.0 self.referenceViewer.current_scale = 1.0 self.selectedViewer.resetCenter() self.referenceViewer.resetCenter() self.selectedViewer.scaleAt(1.0) self.referenceViewer.scaleAt(1.0) self.centerViews() self.parent.verticalToolBar.buttonZoomIn.setEnabled(False) self.parent.verticalToolBar.buttonZoomOut.setEnabled(False) self.parent.verticalToolBar.buttonNormalSize.setEnabled(True) self.parent.verticalToolBar.buttonBestFit.setEnabled(False) # active mode by default def resetViewersState(self): """No item from the model, disable and clear everything.""" # only called by the details dialog self.selectedPixmap = QPixmap() self.scaledSelectedPixmap = QPixmap() self.referencePixmap = QPixmap() self.scaledReferencePixmap = QPixmap() self.setBestFit(True) self.current_scale = 1.0 self.selectedViewer.current_scale = 1.0 self.referenceViewer.current_scale = 1.0 self.selectedViewer.resetCenter() self.referenceViewer.resetCenter() self.selectedViewer.scaleAt(1.0) self.referenceViewer.scaleAt(1.0) self.centerViews() self.parent.verticalToolBar.buttonImgSwap.setEnabled(False) self.parent.verticalToolBar.buttonZoomIn.setEnabled(False) self.parent.verticalToolBar.buttonZoomOut.setEnabled(False) self.parent.verticalToolBar.buttonNormalSize.setEnabled(False) self.parent.verticalToolBar.buttonBestFit.setEnabled(False) # active mode by default self.selectedViewer.setImage(self.selectedPixmap) # null self.selectedViewer.setEnabled(False) self.referenceViewer.setImage(self.referencePixmap) # null self.referenceViewer.setEnabled(False) @pyqtSlot() def zoomIn(self): self.scaleImagesBy(1.25) @pyqtSlot() def zoomOut(self): self.scaleImagesBy(0.8) @pyqtSlot(float) def scaleImagesBy(self, factor): """Compute new scale from factor and scale.""" self.current_scale *= factor self.selectedViewer.scaleBy(factor) self.referenceViewer.scaleBy(factor) self.updateButtons() @pyqtSlot(float) def scaleImagesAt(self, scale): """Scale at a pre-computed scale.""" self.current_scale = scale self.selectedViewer.scaleAt(scale) self.referenceViewer.scaleAt(scale) self.updateButtons() def updateButtons(self): self.parent.verticalToolBar.buttonZoomIn.setEnabled(self.current_scale < MAX_SCALE) self.parent.verticalToolBar.buttonZoomOut.setEnabled(self.current_scale > MIN_SCALE) self.parent.verticalToolBar.buttonNormalSize.setEnabled(round(self.current_scale, 1) != 1.0) self.parent.verticalToolBar.buttonBestFit.setEnabled(self.bestFit is False) def updateButtonsAsPerDimensions(self, previous_same_dimensions): if not self.same_dimensions: self.parent.verticalToolBar.buttonZoomIn.setEnabled(False) self.parent.verticalToolBar.buttonZoomOut.setEnabled(False) if not self.bestFit: self.zoomBestFit() self.parent.verticalToolBar.buttonNormalSize.setEnabled(True) if not self.referencePixmap.isNull(): self.parent.verticalToolBar.buttonImgSwap.setEnabled(True) return if not self.bestFit and not previous_same_dimensions: self.zoomBestFit() self.parent.verticalToolBar.buttonNormalSize.setEnabled(True) if self.referencePixmap.isNull(): self.parent.verticalToolBar.buttonImgSwap.setEnabled(False) @pyqtSlot() def zoomBestFit(self): """Setup before scaling to bestfit""" self.setBestFit(True) self.current_scale = 1.0 self.selectedViewer.current_scale = 1.0 self.referenceViewer.current_scale = 1.0 self.selectedViewer.scaleAt(1.0) self.referenceViewer.scaleAt(1.0) self.selectedViewer.resetCenter() self.referenceViewer.resetCenter() self._updateImage(self.selectedPixmap, self.selectedViewer, True) self._updateImage(self.referencePixmap, self.referenceViewer, True) self.centerViews() self.parent.verticalToolBar.buttonZoomIn.setEnabled(False) self.parent.verticalToolBar.buttonZoomOut.setEnabled(False) self.parent.verticalToolBar.buttonNormalSize.setEnabled(True) self.parent.verticalToolBar.buttonBestFit.setEnabled(False) self.parent.verticalToolBar.buttonImgSwap.setEnabled(True) def setBestFit(self, value): self.bestFit = value self.selectedViewer.bestFit = value self.referenceViewer.bestFit = value @pyqtSlot() def zoomNormalSize(self): self.setBestFit(False) self.current_scale = 1.0 self.selectedViewer.setImage(self.selectedPixmap) self.referenceViewer.setImage(self.referencePixmap) self.centerViews() self.selectedViewer.scaleToNormalSize() self.referenceViewer.scaleToNormalSize() if self.same_dimensions: self.parent.verticalToolBar.buttonZoomIn.setEnabled(True) self.parent.verticalToolBar.buttonZoomOut.setEnabled(True) else: # we can't allow swapping pixmaps of different dimensions self.parent.verticalToolBar.buttonImgSwap.setEnabled(False) self.parent.verticalToolBar.buttonNormalSize.setEnabled(False) self.parent.verticalToolBar.buttonBestFit.setEnabled(True) def centerViews(self, only_selected=False): self.selectedViewer.centerViewAndUpdate() if only_selected: return self.referenceViewer.centerViewAndUpdate() @pyqtSlot() def swapImages(self): # swap the columns in the details table as well self.parent.tableView.horizontalHeader().swapSections(0, 1) class QWidgetController(BaseController): """Specialized version for QWidget-based viewers.""" def __init__(self, parent): super().__init__(parent) def _updateImage(self, *args): ret = super()._updateImage(*args) # Fix alignment when resizing window self.centerViews() return ret @pyqtSlot(QPointF) def onDraggedMouse(self, delta): if not self.same_dimensions: return if self.sender() is self.referenceViewer: self.selectedViewer.onDraggedMouse(delta) else: self.referenceViewer.onDraggedMouse(delta) @pyqtSlot() def swapImages(self): self.selectedViewer._pixmap.swap(self.referenceViewer._pixmap) self.selectedViewer.centerViewAndUpdate() self.referenceViewer.centerViewAndUpdate() super().swapImages() class ScrollAreaController(BaseController): """Specialized version fro QLabel-based viewers.""" def __init__(self, parent): super().__init__(parent) def _setupConnections(self): super()._setupConnections() self.selectedViewer.connectScrollBars() self.referenceViewer.connectScrollBars() def updateBothImages(self, same_group=False): super().updateBothImages(same_group) if not self.referenceViewer.isEnabled(): return self.referenceViewer._horizontalScrollBar.setValue(self.selectedViewer._horizontalScrollBar.value()) self.referenceViewer._verticalScrollBar.setValue(self.selectedViewer._verticalScrollBar.value()) @pyqtSlot(QPoint) def onDraggedMouse(self, delta): self.selectedViewer.ignore_signal = True self.referenceViewer.ignore_signal = True if self.same_dimensions: self.selectedViewer.onDraggedMouse(delta) self.referenceViewer.onDraggedMouse(delta) else: if self.sender() is self.selectedViewer: self.selectedViewer.onDraggedMouse(delta) else: self.referenceViewer.onDraggedMouse(delta) self.selectedViewer.ignore_signal = False self.referenceViewer.ignore_signal = False @pyqtSlot() def swapImages(self): self.referenceViewer._pixmap.swap(self.selectedViewer._pixmap) self.referenceViewer.setCachedPixmap() self.selectedViewer.setCachedPixmap() super().swapImages() @pyqtSlot(float, QPointF) def onMouseWheel(self, scale, delta): self.scaleImagesAt(scale) self.selectedViewer.adjustScrollBarsScaled(delta) # Signal from scrollbars will automatically change the other: # self.referenceViewer.adjustScrollBarsScaled(delta) @pyqtSlot(int) def onVScrollBarChanged(self, value): if not self.same_dimensions: return if self.sender() is self.referenceViewer._verticalScrollBar: if not self.selectedViewer.ignore_signal: self.selectedViewer._verticalScrollBar.setValue(value) else: if not self.referenceViewer.ignore_signal: self.referenceViewer._verticalScrollBar.setValue(value) @pyqtSlot(int) def onHScrollBarChanged(self, value): if not self.same_dimensions: return if self.sender() is self.referenceViewer._horizontalScrollBar: if not self.selectedViewer.ignore_signal: self.selectedViewer._horizontalScrollBar.setValue(value) else: if not self.referenceViewer.ignore_signal: self.referenceViewer._horizontalScrollBar.setValue(value) @pyqtSlot(float) def scaleImagesBy(self, factor): super().scaleImagesBy(factor) # The other is automatically updated via sigals self.selectedViewer.adjustScrollBarsFactor(factor) @pyqtSlot() def zoomBestFit(self): # Disable scrollbars to avoid GridLayout size rounding glitch super().zoomBestFit() if self.referencePixmap.isNull(): self.parent.verticalToolBar.buttonImgSwap.setEnabled(False) self.selectedViewer.toggleScrollBars() self.referenceViewer.toggleScrollBars() class GraphicsViewController(BaseController): """Specialized version fro QGraphicsView-based viewers.""" def __init__(self, parent): super().__init__(parent) def _setupConnections(self): super()._setupConnections() self.selectedViewer.connectScrollBars() self.referenceViewer.connectScrollBars() # Special case for mouse wheel event conflicting with scrollbar adjustments self.selectedViewer.other_viewer = self.referenceViewer self.referenceViewer.other_viewer = self.selectedViewer @pyqtSlot() def syncCenters(self): if self.sender() is self.referenceViewer: self.selectedViewer.setCenter(self.referenceViewer._centerPoint) else: self.referenceViewer.setCenter(self.selectedViewer._centerPoint) @pyqtSlot(float, QPointF) def onMouseWheel(self, factor, new_center): self.current_scale *= factor if self.sender() is self.referenceViewer: self.selectedViewer.scaleBy(factor) self.selectedViewer.setCenter(new_center) else: self.referenceViewer.scaleBy(factor) self.referenceViewer.setCenter(new_center) @pyqtSlot(int) def onVScrollBarChanged(self, value): if not self.same_dimensions: return if self.sender() is self.referenceViewer._verticalScrollBar: if not self.selectedViewer.ignore_signal: self.selectedViewer._verticalScrollBar.setValue(value) else: if not self.referenceViewer.ignore_signal: self.referenceViewer._verticalScrollBar.setValue(value) @pyqtSlot(int) def onHScrollBarChanged(self, value): if not self.same_dimensions: return if self.sender() is self.referenceViewer._horizontalScrollBar: if not self.selectedViewer.ignore_signal: self.selectedViewer._horizontalScrollBar.setValue(value) else: if not self.referenceViewer.ignore_signal: self.referenceViewer._horizontalScrollBar.setValue(value) @pyqtSlot() def swapImages(self): self.referenceViewer._pixmap.swap(self.selectedViewer._pixmap) self.referenceViewer.setCachedPixmap() self.selectedViewer.setCachedPixmap() super().swapImages() @pyqtSlot() def zoomBestFit(self): """Setup before scaling to bestfit""" self.setBestFit(True) self.current_scale = 1.0 self.selectedViewer.fitScale() self.referenceViewer.fitScale() self.parent.verticalToolBar.buttonBestFit.setEnabled(False) self.parent.verticalToolBar.buttonZoomOut.setEnabled(False) self.parent.verticalToolBar.buttonZoomIn.setEnabled(False) self.parent.verticalToolBar.buttonNormalSize.setEnabled(True) if not self.referencePixmap.isNull(): self.parent.verticalToolBar.buttonImgSwap.setEnabled(True) # else: # self.referenceViewer.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # self.referenceViewer.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) def updateView(self, ref, dupe, group): # Keep current scale accross dupes from the same group previous_same_dimensions = self.same_dimensions self.same_dimensions = True same_group = True if group != self.cached_group: same_group = False self.resetState() self.cached_group = group self.selectedPixmap = QPixmap(str(dupe.path)) if ref is dupe: # currently selected file is the actual reference file self.same_dimensions = False self.referencePixmap = QPixmap() self.parent.verticalToolBar.buttonImgSwap.setEnabled(False) self.parent.verticalToolBar.buttonNormalSize.setEnabled(True) else: self.referencePixmap = QPixmap(str(ref.path)) self.parent.verticalToolBar.buttonImgSwap.setEnabled(True) if ref.dimensions != dupe.dimensions: self.same_dimensions = False self.parent.verticalToolBar.buttonNormalSize.setEnabled(True) self.updateButtonsAsPerDimensions(previous_same_dimensions) self.updateBothImages(same_group) def updateBothImages(self, same_group=False): """This is called only during resize events and while bestFit.""" ignore_update = self.referencePixmap.isNull() if ignore_update: self.selectedViewer.ignore_signal = True self._updateFitImage(self.selectedPixmap, self.selectedViewer) self._updateFitImage(self.referencePixmap, self.referenceViewer) if ignore_update: self.selectedViewer.ignore_signal = False def _updateFitImage(self, pixmap, viewer): # If not same_group, we need full update""" viewer.setImage(pixmap) if pixmap.isNull(): return if viewer.bestFit: viewer.fitScale() def resetState(self): """Only called when the group of dupes has changed. We reset our controller internal state and buttons, center view on viewers.""" self.selectedPixmap = QPixmap() self.referencePixmap = QPixmap() self.setBestFit(True) self.current_scale = 1.0 self.selectedViewer.current_scale = 1.0 self.referenceViewer.current_scale = 1.0 self.selectedViewer.resetCenter() self.referenceViewer.resetCenter() self.selectedViewer.fitScale() self.referenceViewer.fitScale() # self.centerViews() self.parent.verticalToolBar.buttonZoomIn.setEnabled(False) self.parent.verticalToolBar.buttonZoomOut.setEnabled(False) self.parent.verticalToolBar.buttonBestFit.setEnabled(False) self.parent.verticalToolBar.buttonNormalSize.setEnabled(True) def resetViewersState(self): """No item from the model, disable and clear everything.""" # only called by the details dialog self.selectedPixmap = QPixmap() self.scaledSelectedPixmap = QPixmap() self.referencePixmap = QPixmap() self.scaledReferencePixmap = QPixmap() self.setBestFit(True) self.current_scale = 1.0 self.selectedViewer.current_scale = 1.0 self.referenceViewer.current_scale = 1.0 self.selectedViewer.resetCenter() self.referenceViewer.resetCenter() # self.centerViews() self.parent.verticalToolBar.buttonZoomIn.setEnabled(False) self.parent.verticalToolBar.buttonZoomOut.setEnabled(False) self.parent.verticalToolBar.buttonBestFit.setEnabled(False) self.parent.verticalToolBar.buttonImgSwap.setEnabled(False) self.parent.verticalToolBar.buttonNormalSize.setEnabled(False) self.selectedViewer.setImage(self.selectedPixmap) # null self.selectedViewer.setEnabled(False) self.referenceViewer.setImage(self.referencePixmap) # null self.referenceViewer.setEnabled(False) @pyqtSlot(float) def scaleImagesBy(self, factor): self.selectedViewer.updateCenterPoint() self.referenceViewer.updateCenterPoint() super().scaleImagesBy(factor) self.selectedViewer.centerOn(self.selectedViewer._centerPoint) # Scrollbars sync themselves here class QWidgetImageViewer(QWidget): """Use a QPixmap, but no scrollbars and no keyboard key sequence for navigation.""" # FIXME: panning while zoomed-in is broken (due to delta not interpolated right? mouseDragged = pyqtSignal(QPointF) mouseWheeled = pyqtSignal(float) def __init__(self, parent, name=""): super().__init__(parent) self._app = QApplication self._pixmap = QPixmap() self._rect = QRectF() self._lastMouseClickPoint = QPointF() self._mousePanningDelta = QPointF() self.current_scale = 1.0 self._drag = False self._dragConnection = None self._wheelConnection = None self._instance_name = name self.bestFit = True self.controller = None self.setMouseTracking(False) def __repr__(self): return f"{self._instance_name}" def connectMouseSignals(self): if not self._dragConnection: self._dragConnection = self.mouseDragged.connect(self.controller.onDraggedMouse) if not self._wheelConnection: self._wheelConnection = self.mouseWheeled.connect(self.controller.scaleImagesBy) def disconnectMouseSignals(self): if self._dragConnection: self.mouseDragged.disconnect() self._dragConnection = None if self._wheelConnection: self.mouseWheeled.disconnect() self._wheelConnection = None def paintEvent(self, event): painter = QPainter(self) painter.translate(self.rect().center()) painter.scale(self.current_scale, self.current_scale) painter.translate(self._mousePanningDelta) painter.drawPixmap(self._rect.topLeft(), self._pixmap) def resetCenter(self): """Resets origin""" # Make sure we are not still panning around self._mousePanningDelta = QPointF() self.update() def changeEvent(self, event): if event.type() == QEvent.EnabledChange: if self.isEnabled(): self.connectMouseSignals() return self.disconnectMouseSignals() def contextMenuEvent(self, event): """Block parent's (main window) context menu on right click.""" event.accept() def mousePressEvent(self, event): if self.bestFit or not self.isEnabled(): event.ignore() return if event.button() & (Qt.LeftButton | Qt.MidButton | Qt.RightButton): self._drag = True else: self._drag = False event.ignore() return self._lastMouseClickPoint = event.pos() self._app.setOverrideCursor(Qt.ClosedHandCursor) self.setMouseTracking(True) event.accept() def mouseMoveEvent(self, event): if self.bestFit or not self.isEnabled(): event.ignore() return self._mousePanningDelta += (event.pos() - self._lastMouseClickPoint) * 1.0 / self.current_scale self._lastMouseClickPoint = event.pos() if self._drag: self.mouseDragged.emit(self._mousePanningDelta) self.update() def mouseReleaseEvent(self, event): if self.bestFit or not self.isEnabled(): event.ignore() return # if event.button() == Qt.LeftButton: self._drag = False self._app.restoreOverrideCursor() self.setMouseTracking(False) def wheelEvent(self, event): if self.bestFit or not self.controller.same_dimensions or not self.isEnabled(): event.ignore() return if event.angleDelta().y() > 0: if self.current_scale > MAX_SCALE: return self.mouseWheeled.emit(1.25) # zoom-in else: if self.current_scale < MIN_SCALE: return self.mouseWheeled.emit(0.8) # zoom-out def setImage(self, pixmap): if pixmap.isNull(): if not self._pixmap.isNull(): self._pixmap = pixmap self.disconnectMouseSignals() self.setEnabled(False) self.update() return elif not self.isEnabled(): self.setEnabled(True) self.connectMouseSignals() self._pixmap = pixmap def centerViewAndUpdate(self): self._rect = self._pixmap.rect() self._rect.translate(-self._rect.center()) self.update() def shouldBeActive(self): return True if not self.pixmap.isNull() else False def scaleBy(self, factor): self.current_scale *= factor self.update() def scaleAt(self, scale): self.current_scale = scale self.update() def sizeHint(self): return QSize(400, 400) @pyqtSlot() def scaleToNormalSize(self): """Called when the pixmap is set back to original size.""" self.current_scale = 1.0 self.update() @pyqtSlot(QPointF) def onDraggedMouse(self, delta): self._mousePanningDelta = delta self.update() class ScalablePixmap(QWidget): """Container for a pixmap that scales up very fast, used in ScrollAreaImageViewer.""" def __init__(self, parent): super().__init__(parent) self._pixmap = QPixmap() self.current_scale = 1.0 def paintEvent(self, event): painter = QPainter(self) painter.scale(self.current_scale, self.current_scale) # painter.drawPixmap(self.rect().topLeft(), self._pixmap) # should be the same as: painter.drawPixmap(0, 0, self._pixmap) def sizeHint(self): return self._pixmap.size() * self.current_scale def minimumSizeHint(self): return self.sizeHint() class ScrollAreaImageViewer(QScrollArea): """Implementation using a pixmap container in a simple scroll area.""" mouseDragged = pyqtSignal(QPoint) mouseWheeled = pyqtSignal(float, QPointF) def __init__(self, parent, name=""): super().__init__(parent) self._parent = parent self._app = QApplication self._pixmap = QPixmap() self._scaledpixmap = None self._rect = QRectF() self._lastMouseClickPoint = QPointF() self._mousePanningDelta = QPoint() self.current_scale = 1.0 self._drag = False self._dragConnection = None self._wheelConnection = None self._instance_name = name self.prefs = parent.app.prefs self.bestFit = True self.controller = None self.label = ScalablePixmap(self) # This is to avoid sending signals twice on scrollbar updates self.ignore_signal = False self.setBackgroundRole(QPalette.Dark) self.setWidgetResizable(False) self.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents) self.setAlignment(Qt.AlignCenter) self._verticalScrollBar = self.verticalScrollBar() self._horizontalScrollBar = self.horizontalScrollBar() if self.prefs.details_dialog_viewers_show_scrollbars: self.toggleScrollBars() else: self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setWidget(self.label) self.setVisible(True) def __repr__(self): return f"{self._instance_name}" def toggleScrollBars(self, force_on=False): if not self.prefs.details_dialog_viewers_show_scrollbars: return # Ensure that it's off on the first run if self.horizontalScrollBarPolicy() == Qt.ScrollBarAsNeeded: if force_on: return self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) else: self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) def connectMouseSignals(self): if not self._dragConnection: self._dragConnection = self.mouseDragged.connect(self.controller.onDraggedMouse) if not self._wheelConnection: self._wheelConnection = self.mouseWheeled.connect(self.controller.onMouseWheel) def disconnectMouseSignals(self): if self._dragConnection: self.mouseDragged.disconnect() self._dragConnection = None if self._wheelConnection: self.mouseWheeled.disconnect() self._wheelConnection = None def connectScrollBars(self): """Only call once controller is connected.""" # Cyclic connections are handled by Qt self._verticalScrollBar.valueChanged.connect(self.controller.onVScrollBarChanged, Qt.UniqueConnection) self._horizontalScrollBar.valueChanged.connect(self.controller.onHScrollBarChanged, Qt.UniqueConnection) def contextMenuEvent(self, event): """Block parent's (main window) context menu on right click.""" # Even though we don't have a context menu right now, and the default # contextMenuPolicy is DefaultContextMenu, we leverage that handler to # avoid raising the Result window's Actions menu event.accept() def mousePressEvent(self, event): if self.bestFit: event.ignore() return if event.button() & (Qt.LeftButton | Qt.MidButton | Qt.RightButton): self._drag = True else: self._drag = False event.ignore() return self._lastMouseClickPoint = event.pos() self._app.setOverrideCursor(Qt.ClosedHandCursor) self.setMouseTracking(True) super().mousePressEvent(event) def mouseMoveEvent(self, event): if self.bestFit: event.ignore() return if self._drag: delta = event.pos() - self._lastMouseClickPoint self._lastMouseClickPoint = event.pos() self.mouseDragged.emit(delta) super().mouseMoveEvent(event) def mouseReleaseEvent(self, event): if self.bestFit: event.ignore() return self._drag = False self._app.restoreOverrideCursor() self.setMouseTracking(False) super().mouseReleaseEvent(event) def wheelEvent(self, event): if self.bestFit or not self.controller.same_dimensions: event.ignore() return old_scale = self.current_scale if event.angleDelta().y() > 0: # zoom-in if old_scale < MAX_SCALE: self.current_scale *= 1.25 else: if old_scale > MIN_SCALE: # zoom-out self.current_scale *= 0.8 if old_scale == self.current_scale: return delta_to_pos = (event.position() / old_scale) - (self.label.pos() / old_scale) delta = (delta_to_pos * self.current_scale) - (delta_to_pos * old_scale) self.mouseWheeled.emit(self.current_scale, delta) def setImage(self, pixmap): self._pixmap = pixmap self.label._pixmap = pixmap self.label.update() self.label.adjustSize() if pixmap.isNull(): self.setEnabled(False) self.disconnectMouseSignals() elif not self.isEnabled(): self.setEnabled(True) self.connectMouseSignals() def centerViewAndUpdate(self): self._rect = self.label.rect() self.label.rect().translate(-self._rect.center()) self.label.current_scale = self.current_scale self.label.update() # self.viewport().update() def setCachedPixmap(self): """In case we have changed the cached pixmap, reset it.""" self.label._pixmap = self._pixmap self.label.update() def shouldBeActive(self): return True if not self.pixmap.isNull() else False def scaleBy(self, factor): self.current_scale *= factor # factor has to be either 1.25 or 0.8 here self.label.resize(self.label.size().__imul__(factor)) self.label.current_scale = self.current_scale self.label.update() def scaleAt(self, scale): self.current_scale = scale self.label.resize(self._pixmap.size().__imul__(scale)) self.label.current_scale = scale self.label.update() # self.label.adjustSize() def adjustScrollBarsFactor(self, factor): """After scaling, no mouse position, default to center.""" # scrollBar.setMaximum(scrollBar.maximum() - scrollBar.minimum() + scrollBar.pageStep()) self._horizontalScrollBar.setValue( int(factor * self._horizontalScrollBar.value() + ((factor - 1) * self._horizontalScrollBar.pageStep() / 2)) ) self._verticalScrollBar.setValue( int(factor * self._verticalScrollBar.value() + ((factor - 1) * self._verticalScrollBar.pageStep() / 2)) ) def adjustScrollBarsScaled(self, delta): """After scaling with the mouse, update relative to mouse position.""" self._horizontalScrollBar.setValue(int(self._horizontalScrollBar.value() + delta.x())) self._verticalScrollBar.setValue(int(self._verticalScrollBar.value() + delta.y())) def adjustScrollBarsAuto(self): """After panning, update accordingly.""" self.horizontalScrollBar().setValue(int(self.horizontalScrollBar().value() - self._mousePanningDelta.x())) self.verticalScrollBar().setValue(int(self.verticalScrollBar().value() - self._mousePanningDelta.y())) def adjustScrollBarCentered(self): """Just center in the middle.""" self._horizontalScrollBar.setValue(int(self._horizontalScrollBar.maximum() / 2)) self._verticalScrollBar.setValue(int(self._verticalScrollBar.maximum() / 2)) def resetCenter(self): """Resets origin""" self._mousePanningDelta = QPoint() self.current_scale = 1.0 # self.scaleAt(1.0) def setCenter(self, point): self._lastMouseClickPoint = point def sizeHint(self): return self.viewport().rect().size() @pyqtSlot() def scaleToNormalSize(self): """Called when the pixmap is set back to original size.""" self.scaleAt(1.0) self.ensureWidgetVisible(self.label) # needed for centering self.toggleScrollBars(True) @pyqtSlot(QPoint) def onDraggedMouse(self, delta): """Update position from mouse delta sent by the other panel.""" self._mousePanningDelta = delta # Signal from scrollbars had already synced the values here self.adjustScrollBarsAuto() class GraphicsViewViewer(QGraphicsView): """Re-Implementation a full-fledged GraphicsView but is a bit buggy.""" mouseDragged = pyqtSignal() mouseWheeled = pyqtSignal(float, QPointF) def __init__(self, parent, name=""): super().__init__(parent) self._parent = parent self._app = QApplication self._pixmap = QPixmap() self._scaledpixmap = None self._rect = QRectF() self._lastMouseClickPoint = QPointF() self._mousePanningDelta = QPointF() self._scaleFactor = 1.3 self.zoomInFactor = self._scaleFactor self.zoomOutFactor = 1.0 / self._scaleFactor self.current_scale = 1.0 self._drag = False self._dragConnection = None self._wheelConnection = None self._instance_name = name self.prefs = parent.app.prefs self.bestFit = True self.controller = None self._centerPoint = QPointF() self.centerOn(self._centerPoint) self.other_viewer = None # specific to this class self._scene = QGraphicsScene() self._scene.setBackgroundBrush(Qt.black) self._item = QGraphicsPixmapItem() self.setScene(self._scene) self._scene.addItem(self._item) self.setDragMode(QGraphicsView.DragMode.ScrollHandDrag) self._horizontalScrollBar = self.horizontalScrollBar() self._verticalScrollBar = self.verticalScrollBar() self.ignore_signal = False if self.prefs.details_dialog_viewers_show_scrollbars: self.toggleScrollBars() else: self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setResizeAnchor(QGraphicsView.AnchorViewCenter) self.setAlignment(Qt.AlignCenter) self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate) self.setMouseTracking(True) def connectMouseSignals(self): if not self._dragConnection: self._dragConnection = self.mouseDragged.connect(self.controller.syncCenters) if not self._wheelConnection: self._wheelConnection = self.mouseWheeled.connect(self.controller.onMouseWheel) def disconnectMouseSignals(self): if self._dragConnection: self.mouseDragged.disconnect() self._dragConnection = None if self._wheelConnection: self.mouseWheeled.disconnect() self._wheelConnection = None def connectScrollBars(self): """Only call once controller is connected.""" # Cyclic connections are handled by Qt self._verticalScrollBar.valueChanged.connect(self.controller.onVScrollBarChanged, Qt.UniqueConnection) self._horizontalScrollBar.valueChanged.connect(self.controller.onHScrollBarChanged, Qt.UniqueConnection) def toggleScrollBars(self, force_on=False): if not self.prefs.details_dialog_viewers_show_scrollbars: return # Ensure that it's off on the first run if self.horizontalScrollBarPolicy() == Qt.ScrollBarAsNeeded: if force_on: return self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) else: self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) def contextMenuEvent(self, event): """Block parent's (main window) context menu on right click.""" event.accept() def mousePressEvent(self, event): if self.bestFit: event.ignore() return if event.button() & (Qt.LeftButton | Qt.MidButton | Qt.RightButton): self._drag = True else: self._drag = False event.ignore() return self._lastMouseClickPoint = event.pos() self._app.setOverrideCursor(Qt.ClosedHandCursor) self.setMouseTracking(True) # We need to propagate to scrollbars, so we send back up super().mousePressEvent(event) def mouseReleaseEvent(self, event): if self.bestFit: event.ignore() return self._drag = False self._app.restoreOverrideCursor() self.setMouseTracking(False) self.updateCenterPoint() super().mouseReleaseEvent(event) def mouseMoveEvent(self, event): if self.bestFit: event.ignore() return if self._drag: self._lastMouseClickPoint = event.pos() # We can simply rely on the scrollbar updating each other here # self.mouseDragged.emit() self.updateCenterPoint() super().mouseMoveEvent(event) def updateCenterPoint(self): self._centerPoint = self.mapToScene(self.rect().center()) def wheelEvent(self, event): if self.bestFit or MIN_SCALE > self.current_scale > MAX_SCALE or not self.controller.same_dimensions: event.ignore() return point_before_scale = QPointF(self.mapToScene(self.mapFromGlobal(QCursor.pos()))) # Get the original screen centerpoint screen_center = QPointF(self.mapToScene(self.rect().center())) if event.angleDelta().y() > 0: factor = self.zoomInFactor else: factor = self.zoomOutFactor # Avoid scrollbars conflict: self.other_viewer.ignore_signal = True self.scaleBy(factor) point_after_scale = QPointF(self.mapToScene(self.mapFromGlobal(QCursor.pos()))) # Get the offset of how the screen moved offset = point_before_scale - point_after_scale # Adjust to the new center for correct zooming new_center = screen_center + offset self.setCenter(new_center) self.mouseWheeled.emit(factor, new_center) self.other_viewer.ignore_signal = False def setImage(self, pixmap): if pixmap.isNull(): self.ignore_signal = True elif self.ignore_signal: self.ignore_signal = False self._pixmap = pixmap self._item.setPixmap(pixmap) self.translate(1, 1) def centerViewAndUpdate(self): # Called from the base controller for Normal Size pass def setCenter(self, point): self._centerPoint = point self.centerOn(self._centerPoint) def resetCenter(self): """Resets origin""" self._mousePanningDelta = QPointF() self.current_scale = 1.0 def setNewCenter(self, position): self._centerPoint = position self.centerOn(self._centerPoint) def setCachedPixmap(self): """In case we have changed the cached pixmap, reset it.""" self._item.setPixmap(self._pixmap) self._item.update() def scaleAt(self, scale): if scale == 1.0: self.resetScale() # self.setTransform( QTransform() ) self.scale(scale, scale) def getScale(self): return self.transform().m22() def scaleBy(self, factor): self.current_scale *= factor super().scale(factor, factor) def resetScale(self): # self.setTransform( QTransform() ) self.resetTransform() # probably same as above self.setCenter(self.scene().sceneRect().center()) def fitScale(self): self.bestFit = True super().fitInView(self._scene.sceneRect(), Qt.KeepAspectRatio) self.setNewCenter(self._scene.sceneRect().center()) @pyqtSlot() def scaleToNormalSize(self): """Called when the pixmap is set back to original size.""" self.bestFit = False self.scaleAt(1.0) self.toggleScrollBars(True) self.update() def adjustScrollBarsScaled(self, delta): """After scaling with the mouse, update relative to mouse position.""" self._horizontalScrollBar.setValue(self._horizontalScrollBar.value() + delta.x()) self._verticalScrollBar.setValue(self._verticalScrollBar.value() + delta.y()) def sizeHint(self): return self.viewport().rect().size() def adjustScrollBarsFactor(self, factor): """After scaling, no mouse position, default to center.""" self._horizontalScrollBar.setValue( int(factor * self._horizontalScrollBar.value() + ((factor - 1) * self._horizontalScrollBar.pageStep() / 2)) ) self._verticalScrollBar.setValue( int(factor * self._verticalScrollBar.value() + ((factor - 1) * self._verticalScrollBar.pageStep() / 2)) ) def adjustScrollBarsAuto(self): """After panning, update accordingly.""" self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - self._mousePanningDelta.x()) self.verticalScrollBar().setValue(self.verticalScrollBar().value() - self._mousePanningDelta.y())
51,061
Python
.py
1,148
34.930314
119
0.662765
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,083
photo.py
arsenetar_dupeguru/qt/pe/photo.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import logging from PyQt5.QtGui import QImage, QImageReader, QTransform from core.pe.photo import Photo as PhotoBase from qt.pe.block import getblocks class File(PhotoBase): def _plat_get_dimensions(self): try: ir = QImageReader(str(self.path)) size = ir.size() if size.isValid(): return (size.width(), size.height()) else: return (0, 0) except OSError: logging.warning("Could not read image '%s'", str(self.path)) return (0, 0) def _plat_get_blocks(self, block_count_per_side, orientation): image = QImage(str(self.path)) image = image.convertToFormat(QImage.Format_RGB888) if not isinstance(orientation, int): logging.warning( "Orientation for file '%s' was a %s '%s', not an int.", str(self.path), type(orientation), orientation, ) try: orientation = int(orientation) except Exception as e: logging.exception( "Skipping transformation because could not convert %s to int. %s", type(orientation), e, ) return getblocks(image, block_count_per_side) # MYSTERY TO SOLVE: For reasons I cannot explain, orientations 5 and 7 don't work for # duplicate scanning. The transforms seems to work fine (if I try to save the image after # the transform, we see that the image has been correctly flipped and rotated), but the # analysis part yields wrong blocks. I spent enought time with this feature, so I'll leave # like that for now. (by the way, orientations 5 and 7 work fine under Cocoa) if 2 <= orientation <= 8: t = QTransform() if orientation == 2: t.scale(-1, 1) elif orientation == 3: t.rotate(180) elif orientation == 4: t.scale(1, -1) elif orientation == 5: t.scale(-1, 1) t.rotate(90) elif orientation == 6: t.rotate(90) elif orientation == 7: t.scale(-1, 1) t.rotate(270) elif orientation == 8: t.rotate(270) image = image.transformed(t) return getblocks(image, block_count_per_side)
2,767
Python
.py
65
30.753846
98
0.567347
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,084
results_model.py
arsenetar_dupeguru/qt/pe/results_model.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from qt.column import Column from qt.results_model import ResultsModel as ResultsModelBase class ResultsModel(ResultsModelBase): COLUMNS = [ Column("marked", default_width=30), Column("name", default_width=200), Column("folder_path", default_width=180), Column("size", default_width=60), Column("extension", default_width=40), Column("dimensions", default_width=100), Column("exif_timestamp", default_width=120), Column("mtime", default_width=120), Column("percentage", default_width=60), Column("dupe_count", default_width=80), ]
898
Python
.py
20
39.35
89
0.700571
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,085
preferences_dialog.py
arsenetar_dupeguru/qt/me/preferences_dialog.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import QSize from PyQt5.QtWidgets import ( QVBoxLayout, QHBoxLayout, QLabel, QSizePolicy, QSpacerItem, QWidget, ) from hscommon.trans import trget from core.app import AppMode from core.scanner import ScanType from qt.preferences_dialog import PreferencesDialogBase tr = trget("ui") class PreferencesDialog(PreferencesDialogBase): def _setupPreferenceWidgets(self): self._setupFilterHardnessBox() self.widgetsVLayout.addLayout(self.filterHardnessHLayout) self.widget = QWidget(self) self.widget.setMinimumSize(QSize(0, 40)) self.verticalLayout_4 = QVBoxLayout(self.widget) self.verticalLayout_4.setSpacing(0) self.verticalLayout_4.setContentsMargins(0, 0, 0, 0) self.label_6 = QLabel(self.widget) self.label_6.setText(tr("Tags to scan:")) self.verticalLayout_4.addWidget(self.label_6) self.horizontalLayout_2 = QHBoxLayout() self.horizontalLayout_2.setSpacing(0) spacer_item = QSpacerItem(15, 20, QSizePolicy.Fixed, QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacer_item) self._setupAddCheckbox("tagTrackBox", tr("Track"), self.widget) self.horizontalLayout_2.addWidget(self.tagTrackBox) self._setupAddCheckbox("tagArtistBox", tr("Artist"), self.widget) self.horizontalLayout_2.addWidget(self.tagArtistBox) self._setupAddCheckbox("tagAlbumBox", tr("Album"), self.widget) self.horizontalLayout_2.addWidget(self.tagAlbumBox) self._setupAddCheckbox("tagTitleBox", tr("Title"), self.widget) self.horizontalLayout_2.addWidget(self.tagTitleBox) self._setupAddCheckbox("tagGenreBox", tr("Genre"), self.widget) self.horizontalLayout_2.addWidget(self.tagGenreBox) self._setupAddCheckbox("tagYearBox", tr("Year"), self.widget) self.horizontalLayout_2.addWidget(self.tagYearBox) self.verticalLayout_4.addLayout(self.horizontalLayout_2) self.widgetsVLayout.addWidget(self.widget) self._setupAddCheckbox("wordWeightingBox", tr("Word weighting")) self.widgetsVLayout.addWidget(self.wordWeightingBox) self._setupAddCheckbox("matchSimilarBox", tr("Match similar words")) self.widgetsVLayout.addWidget(self.matchSimilarBox) self._setupAddCheckbox("mixFileKindBox", tr("Can mix file kind")) self.widgetsVLayout.addWidget(self.mixFileKindBox) self._setupAddCheckbox("useRegexpBox", tr("Use regular expressions when filtering")) self.widgetsVLayout.addWidget(self.useRegexpBox) self._setupAddCheckbox("removeEmptyFoldersBox", tr("Remove empty folders on delete or move")) self.widgetsVLayout.addWidget(self.removeEmptyFoldersBox) self._setupAddCheckbox( "ignoreHardlinkMatches", tr("Ignore duplicates hardlinking to the same file"), ) self.widgetsVLayout.addWidget(self.ignoreHardlinkMatches) self._setupBottomPart() def _load(self, prefs, setchecked, section): setchecked(self.tagTrackBox, prefs.scan_tag_track) setchecked(self.tagArtistBox, prefs.scan_tag_artist) setchecked(self.tagAlbumBox, prefs.scan_tag_album) setchecked(self.tagTitleBox, prefs.scan_tag_title) setchecked(self.tagGenreBox, prefs.scan_tag_genre) setchecked(self.tagYearBox, prefs.scan_tag_year) setchecked(self.matchSimilarBox, prefs.match_similar) setchecked(self.wordWeightingBox, prefs.word_weighting) # Update UI state based on selected scan type scan_type = prefs.get_scan_type(AppMode.MUSIC) word_based = scan_type in ( ScanType.FILENAME, ScanType.FIELDS, ScanType.FIELDSNOORDER, ScanType.TAG, ) tag_based = scan_type == ScanType.TAG self.filterHardnessSlider.setEnabled(word_based) self.matchSimilarBox.setEnabled(word_based) self.wordWeightingBox.setEnabled(word_based) self.tagTrackBox.setEnabled(tag_based) self.tagArtistBox.setEnabled(tag_based) self.tagAlbumBox.setEnabled(tag_based) self.tagTitleBox.setEnabled(tag_based) self.tagGenreBox.setEnabled(tag_based) self.tagYearBox.setEnabled(tag_based) def _save(self, prefs, ischecked): prefs.scan_tag_track = ischecked(self.tagTrackBox) prefs.scan_tag_artist = ischecked(self.tagArtistBox) prefs.scan_tag_album = ischecked(self.tagAlbumBox) prefs.scan_tag_title = ischecked(self.tagTitleBox) prefs.scan_tag_genre = ischecked(self.tagGenreBox) prefs.scan_tag_year = ischecked(self.tagYearBox) prefs.match_similar = ischecked(self.matchSimilarBox) prefs.word_weighting = ischecked(self.wordWeightingBox)
5,113
Python
.py
101
42.762376
101
0.718369
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,086
details_dialog.py
arsenetar_dupeguru/qt/me/details_dialog.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import QSize from PyQt5.QtWidgets import QAbstractItemView from hscommon.trans import trget from qt.details_dialog import DetailsDialog as DetailsDialogBase from qt.details_table import DetailsTable tr = trget("ui") class DetailsDialog(DetailsDialogBase): def _setupUi(self): self.setWindowTitle(tr("Details")) self.resize(502, 295) self.setMinimumSize(QSize(250, 250)) self.tableView = DetailsTable(self) self.tableView.setAlternatingRowColors(True) self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows) self.tableView.setShowGrid(False) self.setWidget(self.tableView)
949
Python
.py
21
40.714286
89
0.771398
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,087
results_model.py
arsenetar_dupeguru/qt/me/results_model.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from qt.column import Column from qt.results_model import ResultsModel as ResultsModelBase class ResultsModel(ResultsModelBase): COLUMNS = [ Column("marked", default_width=30), Column("name", default_width=200), Column("folder_path", default_width=180), Column("size", default_width=60), Column("duration", default_width=60), Column("bitrate", default_width=50), Column("samplerate", default_width=60), Column("extension", default_width=40), Column("mtime", default_width=120), Column("title", default_width=120), Column("artist", default_width=120), Column("album", default_width=120), Column("genre", default_width=80), Column("year", default_width=40), Column("track", default_width=40), Column("comment", default_width=120), Column("percentage", default_width=60), Column("words", default_width=120), Column("dupe_count", default_width=80), ]
1,286
Python
.py
29
37.724138
89
0.669856
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,088
preferences_dialog.py
arsenetar_dupeguru/qt/se/preferences_dialog.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import QSize from PyQt5.QtWidgets import ( QSpinBox, QVBoxLayout, QHBoxLayout, QLabel, QSizePolicy, QSpacerItem, QWidget, ) from hscommon.trans import trget from core.app import AppMode from core.scanner import ScanType from qt.preferences_dialog import PreferencesDialogBase tr = trget("ui") class PreferencesDialog(PreferencesDialogBase): def _setupPreferenceWidgets(self): self._setupFilterHardnessBox() self.widgetsVLayout.addLayout(self.filterHardnessHLayout) self.widget = QWidget(self) self.widget.setMinimumSize(QSize(0, 136)) self.verticalLayout_4 = QVBoxLayout(self.widget) self._setupAddCheckbox("wordWeightingBox", tr("Word weighting"), self.widget) self.verticalLayout_4.addWidget(self.wordWeightingBox) self._setupAddCheckbox("matchSimilarBox", tr("Match similar words"), self.widget) self.verticalLayout_4.addWidget(self.matchSimilarBox) self._setupAddCheckbox("mixFileKindBox", tr("Can mix file kind"), self.widget) self.verticalLayout_4.addWidget(self.mixFileKindBox) self._setupAddCheckbox("useRegexpBox", tr("Use regular expressions when filtering"), self.widget) self.verticalLayout_4.addWidget(self.useRegexpBox) self._setupAddCheckbox( "removeEmptyFoldersBox", tr("Remove empty folders on delete or move"), self.widget, ) self.verticalLayout_4.addWidget(self.removeEmptyFoldersBox) self.horizontalLayout_2 = QHBoxLayout() self._setupAddCheckbox("ignoreSmallFilesBox", tr("Ignore files smaller than"), self.widget) self.horizontalLayout_2.addWidget(self.ignoreSmallFilesBox) self.sizeThresholdSpinBox = QSpinBox(self.widget) size_policy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed) size_policy.setHorizontalStretch(0) size_policy.setVerticalStretch(0) size_policy.setHeightForWidth(self.sizeThresholdSpinBox.sizePolicy().hasHeightForWidth()) self.sizeThresholdSpinBox.setSizePolicy(size_policy) self.sizeThresholdSpinBox.setMaximumSize(QSize(300, 16777215)) self.sizeThresholdSpinBox.setRange(0, 1000000) self.horizontalLayout_2.addWidget(self.sizeThresholdSpinBox) self.label_6 = QLabel(self.widget) self.label_6.setText(tr("KB")) self.horizontalLayout_2.addWidget(self.label_6) spacer_item1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacer_item1) self.verticalLayout_4.addLayout(self.horizontalLayout_2) self.horizontalLayout_2a = QHBoxLayout() self._setupAddCheckbox("ignoreLargeFilesBox", tr("Ignore files larger than"), self.widget) self.horizontalLayout_2a.addWidget(self.ignoreLargeFilesBox) self.sizeSaturationSpinBox = QSpinBox(self.widget) size_policy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed) self.sizeSaturationSpinBox.setSizePolicy(size_policy) self.sizeSaturationSpinBox.setMaximumSize(QSize(300, 16777215)) self.sizeSaturationSpinBox.setRange(0, 1000000) self.horizontalLayout_2a.addWidget(self.sizeSaturationSpinBox) self.label_6a = QLabel(self.widget) self.label_6a.setText(tr("MB")) self.horizontalLayout_2a.addWidget(self.label_6a) spacer_item3 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_2a.addItem(spacer_item3) self.verticalLayout_4.addLayout(self.horizontalLayout_2a) self.horizontalLayout_2b = QHBoxLayout() self._setupAddCheckbox( "bigFilePartialHashesBox", tr("Partially hash files bigger than"), self.widget, ) self.horizontalLayout_2b.addWidget(self.bigFilePartialHashesBox) self.bigSizeThresholdSpinBox = QSpinBox(self.widget) self.bigSizeThresholdSpinBox.setSizePolicy(size_policy) self.bigSizeThresholdSpinBox.setMaximumSize(QSize(300, 16777215)) self.bigSizeThresholdSpinBox.setRange(0, 1000000) self.horizontalLayout_2b.addWidget(self.bigSizeThresholdSpinBox) self.label_6b = QLabel(self.widget) self.label_6b.setText(tr("MB")) self.horizontalLayout_2b.addWidget(self.label_6b) spacer_item2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_2b.addItem(spacer_item2) self.verticalLayout_4.addLayout(self.horizontalLayout_2b) self._setupAddCheckbox( "ignoreHardlinkMatches", tr("Ignore duplicates hardlinking to the same file"), self.widget, ) self.verticalLayout_4.addWidget(self.ignoreHardlinkMatches) self.widgetsVLayout.addWidget(self.widget) self._setupBottomPart() def _load(self, prefs, setchecked, section): setchecked(self.matchSimilarBox, prefs.match_similar) setchecked(self.wordWeightingBox, prefs.word_weighting) setchecked(self.ignoreSmallFilesBox, prefs.ignore_small_files) self.sizeThresholdSpinBox.setValue(prefs.small_file_threshold) setchecked(self.ignoreLargeFilesBox, prefs.ignore_large_files) self.sizeSaturationSpinBox.setValue(prefs.large_file_threshold) setchecked(self.bigFilePartialHashesBox, prefs.big_file_partial_hashes) self.bigSizeThresholdSpinBox.setValue(prefs.big_file_size_threshold) # Update UI state based on selected scan type scan_type = prefs.get_scan_type(AppMode.STANDARD) word_based = scan_type == ScanType.FILENAME self.filterHardnessSlider.setEnabled(word_based) self.matchSimilarBox.setEnabled(word_based) self.wordWeightingBox.setEnabled(word_based) def _save(self, prefs, ischecked): prefs.match_similar = ischecked(self.matchSimilarBox) prefs.word_weighting = ischecked(self.wordWeightingBox) prefs.ignore_small_files = ischecked(self.ignoreSmallFilesBox) prefs.small_file_threshold = self.sizeThresholdSpinBox.value() prefs.ignore_large_files = ischecked(self.ignoreLargeFilesBox) prefs.large_file_threshold = self.sizeSaturationSpinBox.value() prefs.big_file_partial_hashes = ischecked(self.bigFilePartialHashesBox) prefs.big_file_size_threshold = self.bigSizeThresholdSpinBox.value()
6,728
Python
.py
124
46.112903
105
0.734001
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,089
details_dialog.py
arsenetar_dupeguru/qt/se/details_dialog.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from PyQt5.QtCore import QSize from PyQt5.QtWidgets import QAbstractItemView from hscommon.trans import trget from qt.details_dialog import DetailsDialog as DetailsDialogBase from qt.details_table import DetailsTable tr = trget("ui") class DetailsDialog(DetailsDialogBase): def _setupUi(self): self.setWindowTitle(tr("Details")) self.resize(502, 186) self.setMinimumSize(QSize(200, 0)) self.tableView = DetailsTable(self) self.tableView.setAlternatingRowColors(True) self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows) self.tableView.setShowGrid(False) self.setWidget(self.tableView)
947
Python
.py
21
40.619048
89
0.770901
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,090
results_model.py
arsenetar_dupeguru/qt/se/results_model.py
# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from qt.column import Column from qt.results_model import ResultsModel as ResultsModelBase class ResultsModel(ResultsModelBase): COLUMNS = [ Column("marked", default_width=30), Column("name", default_width=200), Column("folder_path", default_width=180), Column("size", default_width=60), Column("extension", default_width=40), Column("mtime", default_width=120), Column("percentage", default_width=60), Column("words", default_width=120), Column("dupe_count", default_width=80), ]
840
Python
.py
19
38.842105
89
0.701711
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,091
trans.py
arsenetar_dupeguru/hscommon/trans.py
# Created By: Virgil Dupras # Created On: 2010-06-23 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html # Doing i18n with GNU gettext for the core text gets complicated, so what I do is that I make the # GUI layer responsible for supplying a tr() function. import locale import logging import os import os.path as op from typing import Callable, Union from hscommon.plat import ISLINUX _trfunc = None _trget = None installed_lang = None def tr(s: str, context: Union[str, None] = None) -> str: if _trfunc is None: return s else: if context: return _trfunc(s, context) else: return _trfunc(s) def trget(domain: str) -> Callable[[str], str]: # Returns a tr() function for the specified domain. if _trget is None: return lambda s: tr(s, domain) else: return _trget(domain) def set_tr( new_tr: Callable[[str, Union[str, None]], str], new_trget: Union[Callable[[str], Callable[[str], str]], None] = None, ) -> None: global _trfunc, _trget _trfunc = new_tr if new_trget is not None: _trget = new_trget def get_locale_name(lang: str) -> Union[str, None]: # Removed old conversion code as windows seems to support these LANG2LOCALENAME = { "cs": "cs_CZ", "de": "de_DE", "el": "el_GR", "en": "en", "es": "es_ES", "fr": "fr_FR", "hy": "hy_AM", "it": "it_IT", "ja": "ja_JP", "ko": "ko_KR", "ms": "ms_MY", "nl": "nl_NL", "pl_PL": "pl_PL", "pt_BR": "pt_BR", "ru": "ru_RU", "tr": "tr_TR", "uk": "uk_UA", "vi": "vi_VN", "zh_CN": "zh_CN", } if lang not in LANG2LOCALENAME: return None result = LANG2LOCALENAME[lang] if ISLINUX: result += ".UTF-8" return result # --- Qt def install_qt_trans(lang: str = None) -> None: from PyQt5.QtCore import QCoreApplication, QTranslator, QLocale if not lang: lang = str(QLocale.system().name())[:2] localename = get_locale_name(lang) if localename is not None: try: locale.setlocale(locale.LC_ALL, localename) except locale.Error: logging.warning("Couldn't set locale %s", localename) else: lang = "en" qtr1 = QTranslator(QCoreApplication.instance()) qtr1.load(":/qt_%s" % lang) QCoreApplication.installTranslator(qtr1) qtr2 = QTranslator(QCoreApplication.instance()) qtr2.load(":/%s" % lang) QCoreApplication.installTranslator(qtr2) def qt_tr(s: str, context: Union[str, None] = "core") -> str: if context is None: context = "core" return str(QCoreApplication.translate(context, s, None)) set_tr(qt_tr) # --- gettext def install_gettext_trans(base_folder: os.PathLike, lang: str) -> None: import gettext def gettext_trget(domain: str) -> Callable[[str], str]: if not lang: return lambda s: s try: return gettext.translation(domain, localedir=base_folder, languages=[lang]).gettext except OSError: return lambda s: s default_gettext = gettext_trget("core") def gettext_tr(s: str, context: Union[str, None] = None) -> str: if not context: return default_gettext(s) else: trfunc = gettext_trget(context) return trfunc(s) set_tr(gettext_tr, gettext_trget) global installed_lang installed_lang = lang def install_gettext_trans_under_qt(base_folder: os.PathLike, lang: str = None) -> None: # So, we install the gettext locale, great, but we also should try to install qt_*.qm if # available so that strings that are inside Qt itself over which I have no control are in the # right language. from PyQt5.QtCore import QCoreApplication, QTranslator, QLocale, QLibraryInfo if not lang: lang = str(QLocale.system().name())[:2] localename = get_locale_name(lang) if localename is None: lang = "en" localename = get_locale_name(lang) try: locale.setlocale(locale.LC_ALL, localename) except locale.Error: logging.warning("Couldn't set locale %s", localename) qmname = "qt_%s" % lang if ISLINUX: # Under linux, a full Qt installation is already available in the system, we didn't bundle # up the qm files in our package, so we have to load translations from the system. qmpath = op.join(QLibraryInfo.location(QLibraryInfo.TranslationsPath), qmname) else: qmpath = op.join(base_folder, qmname) qtr = QTranslator(QCoreApplication.instance()) qtr.load(qmpath) QCoreApplication.installTranslator(qtr) install_gettext_trans(base_folder, lang)
5,015
Python
.py
139
29.71223
98
0.636082
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,092
loc.py
arsenetar_dupeguru/hscommon/loc.py
import os import os.path as op import shutil import tempfile from typing import Any, List import polib from hscommon import pygettext LC_MESSAGES = "LC_MESSAGES" def get_langs(folder: str) -> List[str]: return [name for name in os.listdir(folder) if op.isdir(op.join(folder, name))] def files_with_ext(folder: str, ext: str) -> List[str]: return [op.join(folder, fn) for fn in os.listdir(folder) if fn.endswith(ext)] def generate_pot(folders: List[str], outpath: str, keywords: Any, merge: bool = False) -> None: if merge and not op.exists(outpath): merge = False if merge: _, genpath = tempfile.mkstemp() else: genpath = outpath pyfiles = [] for folder in folders: for root, dirs, filenames in os.walk(folder): keep = [fn for fn in filenames if fn.endswith(".py")] pyfiles += [op.join(root, fn) for fn in keep] pygettext.main(pyfiles, outpath=genpath, keywords=keywords) if merge: merge_po_and_preserve(genpath, outpath) try: os.remove(genpath) except Exception: print("Exception while removing temporary folder %s\n", genpath) def compile_all_po(base_folder: str) -> None: langs = get_langs(base_folder) for lang in langs: pofolder = op.join(base_folder, lang, LC_MESSAGES) pofiles = files_with_ext(pofolder, ".po") for pofile in pofiles: p = polib.pofile(pofile) p.save_as_mofile(pofile[:-3] + ".mo") def merge_locale_dir(target: str, mergeinto: str) -> None: langs = get_langs(target) for lang in langs: if not op.exists(op.join(mergeinto, lang)): continue mofolder = op.join(target, lang, LC_MESSAGES) mofiles = files_with_ext(mofolder, ".mo") for mofile in mofiles: shutil.copy(mofile, op.join(mergeinto, lang, LC_MESSAGES)) def merge_pots_into_pos(folder: str) -> None: # We're going to take all pot files in `folder` and for each lang, merge it with the po file # with the same name. potfiles = files_with_ext(folder, ".pot") for potfile in potfiles: refpot = polib.pofile(potfile) refname = op.splitext(op.basename(potfile))[0] for lang in get_langs(folder): po = polib.pofile(op.join(folder, lang, LC_MESSAGES, refname + ".po")) po.merge(refpot) po.save() def merge_po_and_preserve(source: str, dest: str) -> None: # Merges source entries into dest, but keep old entries intact sourcepo = polib.pofile(source) destpo = polib.pofile(dest) for entry in sourcepo: if destpo.find(entry.msgid) is not None: # The entry is already there continue destpo.append(entry) destpo.save() def normalize_all_pos(base_folder: str) -> None: """Normalize the format of .po files in base_folder. When getting POs from external sources, such as Transifex, we end up with spurious diffs because of a difference in the way line wrapping is handled. It wouldn't be a big deal if it happened once, but these spurious diffs keep overwriting each other, and it's annoying. Our PO files will keep polib's format. Call this function to ensure that freshly pulled POs are of the right format before committing them. """ langs = get_langs(base_folder) for lang in langs: pofolder = op.join(base_folder, lang, LC_MESSAGES) pofiles = files_with_ext(pofolder, ".po") for pofile in pofiles: p = polib.pofile(pofile) p.save()
3,602
Python
.py
84
35.916667
100
0.657421
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,093
pygettext.py
arsenetar_dupeguru/hscommon/pygettext.py
# This module was taken from CPython's Tools/i18n and dirtily hacked to bypass the need for cmdline # invocation. # Originally written by Barry Warsaw <barry@zope.com> # # Minimally patched to make it even more xgettext compatible # by Peter Funk <pf@artcom-gmbh.de> # # 2002-11-22 Jürgen Hermann <jh@web.de> # Added checks that _() only contains string literals, and # command line args are resolved to module lists, i.e. you # can now pass a filename, a module or package name, or a # directory (including globbing chars, important for Win32). # Made docstring fit in 80 chars wide displays using pydoc. # import os import importlib.machinery import importlib.util import sys import glob import token import tokenize __version__ = "1.5" default_keywords = ["_"] DEFAULTKEYWORDS = ", ".join(default_keywords) EMPTYSTRING = "" # The normal pot-file header. msgmerge and Emacs's po-mode work better if it's # there. pot_header = """ msgid "" msgstr "" "Content-Type: text/plain; charset=utf-8\\n" "Content-Transfer-Encoding: utf-8\\n" """ def usage(code, msg=""): print(__doc__ % globals(), file=sys.stderr) if msg: print(msg, file=sys.stderr) sys.exit(code) escapes = [] def make_escapes(pass_iso8859): global escapes if pass_iso8859: # Allow iso-8859 characters to pass through so that e.g. 'msgid # "H?he"' would result not result in 'msgid "H\366he"'. Otherwise we # escape any character outside the 32..126 range. mod = 128 else: mod = 256 for i in range(256): if 32 <= (i % mod) <= 126: escapes.append(chr(i)) else: escapes.append("\\%03o" % i) escapes[ord("\\")] = "\\\\" escapes[ord("\t")] = "\\t" escapes[ord("\r")] = "\\r" escapes[ord("\n")] = "\\n" escapes[ord('"')] = '\\"' def escape(s): global escapes s = list(s) for i in range(len(s)): s[i] = escapes[ord(s[i])] return EMPTYSTRING.join(s) def safe_eval(s): # unwrap quotes, safely return eval(s, {"__builtins__": {}}, {}) def normalize(s): # This converts the various Python string types into a format that is # appropriate for .po files, namely much closer to C style. lines = s.split("\n") if len(lines) == 1: s = '"' + escape(s) + '"' else: if not lines[-1]: del lines[-1] lines[-1] = lines[-1] + "\n" for i in range(len(lines)): lines[i] = escape(lines[i]) lineterm = '\\n"\n"' s = '""\n"' + lineterm.join(lines) + '"' return s def containsAny(str, set): """Check whether 'str' contains ANY of the chars in 'set'""" return 1 in [c in str for c in set] def _visit_pyfiles(list, dirname, names): """Helper for getFilesForName().""" # get extension for python source files if "_py_ext" not in globals(): global _py_ext _py_ext = importlib.machinery.SOURCE_SUFFIXES[0] # don't recurse into CVS directories if "CVS" in names: names.remove("CVS") # add all *.py files to list list.extend([os.path.join(dirname, file) for file in names if os.path.splitext(file)[1] == _py_ext]) def getFilesForName(name): """Get a list of module files for a filename, a module or package name, or a directory. """ if not os.path.exists(name): # check for glob chars if containsAny(name, "*?[]"): files = glob.glob(name) file_list = [] for file in files: file_list.extend(getFilesForName(file)) return file_list # try to find module or package try: spec = importlib.util.find_spec(name) name = spec.origin except ImportError: name = None if not name: return [] if os.path.isdir(name): # find all python files in directory file_list = [] os.walk(name, _visit_pyfiles, file_list) return file_list elif os.path.exists(name): # a single file return [name] return [] class TokenEater: def __init__(self, options): self.__options = options self.__messages = {} self.__state = self.__waiting self.__data = [] self.__lineno = -1 self.__freshmodule = 1 self.__curfile = None def __call__(self, ttype, tstring, stup, etup, line): # dispatch # import token # print >> sys.stderr, 'ttype:', token.tok_name[ttype], \ # 'tstring:', tstring self.__state(ttype, tstring, stup[0]) def __waiting(self, ttype, tstring, lineno): opts = self.__options # Do docstring extractions, if enabled if opts.docstrings and not opts.nodocstrings.get(self.__curfile): # module docstring? if self.__freshmodule: if ttype == tokenize.STRING: self.__addentry(safe_eval(tstring), lineno, isdocstring=1) self.__freshmodule = 0 elif ttype not in (tokenize.COMMENT, tokenize.NL): self.__freshmodule = 0 return # class docstring? if ttype == tokenize.NAME and tstring in ("class", "def"): self.__state = self.__suiteseen return if ttype == tokenize.NAME and tstring in opts.keywords: self.__state = self.__keywordseen def __suiteseen(self, ttype, tstring, lineno): # ignore anything until we see the colon if ttype == tokenize.OP and tstring == ":": self.__state = self.__suitedocstring def __suitedocstring(self, ttype, tstring, lineno): # ignore any intervening noise if ttype == tokenize.STRING: self.__addentry(safe_eval(tstring), lineno, isdocstring=1) self.__state = self.__waiting elif ttype not in (tokenize.NEWLINE, tokenize.INDENT, tokenize.COMMENT): # there was no class docstring self.__state = self.__waiting def __keywordseen(self, ttype, tstring, lineno): if ttype == tokenize.OP and tstring == "(": self.__data = [] self.__lineno = lineno self.__state = self.__openseen else: self.__state = self.__waiting def __openseen(self, ttype, tstring, lineno): if ttype == tokenize.OP and tstring == ")": # We've seen the last of the translatable strings. Record the # line number of the first line of the strings and update the list # of messages seen. Reset state for the next batch. If there # were no strings inside _(), then just ignore this entry. if self.__data: self.__addentry(EMPTYSTRING.join(self.__data)) self.__state = self.__waiting elif ttype == tokenize.STRING: self.__data.append(safe_eval(tstring)) elif ttype not in [ tokenize.COMMENT, token.INDENT, token.DEDENT, token.NEWLINE, tokenize.NL, ]: # warn if we see anything else than STRING or whitespace print( '*** %(file)s:%(lineno)s: Seen unexpected token "%(token)s"' % {"token": tstring, "file": self.__curfile, "lineno": self.__lineno}, file=sys.stderr, ) self.__state = self.__waiting def __addentry(self, msg, lineno=None, isdocstring=0): if lineno is None: lineno = self.__lineno if msg not in self.__options.toexclude: entry = (self.__curfile, lineno) self.__messages.setdefault(msg, {})[entry] = isdocstring def set_filename(self, filename): self.__curfile = filename self.__freshmodule = 1 def write(self, fp): options = self.__options # The time stamp in the header doesn't have the same format as that # generated by xgettext... print(pot_header, file=fp) # Sort the entries. First sort each particular entry's keys, then # sort all the entries by their first item. reverse = {} for k, v in self.__messages.items(): keys = sorted(v.keys()) reverse.setdefault(tuple(keys), []).append((k, v)) rkeys = sorted(reverse.keys()) for rkey in rkeys: rentries = reverse[rkey] rentries.sort() for k, v in rentries: # If the entry was gleaned out of a docstring, then add a # comment stating so. This is to aid translators who may wish # to skip translating some unimportant docstrings. isdocstring = any(v.values()) # k is the message string, v is a dictionary-set of (filename, # lineno) tuples. We want to sort the entries in v first by # file name and then by line number. v = sorted(v.keys()) if not options.writelocations: pass # location comments are different b/w Solaris and GNU: elif options.locationstyle == options.SOLARIS: for filename, lineno in v: d = {"filename": filename, "lineno": lineno} print("# File: %(filename)s, line: %(lineno)d" % d, file=fp) elif options.locationstyle == options.GNU: # fit as many locations on one line, as long as the # resulting line length doesn't exceeds 'options.width' locline = "#:" for filename, lineno in v: d = {"filename": filename, "lineno": lineno} s = " %(filename)s:%(lineno)d" % d if len(locline) + len(s) <= options.width: locline = locline + s else: print(locline, file=fp) locline = "#:" + s if len(locline) > 2: print(locline, file=fp) if isdocstring: print("#, docstring", file=fp) print("msgid", normalize(k), file=fp) print('msgstr ""\n', file=fp) def main(source_files, outpath, keywords=None): global default_keywords # for holding option values class Options: # constants GNU = 1 SOLARIS = 2 # defaults extractall = 0 # FIXME: currently this option has no effect at all. escape = 0 keywords = [] outfile = "messages.pot" writelocations = 1 locationstyle = GNU verbose = 0 width = 78 excludefilename = "" docstrings = 0 nodocstrings = {} options = Options() options.outfile = outpath if keywords: options.keywords = keywords # calculate escapes make_escapes(options.escape) # calculate all keywords options.keywords.extend(default_keywords) # initialize list of strings to exclude if options.excludefilename: try: fp = open(options.excludefilename, encoding="utf-8") options.toexclude = fp.readlines() fp.close() except OSError: print( "Can't read --exclude-file: %s" % options.excludefilename, file=sys.stderr, ) sys.exit(1) else: options.toexclude = [] # slurp through all the files eater = TokenEater(options) for filename in source_files: if options.verbose: print("Working on %s" % filename) fp = open(filename, encoding="utf-8") closep = 1 try: eater.set_filename(filename) try: tokens = tokenize.generate_tokens(fp.readline) for _token in tokens: eater(*_token) except tokenize.TokenError as e: print( "%s: %s, line %d, column %d" % (e.args[0], filename, e.args[1][0], e.args[1][1]), file=sys.stderr, ) finally: if closep: fp.close() fp = open(options.outfile, "w", encoding="utf-8") closep = 1 try: eater.write(fp) finally: if closep: fp.close()
12,539
Python
.py
329
28.300912
104
0.559257
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,094
sphinxgen.py
arsenetar_dupeguru/hscommon/sphinxgen.py
# Copyright 2018 Virgil Dupras # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from pathlib import Path import re from typing import Callable, Dict, Union from hscommon.build import read_changelog_file, filereplace from sphinx.cmd.build import build_main as sphinx_build CHANGELOG_FORMAT = """ {version} ({date}) ---------------------- {description} """ def tixgen(tixurl: str) -> Callable[[str], str]: """This is a filter *generator*. tixurl is a url pattern for the tix with a {0} placeholder for the tix # """ urlpattern = tixurl.format("\\1") # will be replaced buy the content of the first group in re R = re.compile(r"#(\d+)") repl = f"`#\\1 <{urlpattern}>`__" return lambda text: R.sub(repl, text) def gen( basepath: Path, destpath: Path, changelogpath: Path, tixurl: str, confrepl: Union[Dict[str, str], None] = None, confpath: Union[Path, None] = None, changelogtmpl: Union[Path, None] = None, ) -> None: """Generate sphinx docs with all bells and whistles. basepath: The base sphinx source path. destpath: The final path of html files changelogpath: The path to the changelog file to insert in changelog.rst. tixurl: The URL (with one formattable argument for the tix number) to the ticket system. confrepl: Dictionary containing replacements that have to be made in conf.py. {name: replacement} """ if confrepl is None: confrepl = {} if confpath is None: confpath = Path(basepath, "conf.tmpl") if changelogtmpl is None: changelogtmpl = Path(basepath, "changelog.tmpl") changelog = read_changelog_file(changelogpath) tix = tixgen(tixurl) rendered_logs = [] for log in changelog: description = tix(log["description"]) # The format of the changelog descriptions is in markdown, but since we only use bulled list # and links, it's not worth depending on the markdown package. A simple regexp suffice. description = re.sub(r"\[(.*?)\]\((.*?)\)", "`\\1 <\\2>`__", description) rendered = CHANGELOG_FORMAT.format(version=log["version"], date=log["date_str"], description=description) rendered_logs.append(rendered) confrepl["version"] = changelog[0]["version"] changelog_out = Path(basepath, "changelog.rst") filereplace(changelogtmpl, changelog_out, changelog="\n".join(rendered_logs)) if Path(confpath).exists(): conf_out = Path(basepath, "conf.py") filereplace(confpath, conf_out, **confrepl) # Call the sphinx_build function, which is the same as doing sphinx-build from cli try: sphinx_build([str(basepath), str(destpath)]) except SystemExit: print("Sphinx called sys.exit(), but we're cancelling it because we don't actually want to exit")
2,969
Python
.py
66
40.151515
113
0.687975
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,095
util.py
arsenetar_dupeguru/hscommon/util.py
# Created By: Virgil Dupras # Created On: 2011-01-11 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from math import ceil from pathlib import Path from hscommon.path import pathify, log_io_error from typing import IO, Any, Callable, Generator, Iterable, List, Tuple, Union def nonone(value: Any, replace_value: Any) -> Any: """Returns ``value`` if ``value`` is not ``None``. Returns ``replace_value`` otherwise.""" if value is None: return replace_value else: return value def tryint(value: Any, default: int = 0) -> int: """Tries to convert ``value`` to in ``int`` and returns ``default`` if it fails.""" try: return int(value) except (TypeError, ValueError): return default # --- Sequence related def dedupe(iterable: Iterable[Any]) -> List[Any]: """Returns a list of elements in ``iterable`` with all dupes removed. The order of the elements is preserved. """ result = [] seen = {} for item in iterable: if item in seen: continue seen[item] = 1 result.append(item) return result def flatten(iterables: Iterable[Iterable], start_with: Iterable[Any] = None) -> List[Any]: """Takes a list of lists ``iterables`` and returns a list containing elements of every list. If ``start_with`` is not ``None``, the result will start with ``start_with`` items, exactly as if ``start_with`` would be the first item of lists. """ result: List[Any] = [] if start_with: result.extend(start_with) for iterable in iterables: result.extend(iterable) return result def first(iterable: Iterable[Any]): """Returns the first item of ``iterable``.""" try: return next(iter(iterable)) except StopIteration: return None def extract(predicate: Callable[[Any], bool], iterable: Iterable[Any]) -> Tuple[List[Any], List[Any]]: """Separates the wheat from the shaft (`predicate` defines what's the wheat), and returns both.""" wheat = [] shaft = [] for item in iterable: if predicate(item): wheat.append(item) else: shaft.append(item) return wheat, shaft def allsame(iterable: Iterable[Any]) -> bool: """Returns whether all elements of 'iterable' are the same.""" it = iter(iterable) try: first_item = next(it) except StopIteration: raise ValueError("iterable cannot be empty") return all(element == first_item for element in it) def iterconsume(seq: List[Any], reverse: bool = True) -> Generator[Any, None, None]: """Iterate over ``seq`` and pops yielded objects. Because we use the ``pop()`` method, we reverse ``seq`` before proceeding. If you don't need to do that, set ``reverse`` to ``False``. This is useful in tight memory situation where you are looping over a sequence of objects that are going to be discarded afterwards. If you're creating other objects during that iteration you might want to use this to avoid ``MemoryError``. """ if reverse: seq.reverse() while seq: yield seq.pop() # --- String related def escape(s: str, to_escape: str, escape_with: str = "\\") -> str: """Returns ``s`` with characters in ``to_escape`` all prepended with ``escape_with``.""" return "".join((escape_with + c if c in to_escape else c) for c in s) def get_file_ext(filename: str) -> str: """Returns the lowercase extension part of filename, without the dot.""" pos = filename.rfind(".") if pos > -1: return filename[pos + 1 :].lower() else: return "" def rem_file_ext(filename: str) -> str: """Returns the filename without extension.""" pos = filename.rfind(".") if pos > -1: return filename[:pos] else: return filename # TODO type hint number def pluralize(number, word: str, decimals: int = 0, plural_word: Union[str, None] = None) -> str: """Returns a pluralized string with ``number`` in front of ``word``. Adds a 's' to s if ``number`` > 1. ``number``: The number to go in front of s ``word``: The word to go after number ``decimals``: The number of digits after the dot ``plural_word``: If the plural rule for word is more complex than adding a 's', specify a plural """ number = round(number, decimals) plural_format = "%%1.%df %%s" % decimals if number > 1: if plural_word is None: word += "s" else: word = plural_word return plural_format % (number, word) def format_time(seconds: int, with_hours: bool = True) -> str: """Transforms seconds in a hh:mm:ss string. If ``with_hours`` if false, the format is mm:ss. """ minus = seconds < 0 if minus: seconds *= -1 m, s = divmod(seconds, 60) if with_hours: h, m = divmod(m, 60) r = "%02d:%02d:%02d" % (h, m, s) else: r = "%02d:%02d" % (m, s) if minus: return "-" + r else: return r def format_time_decimal(seconds: int) -> str: """Transforms seconds in a strings like '3.4 minutes'.""" minus = seconds < 0 if minus: seconds *= -1 if seconds < 60: r = pluralize(seconds, "second", 1) elif seconds < 3600: r = pluralize(seconds / 60.0, "minute", 1) elif seconds < 86400: r = pluralize(seconds / 3600.0, "hour", 1) else: r = pluralize(seconds / 86400.0, "day", 1) if minus: return "-" + r else: return r SIZE_DESC = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") SIZE_VALS = tuple(1024**i for i in range(1, 9)) def format_size(size: int, decimal: int = 0, forcepower: int = -1, showdesc: bool = True) -> str: """Transform a byte count in a formatted string (KB, MB etc..). ``size`` is the number of bytes to format. ``decimal`` is the number digits after the dot. ``forcepower`` is the desired suffix. 0 is B, 1 is KB, 2 is MB etc.. if kept at -1, the suffix will be automatically chosen (so the resulting number is always below 1024). if ``showdesc`` is ``True``, the suffix will be shown after the number. Usage example:: >>> format_size(1234, decimal=2, showdesc=True) '1.21 KB' """ if forcepower < 0: i = 0 while size >= SIZE_VALS[i]: i += 1 else: i = forcepower if i > 0: div = SIZE_VALS[i - 1] else: div = 1 size_format = "%%%d.%df" % (decimal, decimal) negative = size < 0 divided_size = (0.0 + abs(size)) / div if decimal == 0: divided_size = ceil(divided_size) else: divided_size = ceil(divided_size * (10**decimal)) / (10**decimal) if negative: divided_size *= -1 result = size_format % divided_size if showdesc: result += " " + SIZE_DESC[i] return result def multi_replace(s: str, replace_from: Union[str, List[str]], replace_to: Union[str, List[str]] = "") -> str: """A function like str.replace() with multiple replacements. ``replace_from`` is a list of things you want to replace. Ex: ['a','bc','d'] ``replace_to`` is a list of what you want to replace to. If ``replace_to`` is a list and has the same length as ``replace_from``, ``replace_from`` items will be translated to corresponding ``replace_to``. A ``replace_to`` list must have the same length as ``replace_from`` If ``replace_to`` is a string, all ``replace_from`` occurence will be replaced by that string. ``replace_from`` can also be a str. If it is, every char in it will be translated as if ``replace_from`` would be a list of chars. If ``replace_to`` is a str and has the same length as ``replace_from``, it will be transformed into a list. """ if isinstance(replace_to, str) and (len(replace_from) != len(replace_to)): replace_to = [replace_to for _ in replace_from] if len(replace_from) != len(replace_to): raise ValueError("len(replace_from) must be equal to len(replace_to)") replace = list(zip(replace_from, replace_to)) for r_from, r_to in [r for r in replace if r[0] in s]: s = s.replace(r_from, r_to) return s # --- Files related @log_io_error @pathify def delete_if_empty(path: Path, files_to_delete: List[str] = []) -> bool: """Deletes the directory at 'path' if it is empty or if it only contains files_to_delete.""" if not path.exists() or not path.is_dir(): return False contents = list(path.glob("*")) if any(p for p in contents if (p.name not in files_to_delete) or p.is_dir()): return False for p in contents: p.unlink() path.rmdir() return True def open_if_filename( infile: Union[Path, str, IO], mode: str = "rb", ) -> Tuple[IO, bool]: """If ``infile`` is a string, it opens and returns it. If it's already a file object, it simply returns it. This function returns ``(file, should_close_flag)``. The should_close_flag is True is a file has effectively been opened (if we already pass a file object, we assume that the responsibility for closing the file has already been taken). Example usage:: fp, shouldclose = open_if_filename(infile) dostuff() if shouldclose: fp.close() """ if isinstance(infile, Path): return (infile.open(mode), True) if isinstance(infile, str): return (open(infile, mode), True) else: return (infile, False) class FileOrPath: """Does the same as :func:`open_if_filename`, but it can be used with a ``with`` statement. Example:: with FileOrPath(infile): dostuff() """ def __init__(self, file_or_path: Union[Path, str], mode: str = "rb") -> None: self.file_or_path = file_or_path self.mode = mode self.mustclose = False self.fp: Union[IO, None] = None def __enter__(self) -> IO: self.fp, self.mustclose = open_if_filename(self.file_or_path, self.mode) return self.fp def __exit__(self, exc_type, exc_value, traceback) -> None: if self.fp and self.mustclose: self.fp.close()
10,435
Python
.py
259
34.332046
111
0.628461
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,096
path.py
arsenetar_dupeguru/hscommon/path.py
# Created By: Virgil Dupras # Created On: 2006/02/21 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import logging from functools import wraps from inspect import signature from pathlib import Path def pathify(f): """Ensure that every annotated :class:`Path` arguments are actually paths. When a function is decorated with ``@pathify``, every argument with annotated as Path will be converted to a Path if it wasn't already. Example:: @pathify def foo(path: Path, otherarg): return path.listdir() Calling ``foo('/bar', 0)`` will convert ``'/bar'`` to ``Path('/bar')``. """ sig = signature(f) pindexes = {i for i, p in enumerate(sig.parameters.values()) if p.annotation is Path} pkeys = {k: v for k, v in sig.parameters.items() if v.annotation is Path} def path_or_none(p): return None if p is None else Path(p) @wraps(f) def wrapped(*args, **kwargs): args = tuple((path_or_none(a) if i in pindexes else a) for i, a in enumerate(args)) kwargs = {k: (path_or_none(v) if k in pkeys else v) for k, v in kwargs.items()} return f(*args, **kwargs) return wrapped def log_io_error(func): """Catches OSError, IOError and WindowsError and log them""" @wraps(func) def wrapper(path, *args, **kwargs): try: return func(path, *args, **kwargs) except OSError as e: msg = 'Error "{0}" during operation "{1}" on "{2}": "{3}"' classname = e.__class__.__name__ funcname = func.__name__ logging.warning(msg.format(classname, funcname, str(path), str(e))) return wrapper
1,892
Python
.py
42
38.952381
97
0.651961
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,097
plat.py
arsenetar_dupeguru/hscommon/plat.py
# Created On: 2011/09/22 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html # Yes, I know, there's the 'platform' unit for this kind of stuff, but the thing is that I got a # crash on startup once simply for importing this module and since then I don't trust it. One day, # I'll investigate the cause of that crash further. import sys ISWINDOWS = sys.platform == "win32" ISOSX = sys.platform == "darwin" ISLINUX = sys.platform.startswith("linux")
675
Python
.py
13
50.692308
98
0.760243
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,098
desktop.py
arsenetar_dupeguru/hscommon/desktop.py
# Created By: Virgil Dupras # Created On: 2013-10-12 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html from enum import Enum from os import PathLike import os.path as op import logging class SpecialFolder(Enum): APPDATA = 1 CACHE = 2 def open_url(url: str) -> None: """Open ``url`` with the default browser.""" _open_url(url) def open_path(path: PathLike) -> None: """Open ``path`` with its associated application.""" _open_path(str(path)) def reveal_path(path: PathLike) -> None: """Open the folder containing ``path`` with the default file browser.""" _reveal_path(str(path)) def special_folder_path(special_folder: SpecialFolder, portable: bool = False) -> str: """Returns the path of ``special_folder``. ``special_folder`` is a SpecialFolder.* const. The result is the special folder for the current application. The running process' application info is used to determine relevant information. You can override the application name with ``appname``. This argument is ingored under Qt. """ return _special_folder_path(special_folder, portable=portable) try: from PyQt5.QtCore import QUrl, QStandardPaths from PyQt5.QtGui import QDesktopServices from qt.util import get_appdata from core.util import executable_folder from hscommon.plat import ISWINDOWS, ISOSX import subprocess def _open_url(url: str) -> None: QDesktopServices.openUrl(QUrl(url)) def _open_path(path: str) -> None: url = QUrl.fromLocalFile(str(path)) QDesktopServices.openUrl(url) def _reveal_path(path: str) -> None: if ISWINDOWS: subprocess.run(["explorer", "/select,", op.abspath(path)]) elif ISOSX: subprocess.run(["open", "-R", op.abspath(path)]) else: _open_path(op.dirname(str(path))) def _special_folder_path(special_folder: SpecialFolder, portable: bool = False) -> str: if special_folder == SpecialFolder.CACHE: if ISWINDOWS and portable: folder = op.join(executable_folder(), "cache") else: folder = QStandardPaths.standardLocations(QStandardPaths.CacheLocation)[0] else: folder = get_appdata(portable) return folder except ImportError: # We're either running tests, and these functions don't matter much or we're in a really # weird situation. Let's just have dummy fallbacks. logging.warning("Can't setup desktop functions!") def _open_url(url: str) -> None: # Dummy for tests pass def _open_path(path: str) -> None: # Dummy for tests pass def _reveal_path(path: str) -> None: # Dummy for tests pass def _special_folder_path(special_folder: SpecialFolder, portable: bool = False) -> str: return "/tmp"
3,091
Python
.py
73
36.136986
99
0.679025
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)
28,099
conflict.py
arsenetar_dupeguru/hscommon/conflict.py
# Created By: Virgil Dupras # Created On: 2008-01-08 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html """When you have to deal with names that have to be unique and can conflict together, you can use this module that deals with conflicts by prepending unique numbers in ``[]`` brackets to the name. """ import re import os import shutil from errno import EISDIR, EACCES from pathlib import Path from typing import Callable, List # This matches [123], but not [12] (3 digits being the minimum). # It also matches [1234] [12345] etc.. # And only at the start of the string re_conflict = re.compile(r"^\[\d{3}\d*\] ") def get_conflicted_name(other_names: List[str], name: str) -> str: """Returns name with a ``[000]`` number in front of it. The number between brackets depends on how many conlicted filenames there already are in other_names. """ name = get_unconflicted_name(name) if name not in other_names: return name i = 0 while True: newname = "[%03d] %s" % (i, name) if newname not in other_names: return newname i += 1 def get_unconflicted_name(name: str) -> str: """Returns ``name`` without ``[]`` brackets. Brackets which, of course, might have been added by func:`get_conflicted_name`. """ return re_conflict.sub("", name, 1) def is_conflicted(name: str) -> bool: """Returns whether ``name`` is prepended with a bracketed number.""" return re_conflict.match(name) is not None def _smart_move_or_copy(operation: Callable, source_path: Path, dest_path: Path) -> None: """Use move() or copy() to move and copy file with the conflict management.""" if dest_path.is_dir() and not source_path.is_dir(): dest_path = dest_path.joinpath(source_path.name) if dest_path.exists(): filename = dest_path.name dest_dir_path = dest_path.parent newname = get_conflicted_name(os.listdir(str(dest_dir_path)), filename) dest_path = dest_dir_path.joinpath(newname) operation(str(source_path), str(dest_path)) def smart_move(source_path: Path, dest_path: Path) -> None: """Same as :func:`smart_copy`, but it moves files instead.""" _smart_move_or_copy(shutil.move, source_path, dest_path) def smart_copy(source_path: Path, dest_path: Path) -> None: """Copies ``source_path`` to ``dest_path``, recursively and with conflict resolution.""" try: _smart_move_or_copy(shutil.copy, source_path, dest_path) except OSError as e: # It's a directory, code is 21 on OS X / Linux (EISDIR) and 13 on Windows (EACCES) if e.errno in (EISDIR, EACCES): _smart_move_or_copy(shutil.copytree, source_path, dest_path) else: raise
2,971
Python
.py
64
41.5
98
0.682825
arsenetar/dupeguru
5,226
412
427
GPL-3.0
9/5/2024, 5:13:58 PM (Europe/Amsterdam)