background magic

19 09 2011

Back again. So you got some important date/deadline and want to display it permantly on your desktop wallpaper?

wallpaper with additional text

Wallpaper with deadline text

One solution comes with imagemagick. It provides a way to directly push text into an image file. This text can be overlayed on an existing image file and afterwards set this resulting image as wallpaper (for GNOME environment in the following script).

The way the following script works? Ok, first we copy the desired image to a predefined location. Then we resize it to the screen width/heigth (depending on the source image aspect ratio) and crop its borders. Then we overlay the desired boxes and text. Finally we (re)set it als the gnome wallpaper.
If you just execute the script it will only update the days/hours, if you execute it with a variable, it will use the given image as the new background image.

#!/bin/bash
# imagemagick and exiftool required
# maybe someone wants to replace the exiftool-part with identify (also part of imagemagick)

## initial conditions
# empty source file without text overlay
sourcefile=~/hintergrund.jpg
if [[ $1 != "" ]]	# if new file is chosen
        then    cp $1 $sourcefile	# replace old file
fi			# sourcefile necessary for hourly updates
targetfile=~/wallpaper.jpg

# fonts used (best used with complete paths)
font1=/usr/share/texmf/fonts/opentype/public/lm/lmsansquot8-bold.otf
font2=/usr/share/texmf/fonts/opentype/public/lm/lmsans8-regular.otf

# opacity of overlay text/lines
opacity=0.5

# hours (stunden), days (tage)
stunden=$(( ($(date -d "2011-09-22 11:23" +%s) - $(date +%s))/(60*60) ))
tage=$(( $stunden / 24 ))

## image analysis, background resizing and cropping
# monitor/background resolution
width=1280
height=800
# image resolution
sourcewidth=$(exiftool -ImageWidth $sourcefile | sed "s/.*: //g")
sourceheight=$(exiftool -ImageHeight $sourcefile | sed "s/.*: //g")
# calculation of resize-factor
# something a bit more complicated to calculate the image aspect ratio because I found no way to calculate float numbers in the bash. so I just use very big numbers...
afactor=$(( $sourcewidth * $height ))
bfactor=$(( $sourceheight * $width ))
# source-file - portrait or landscape-mode?
if [[ $afactor > $bfactor  ]]
then resizefactor=x$height
	echo lanscape
else resizefactor=$width
	echo portrait
fi	
# resize and crop source image
convert $sourcefile -resize $resizefactor \
                    -gravity South -crop ${width}x${height}+0+0 $targetfile

## create and overlay text and boxes
# in detail: 
# - draw 2 boxes with round corners
# - place day/hour variables
# - place day/hour text
# for more info...see imagemagick/convert man page or homepage
convert $targetfile \
	-fill transparent -stroke black -strokewidth 5 -gravity center \
       	-draw "stroke-opacity $opacity roundrectangle 1040,70 1240,270 20,20 \
	       roundrectangle 1040,315 1240,475 20,20" \
	-strokewidth 1 -fill black -stroke transparent \
	-font $font1 -pointsize 130 -draw "fill-opacity $opacity text 499,-260 '$tage' " \
	             -pointsize 100 -draw "fill-opacity $opacity text 499,-30 '$stunden' " \
	-font $font2 -pointsize 40 -draw "fill-opacity $opacity text 499,-157 'Tage' " \
	             -pointsize 28 -draw "fill-opacity $opacity text 499,47 'Stunden' " \
	 $targetfile 

## set image as background (gnome only)
gconftool-2 -t str --set /desktop/gnome/background/picture_filename $baum$1
gconftool-2 -t str --set /desktop/gnome/background/picture_options stretched
# alternatives: "none", "wallpaper", "centered", "scaled", "stretched", "zoom", "spanned"


So…if you like to…just adapt it to your needs, display the joke of the day or whatever you like.





just listen…

22 07 2011

so. you want to listen to your favourite internet radio station in the console? not a problem with today’s script. all you additionally need is a playlists-folder where you store your onlineradio-playlist-files.

Usage:
$ listen sputnik
whereas sputnik is a playlist file in the playlists-folder (see below)

Newer versions of mplayer are able to capture the current audio stream using the -capture option, combined with the -dumpfile argument. Using this you can record the current stream pressing the ‘c’ key on the keyboard. Note that if you repeatedly press the ‘c’ key, the sound will be appended. No new file is being created until you restart mplayer or rename the recorded file in between.
If your version of mplayer does not support this option use the line without -capture and -dumpfile.

#!/bin/bash
# folder
plfolder="~/music/.playlists"
capturefile=~/radio_$1_$(date +%Y%m%d_%H%M).mp3
# if help is wanted...list the files in the playlist-folder
if [ "$1" = '--help' ] || [ "$1" = "-h" ] || [ "$1" = "help" ]
then  ls $plfolder
 exit 1
fi

clear
echo Tuning in to $1 
# version with capture option (newer versions of mplayer)
mplayer -capture -loop 0 -playlist ${plfolder}/$1  -dumpfile $capturefile
# version without capture option (older versions)
# mplayer -loop 0 -playlist ${plfolder}/$1


some example playlist files:
(somehow the http creates empty lines that were not intended – just cancel out all empty lines in your local playlist files)

sputnik – alternative radio stations (mdr, germany)










top40 – dance/party music

http://stream.hoerradar.de/mp3-radiotop40-192
http://stream.hoerradar.de/mp3-radiotop40-electro-192

chris – some christian internet radio staions

http://www.christianrock.net/CRDN/live/high.pls
http://www.christianhardrock.net/CHRDN/live2/high.pls
http://www.christian-hiphop.net/CHHDN/live/high.pls
http://www.christianpowerpraise.net/CPPDN/live/high.pls

norge – norwegian radio

mms://straumr.nrk.no/nrk_radio_mp3_m
mms://wms.yourstation.com/RadioTromsoLive
mms://straumr.nrk.no/nrk_radio_p1_m
mms://straumr.nrk.no/nrk_radio_p2_m
mms://straumr.nrk.no/nrk_radio_p3_m
#mms://straumr.nrk.no/nrk_radio_p3_urort_m
mms://straumr.nrk.no/nrk_radio_alltid_folkemusikk_m
mms://straumr.nrk.no/nrk_radio_alltid_nyheter_m
mms://straumr.nrk.no/nrk_radio_alltid_klassisk_m
mms://straumr.nrk.no/nrk_radio_barn_m

andes – music from the peru

http://74.55.180.162:8020
http://74.55.180.162:9304       
http://173.212.214.10:7148
http://173.212.214.10:8526

You may post your favourite radio station in the comments if you like to.





Unwetterwarnung

20 07 2011

So this time in Deutsch. Der Deutsche Wetterdienst gibt auf seiner Homepage relativ zeitnah Unwetterwarnungen heraus. Um mir die Arbeit zu ersparen, dort des Öfteren nachsehen zu müssen, und trotzdem bescheid zu wissen wann ein größeres Gewitter o.ä. aufzieht hab ich mir das folgende Skript erdacht.

Es holt sich von der Homepage die Warnungen für den festgelegten Landkreis. Dieser String wird bei Vorhandensein einer Warnung im untigen Fall an notify-send übergeben und erscheint somit als kleines Popup, wie es auch andere Programme verwenden. Zudem wird dann noch die Timeline-Grafik (für die Dauer der Warnung) heruntergeladen und kurzzeitig mit einem image_viewer angezeigt.
Vom Prinzip her ist das Meiste glaub ich selbsterklärend. Auch im Panel erscheint ein Warnsymbol.

Die Landkreise entsprechen (meiner Erkenntnis nach) den entsprechenden amtlichen Kennzeichen, bei Bedarf mit ‘X’en auf drei Buchstaben erweitert (BXX – Berlin , KIX – Kiel, COE – Coesfeld). Zur Sicherheit einfach mal auf der DWD-Seite nachschaun. Hierzu auf der Warnkarte den gewünschen Kreis anklicken und in der URL das entsprechende Kürzel suchen (Ausnahmen z.B. WUE statt WÜX für Würzburg – macht ja auch Sinn).

[edit: normalerweise wird der Standard-Landkreis gecheckt, bei übergebener Variable der alternative Kreis]
usage:
$ wetterdienst [LKR]

#!/bin/bash
# display weather warnings using notify-send
## settings
notify_header="Wetterwarnungen für Berlin"
popup_icon=~/Bilder/Wetterwarnung.png
landkreis=BXX
image_viewer=display # must be able to handle URLs
## check for alternative location
if [ "$1" != "" ] 
then landkreis=$1
     notify_header="Wetterwarnungen für "$landkreis
fi
## get warnings
textstring=$(wget 'http://www.dwd.de/dyn/app/ws/html/reports/'${landkreis}'_warning_de.html' -O -  | grep -i "warnung vor" | sed s/\<\\/p\>//g ) 
## check warnings
if [ "$textstring" = ""  ]  
## if there's no warning
# then exit 0;
then notify-send --icon=$popup_icon """$notify_header""" "keine Warnungen vorhanden"
## if there are warnings
# do funny things
else notify-send --icon=$popup_icon """$notify_header""" """$textstring"""
# do some acoustic output
#espeak -v de """$textstring"""
# set a notification in the taskbar
zenity --notification --text="""$textstring""" &
# display the warning timeline for some seconds
 $image_viewer http://www.dwd.de/dyn/app/ws/maps/${landkreis}_timeline.png &
 sleep 4
 kill $!
fi


Natürlich kann man den Warn-String beliebig anderweitig weiterverarbeiten, sich einen cronjob anlegen, der alle 30 Minuten nachschaut ob’s was neues gibt (hierbei nicht vergessen das DISPLAY zu definieren) und sich nur bei vorhandener rührt, ansonsten abbricht.

Grundsätzlich könnte man auch die Timeline über imagemagick mit dem Desktop-Hintergrund oder einem sonstigen Element verwursten…das jedoch obliegt den Anforderungen und dem Ideenreichtum jedes Einzelnen. Viel Freude!





Bon Voyage! (german railway edition)

1 07 2011

So. This might be especially helpful to our german friends who quickly want to know when the next train goes from A to B. Or when the trains go on a special date.
Opens your favourite browser with the travelling-information-page without the need to klick a lot before.
Usage:
$ bahnanfrage start ziel [nv]
or
$ bahnanfrage start ziel dd.mm.yy hh:mm [nv]
The last parameter nv is optional, meaning that no ICE or IC trains are to be used (Nur Nahverkehr).

#!/bin/bash
# bahnanfrage - short bash tool to launch browser with right data feed
## Help
if [ "$1" = "-h" ]
then echo "bahnanfrage start ziel [nv]
	or
bahnanfrage start ziel dd.mm.yy hh:mm [nv] "
exit 1
fi
## Variables
browser=firefox
von=$1
nach=$2
if [ "$3" = "nv"  ] || [ "$3" = ""  ]
then
	wochentag=$( date +%a)
	datum=$(date +%d.%m.%y)
            zeit=$(date +%H:%M)
	if [ "$3" = "nv"   ]
		then
		        nahverkehr="&journeyProducts=1016"
		else
		        nahverkehr=""
	fi

else
	wochentag=$( date -d $(echo $5-$4-$3) +%a)
	datum=$3
	zeit=$4
	if [ "$5" = "nv"   ]
	then    
	        nahverkehr="&journeyProducts=1016"
	else
	        nahverkehr=""
	fi  
fi
$browser 'http://reiseauskunft.bahn.de/bin/query.exe/dn?revia=yes&existOptimizePrice=1&country=DEU&initialAvail=ON&dbkanal_007=L01_S01_D001_KIN0001_qf-bahn_LZ003&start=1&S='${von}'&REQ0JourneyStopsSID=&Z='${nach}'&REQ0JourneyStopsZID=&trip-type=single&date='${wochentag}'%2C+'${datum}'&time='${zeit}'&timesel=depart&returnTimesel=depart&optimize=0&travelProfile=-1&adult-number=1&children-number=0&infant-number=0&tariffTravellerType.1=E&tariffTravellerReductionClass.1=0&tariffTravellerAge.1=&qf-trav-bday-1=&tariffClass=2'$nahverkehr





Bon Voyage!

30 06 2011

A simple but yet helpful line if you quickly want to look up the track from A to B. Opens google maps in your favourite browser, displaying the desired route.
$ gmaps city_1 city_2

#!/bin/bash
browser=firefox
from=$1
to=$2
$browser 'http://maps.google.de/maps?saddr='${from}'&daddr='${to}





compress images in pdf files

30 06 2011

so this might be useful if you want to forward/store a pdf file (newsletter etc.) that contains uncompressed images. Using ghostscript you can resize them inside the pdf file.
$ pdfcompress inputfile.pdf outputfile.pdf

#!/bin/bash
gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile=$2 $1
# more options:
# http://milan.kupcevic.net/ghostscript-ps-pdf/


With thanks to Milan Kupcevic for the inspiration. More options (especially regarding the image resolution) can be found on his page.





laser sword

22 06 2011

If you ever wanted to print colored text with a monochrome laser printer, you might have encountered the same problem I had: You just can’t read the light blue letters.
The following script can resolve the problem. It converts the pdf to a ps file and (as far as I understand) sets the font color to black (completeley black, not greyscale, halftonig etc.). The output file is a pdf again.
$ pdf_uncolor filename.pdf

#!/bin/bash
# adapted from http://superuser.com/questions/200378/converting-a-pdf-to-black-white-with-ghostscript
tempfile=/tmp/pdf_uncolor_temp.ps
rm $tempfile 
pdf2ps $1 $tempfile
gs -o bw_$1 -sDEVICE=pdfwrite -c "/setrgbcolor{0 mul 3 1 roll 0 mul 3 1 roll 0 mul 3 1 roll 0 mul add add setgray }def" -f $tempfile
rm $tempfile


Thanks to superuser.com for the template. Though I don’t completely understand the ps operations, I was able to adapt them to my needs.