File: pixindex/pixindex.py

#!/usr/bin/python3
"""
====================================================================================
pixindex.py -- make+upload a simple images-viewer HTML page plus zipfile.
Created: April 2015, by M. Lutz (learning-python.com), for Python 3.X.
License: Provided freely, but with no warranties of any kind.

Generate an HTML page to view a folder of images -- inline in the page, by links
in the page, and by an automatically created and linked zipfile of the photos.
Transfer the photos and generated zipfile and HTML page to a site folder by FTP.

The HTML page file and zipfile are created in and uploaded from the photos dir.
Configured by assignments at start of script's code below: run with no arguments.
All-uppercase names here are used in HTML template (and fetched from vars() dict).
Use "index.html" for HTML filename to avoid another level in the target URL.

DONE: to do - automatically upload the output file and images (and zip) via FTP.
DONE: to do - automatically generate zipfile of the photos, ref in HTML, upload.
To do - use Pillow to create thumbnails or small versions auto for HTML inline use.

UPDATES, 2022:
- For a later approach, see also https://learning-python.com/thumbspage.html.
- For a later zip tool, see also https://learning-python.com/ziptools.html.
- Most hosts don't support unsecure FTP anymore; use scp or other FTP tools.
====================================================================================
"""

import os, mimetypes, zipfile, shutil
from PP4E_tools.ftptools import FtpTools


# Configuration settings (change all ? and others as needed)

photodir  = 'pix'                   # where photos dir lives here on local machine
sitedir   = '?sdzoo2015'            # where to store html, photos, zipfile on web server
PAGETITLE = '?San Diego Zoos 2015'  # HTML output page's title
htmlname  = 'index.html'            # HTML page's name in photodir (or None=stdout)
zipname   = '?sdzoo2015.zip'        # zipfile created in photodir  (or None=don't make zip)
ftpsite   = '?_yoursite_.com'       # site to copy photodir to     (or None=don't ftp to site)
ftpuser   = input('FTP user id?')   # site user id; password input via console prompt


# HTML templates (change as desired)

# the main page template
pagetemplate = """
<HTML>
<!-- HTML and zipfile generated by pixindex.py -->
<HEAD>
<TITLE>%(PAGETITLE)s</TITLE>
%(HEADINSERT)s
</HEAD>
<BODY bgcolor=white>
<H1>%(PAGETITLE)s</H1>

<P>
View pictures below,
%(ZIPFILEREF)s
or open them individually using the following list:

<UL>
%(INDEXLIST)s
</UL>
</P>
<HR>

%(INLINELIST)s
<HR>

<P align=right>
<I>Generated by <A HREF="http://learning-python.com/pixindex.html">pixindex.py</A></I>
</P>
</BODY></HTML>
"""

# evil tracking analytics javascript code goes here...
HEADINSERT = """
<!-- any head insert code -->
"""


def isImageFile(filename):
    "detect images by file mimetype (not hardcoded set)"
    filetype = mimetypes.guess_type(filename)[0]                    # (type?, encoding?)
    return filetype != None and filetype.split('/')[0] == 'image'   # e.g., 'image/jpeg'


# Build html index/photo lists (all relative to dir)

INDEXLIST  = ''
INLINELIST = ''
for filename in os.listdir(photodir):
    if isImageFile(filename):
        INDEXLIST  += '<LI><A HREF="%s">%s</A>\n' % (filename, filename)
        INLINELIST += '<P><img src="%s">\n\n' % filename 


# Create optional zipfile of photos (in and relative to dir)

if not zipname:
    ZIPFILEREF = ''
else:
    zipobj = zipfile.ZipFile(os.path.join(photodir, zipname), 'w')
    for filename in os.listdir(photodir):
        if isImageFile(filename):
            zipobj.write(os.path.join(photodir, filename))
    zipobj.close()
    ZIPFILEREF = ('fetch them all as a <A HREF="%s">zipfile here</A>, ' % zipname)


# Create and print/save html page (in photo dir)

if not htmlname:
    print(pagetemplate % vars())
else:
    output = open(os.path.join(photodir, htmlname), 'w')   # default encoding
    print(pagetemplate % vars(), file=output)
    output.close()


# Upload photos+zip+html folder by ftp (to web site folder)

if ftpsite:
    # makes remote site's dir if doesn't already exist
    ftp = FtpTools()
    ftp.configTransfer(site=ftpsite, rdir=sitedir, user=ftpuser)
    ftp.localdir = photodir
    ftp.run(cleanTarget=ftp.cleanRemotes, transferAct=ftp.uploadDir, makedir=True)



[Home page] Books Code Blog Python Author Train Find ©M.Lutz