Skip to content

Instantly share code, notes, and snippets.

@zpmorgan
Last active August 5, 2016 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zpmorgan/c35ed77e55f847fb5792b059230ea2d9 to your computer and use it in GitHub Desktop.
Save zpmorgan/c35ed77e55f847fb5792b059230ea2d9 to your computer and use it in GitHub Desktop.
random jigsaw puzzle launcher
#!/usr/bin/env perl
#./rand-jig.pl -p 200 -s 'imaginarylandscapes/top?sort=top&t=all'
use Modern::Perl;
use Mojo::UserAgent;
use Getopt::Long;
use Path::Tiny;
my $img_dir = "~/jig-images";
my $reddit_url = 'https://www.reddit.com/r/NoSillySuffix/';
my $pieces = 200;
my $subreddit;
GetOptions(
"subreddit=s" => \$subreddit,
"pieces=i" => \$pieces,
"directory=s" => \$img_dir,
);
$reddit_url = 'https://www.reddit.com/r/' . $subreddit if $subreddit;
sub fetch_random{
my $ua = Mojo::UserAgent->new;
my $tx = $ua->get($reddit_url);
#my @links = $tx->res->dom->find('a[href*="//i.imgur"]')->shuffle->each;
my @links = $tx->res->dom->find('a[href*=".jpg"]')->shuffle->each;
@links = grep {$_->attr('href') =~ /jpg/} @links; #no gifs or pngs.
#my @urls = map {$_->attr('href')} @links;
say scalar (@links) . 'images found.';
die 'blah' unless @links;
while(scalar @links){
#say $links[0];
#say $urls[0];
my $link = shift @links;
my $url = $link->attr('href');
$url =~ /([^\/]+\.jpg)/;
die " ??? $url" unless $1;
my $dirpath = path($img_dir);
my $ipath = $dirpath->child($1);
$ipath->mkpath unless $dirpath->exists;
# e.g. /tmp/fldsah.jpg
next if $ipath->exists; #dont present the same puzzle.
#my $itx = $ua->get($urls[0]);
use LWP::Simple qw(getstore);
my $ua = LWP::UserAgent->new();
my $response = $ua->get($url);
if (!$response->is_success){
warn $url;
warn $response->status_line;
next;
}
my $file = $response->decoded_content( charset => 'none' );
say "URL: $url";
if ($url =~ m|i.imgur.com/([\w\d]+).jpg|){
say "imgur page: http://imgur.com/$1";
}
say "saving at $ipath";
getstore($url,"$ipath");
return $ipath;
}
die "nothing here.";
}
my $ipath = fetch_random();
use Image::Size;
use POSIX 'round';
my ($x,$y) = imgsize("$ipath");
say "x,y: $x $y";
my $aspect = $x / $y;
#no more round() with -ts
my $xt = (sqrt($pieces) * $aspect);
my $yt = (sqrt($pieces) / $aspect);
say "tiles: $xt $yt " . $xt*$yt;
my $ts = 800 / $xt;
if($x > $y){
#portrait rotation...
#dont feel like counting the pieces but i think this should work.
$ts = 800 / $yt;
}
my $xjig_command = "xjig -ww 800 -file $ipath -ts $ts";
#my $xjig_command = "xjig -ww 800 -w $xt -h $yt -file $ipath";
say "command: $xjig_command";
say '' for 1..4;
say `$xjig_command`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment