Creating a local movie catalog involves setting up a simple web server that can interact with your filesystem, process movie directories, and serve an interactive HTML page where you can browse, sort, and filter your movies. Below are the three essential files you'll need:
server.py: A Python Flask server that processes the movie directories and serves the data to the frontend.
index.html: The frontend HTML page that displays the movie catalog with interactive features.
start_here.bat: A batch file to start the Python server and open the HTML page in your default web browser.
Let's go through each file step-by-step.
1. server.py
This Python script uses the Flask framework to create a local server that:
- Serves the
index.html and any static files (like CSS and images).
- Provides an API endpoint (
/api/movies) that accepts a root folder path, scans the movie directories, and returns movie data in JSON format.
Dependencies:
- Flask: Install it using
pip install flask.
Code:
from flask import Flask, request, jsonify, send_from_directory
import os
import re
from datetime import datetime
app = Flask(__name__, static_folder='')
# Function to parse movie folder names
def parse_movie_folder(folder_name):
pattern = r'^(.*?)\s+\((\d{4})\)\s+([A-Za-z\s,]+)\s+([\d.]+)$'
match = re.match(pattern, folder_name)
if match:
name = match.group(1).strip()
year = int(match.group(2))
genres = [genre.strip() for genre in match.group(3).split(',')]
rating = float(match.group(4))
return {
'name': name,
'year': year,
'genres': genres,
'rating': rating
}
else:
return None
# API endpoint to get movies
@app.route('/api/movies', methods=['POST'])
def get_movies():
data = request.get_json()
root_path = data.get('root_path')
if not root_path or not os.path.isdir(root_path):
return jsonify({'error': 'Invalid root path'}), 400
movies = []
for folder in os.listdir(root_path):
folder_path = os.path.join(root_path, folder)
if os.path.isdir(folder_path):
movie_info = parse_movie_folder(folder)
if movie_info:
# Initialize movie details
movie = {
'name': movie_info['name'],
'year': movie_info['year'],
'genres': movie_info['genres'],
'rating': movie_info['rating'],
'cover': '',
'has_subtitle': False,
'mp4': '',
'folder_path': folder_path,
'created_time': os.path.getctime(folder_path)
}
# Scan for files in the movie folder
for file in os.listdir(folder_path):
file_path = os.path.join(folder_path, file)
if os.path.isfile(file_path):
ext = file.split('.')[-1].lower()
if ext in ['jpg', 'jpeg', 'png']:
movie['cover'] = f"/movies/{folder}/" + file
elif ext == 'mp4':
movie['mp4'] = file
elif ext in ['srt', 'sub']:
movie['has_subtitle'] = True
elif os.path.isdir(file_path):
if file.lower() == 'sub':
for subfile in os.listdir(file_path):
sub_ext = subfile.split('.')[-1].lower()
if sub_ext in ['srt', 'sub']:
movie['has_subtitle'] = True
break
movies.append(movie)
# Sort movies by name by default
movies.sort(key=lambda x: x['name'])
return jsonify({'movies': movies})
# Route to serve movie cover images
@app.route('/movies/<folder>/<filename>')
def serve_movie_cover(folder, filename):
return send_from_directory(os.path.join('/', folder), filename)
# Serve index.html
@app.route('/')
def index():
return send_from_directory('', 'index.html')
if __name__ == '__main__':
app.run(debug=True)
Explanation:
parse_movie_folder: Uses a regular expression to extract movie name, year, genres, and rating from the folder name.
/api/movies: Accepts a JSON POST request with the root_path, scans each subfolder, and extracts movie information.
/movies/<folder>/<filename>: Serves the movie cover images.
/: Serves the index.html file.
2. index.html
This HTML file provides the user interface for your movie catalog. It includes:
- An input field to enter the root folder path.
- A button to process the entered path.
- Display of the number of movies found.
- Sort and search functionalities.
- A grid layout to display movie cards with details and action buttons.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Local Movie Catalog</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
#controls {
margin-bottom: 20px;
}
#movies-count {
margin-top: 10px;
font-weight: bold;
}
#filter-sort {
margin-top: 10px;
display: flex;
gap: 10px;
align-items: center;
}
#movies-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 20px;
}
.movie-card {
border: 1px solid #ccc;
border-radius: 8px;
padding: 10px;
position: relative;
box-shadow: 2px 2px 6px rgba(0,0,0,0.1);
}
.movie-cover {
width: 100%;
height: 300px;
object-fit: cover;
border-radius: 4px;
}
.rating {
position: absolute;
top: 10px;
right: 10px;
background-color: rgba(255, 165, 0, 0.9);
color: white;
border-radius: 50%;
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
}
.movie-name {
font-size: 18px;
margin: 10px 0 5px 0;
font-weight: bold;
}
.movie-genres {
font-size: 14px;
color: #555;
margin-bottom: 10px;
}
.subtitle-tag {
display: inline-block;
padding: 4px 8px;
background-color: #28a745;
color: white;
border-radius: 4px;
font-size: 12px;
margin-bottom: 10px;
}
.buttons {
display: flex;
gap: 10px;
}
.buttons button {
flex: 1;
padding: 8px;
border: none;
border-radius: 4px;
cursor: pointer;
color: white;
}
.open-movie {
background-color: #007bff;
}
.open-folder {
background-color: #6c757d;
}
/* Responsive adjustments */
@media (max-width: 600px) {
.movie-cover {
height: 200px;
}
}
</style>
</head>
<body>
<h1>Local Movie Catalog</h1>
<div id="controls">
<input type="text" id="root-path" placeholder="Enter root folder path" size="50">
<button id="process-button">Process Path</button>
<div id="movies-count"></div>
<div id="filter-sort">
<input type="text" id="search-input" placeholder="Search by name" size="30">
<label for="sort-select">Sort by:</label>
<select id="sort-select">
<option value="name">Name</option>
<option value="year">Year</option>
<option value="created_time">Date Added</option>
</select>
</div>
</div>
<div id="movies-grid"></div>
<script>
const processButton = document.getElementById('process-button');
const rootPathInput = document.getElementById('root-path');
const moviesGrid = document.getElementById('movies-grid');
const moviesCount = document.getElementById('movies-count');
const searchInput = document.getElementById('search-input');
const sortSelect = document.getElementById('sort-select');
let movies = [];
processButton.addEventListener('click', () => {
const rootPath = rootPathInput.value.trim();
if (!rootPath) {
alert('Please enter a valid root folder path.');
return;
}
fetch('/api/movies', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ root_path: rootPath }),
})
.then(response => response.json())
.then(data => {
if (data.error) {
alert(data.error);
return;
}
movies = data.movies;
moviesCount.textContent = `Movies Found: ${movies.length}`;
renderMovies();
})
.catch(err => {
console.error(err);
alert('An error occurred while fetching movies.');
});
});
// Render movies based on current movies array
function renderMovies() {
const searchTerm = searchInput.value.toLowerCase();
const sortBy = sortSelect.value;
let filteredMovies = movies.filter(movie => movie.name.toLowerCase().includes(searchTerm));
filteredMovies.sort((a, b) => {
if (sortBy === 'name') {
return a.name.localeCompare(b.name);
} else if (sortBy === 'year') {
return b.year - a.year;
} else if (sortBy === 'created_time') {
return b.created_time - a.created_time;
}
return 0;
});
moviesGrid.innerHTML = '';
filteredMovies.forEach(movie => {
const card = document.createElement('div');
card.className = 'movie-card';
// Movie Cover
const cover = document.createElement('img');
cover.src = movie.cover ? movie.cover : 'https://via.placeholder.com/200x300?text=No+Cover';
cover.alt = `${movie.name} Cover`;
cover.className = 'movie-cover';
card.appendChild(cover);
// Rating
const rating = document.createElement('div');
rating.className = 'rating';
rating.textContent = movie.rating;
card.appendChild(rating);
// Movie Name
const name = document.createElement('div');
name.className = 'movie-name';
name.textContent = movie.name;
card.appendChild(name);
// Genres
const genres = document.createElement('div');
genres.className = 'movie-genres';
genres.textContent = movie.genres.join(', ');
card.appendChild(genres);
// Subtitle Tag
if (movie.has_subtitle) {
const subtitleTag = document.createElement('div');
subtitleTag.className = 'subtitle-tag';
subtitleTag.textContent = 'Subtitle';
card.appendChild(subtitleTag);
}
// Buttons
const buttonsDiv = document.createElement('div');
buttonsDiv.className = 'buttons';
// Open Movie Button
const openMovieBtn = document.createElement('button');
openMovieBtn.className = 'open-movie';
openMovieBtn.textContent = 'Play';
openMovieBtn.onclick = () => {
const moviePath = `"${movie.folder_path}\\${movie.mp4}"`;
window.open(`file:///${moviePath}`);
};
buttonsDiv.appendChild(openMovieBtn);
// Open Folder Button
const openFolderBtn = document.createElement('button');
openFolderBtn.className = 'open-folder';
openFolderBtn.textContent = 'Open Folder';
openFolderBtn.onclick = () => {
const folderPath = `"${movie.folder_path}"`;
window.open(`file:///${folderPath}`);
};
buttonsDiv.appendChild(openFolderBtn);
card.appendChild(buttonsDiv);
moviesGrid.appendChild(card);
});
}
// Event listeners for search and sort
searchInput.addEventListener('input', renderMovies);
sortSelect.addEventListener('change', renderMovies);
</script>
</body>
</html>
Explanation:
- Controls Section: Allows users to input the root folder path, process it, view the number of movies found, and apply search and sort filters.
- Movies Grid: Displays movie cards in a responsive grid layout.
- Movie Card: Each card shows the movie cover, rating, name, genres, subtitle tag (if available), and buttons to play the movie or open its folder.
- JavaScript Functionality:
- Fetch Movies: Sends a POST request to the server with the root path to retrieve movie data.
- Render Movies: Dynamically creates and displays movie cards based on the fetched data, applying search and sort filters.
- Buttons: Use the
file:/// protocol to open the movie file with the default video player or open the movie's folder.
Note: Modern browsers may have restrictions on opening local files directly from JavaScript for security reasons. If you encounter issues with the "Play" or "Open Folder" buttons, consider using alternative methods or adjusting browser settings as needed.
3. start_here.bat
This batch file automates the process of starting the Python server and opening the index.html page in your default web browser.
Code:
@echo off
echo Starting the local movie catalog server...
REM Activate virtual environment if you have one
REM call path\to\your\venv\Scripts\activate.bat
REM Start the Flask server
start cmd /k "python server.py"
REM Give the server a moment to start
timeout /t 2 /nobreak > NUL
REM Open the default browser to the local server
start http://127.0.0.1:5000/
echo Server started and browser opened.
pause
Explanation:
- Start Flask Server: Opens a new command prompt window and runs
server.py.
- Wait: Gives the server a couple of seconds to start before attempting to open the browser.
- Open Browser: Launches
http://127.0.0.1:5000/ in your default web browser.
- Pause: Keeps the batch window open so you can see any server logs or messages.
Instructions:
- Save the Files: Ensure all three files (
server.py, index.html, and start_here.bat) are saved in the same directory.
- Install Flask: Open a command prompt and navigate to the directory containing the files. Run:
pip install flask
- Run the Batch File: Double-click
start_here.bat to start the server and open the web page.
- Use the Application:
- Enter the full path to your root movie directory in the input field (e.g.,
C:\Users\YourName\Videos\Movies).
- Click "Process Path" to load and display your movies.
- Use the search and sort features to navigate through your catalog.
Example Root Path:
C:\Users\YourName\Videos\Movies
Security Considerations:
- This setup is intended for local use only. Exposing the server to external networks can pose security risks.
- Ensure that the Flask server is only accessible from
localhost unless you have specific needs and understand the security implications.
Final Notes
-
Folder Naming Convention: Ensure that your movie folders strictly follow the naming pattern:
movie_name (year) genre1, genre2, ... rating
For example:
The Matrix (1999) Action, Sci-Fi 8.7
This allows the server.py script to correctly parse and extract movie information.
-
File Placement: Each movie folder should contain:
- An
.mp4 file for the movie.
- A
.jpg (or other image format) file for the cover.
- Optional subtitle files (
.srt, .sub) either in the main folder or inside a sub subfolder.
-
Extending Functionality: You can enhance this setup by adding more features such as:
- Pagination for large movie libraries.
- More detailed movie information (e.g., descriptions, directors).
- User authentication for restricted access.
Enjoy your organized and easily navigable local movie catalog!