File size: 1,709 Bytes
41b7e6b
 
3a60318
41b7e6b
 
 
 
3a60318
41b7e6b
 
 
 
 
3a60318
41b7e6b
 
 
 
 
 
 
3a60318
 
41b7e6b
 
 
 
 
3a60318
41b7e6b
 
 
3a60318
 
 
41b7e6b
 
3a60318
 
41b7e6b
 
3a60318
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import os
import json
import uvicorn
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

# --- Part 1: Automatic File List Generation ---
# This code runs ONCE when the application starts.

DATA_DIR = "data"
OUTPUT_FILE = "filelist.json"

def generate_file_list():
    """Scans the data directory and creates a fresh filelist.json."""
    print("--- Running automatic file scan ---")
    if not os.path.exists(DATA_DIR):
        print(f"Warning: The '{DATA_DIR}' directory was not found. Creating an empty list.")
        filenames = []
    else:
        filenames = [f for f in os.listdir(DATA_DIR) if f.endswith(".html")]
    
    # In a Hugging Face Space, we need to make sure we write to a writable directory.
    # The root directory is writable.
    with open(OUTPUT_FILE, 'w') as f:
        json.dump(filenames, f)
        
    print(f"Successfully created '{OUTPUT_FILE}' with {len(filenames)} files.")

# Run the function on startup to generate the file list
generate_file_list()


# --- Part 2: The FastAPI Web Server ---

# Create the main application instance
app = FastAPI()

# This "mounts" the static file server. It serves all files from the current
# directory ('.') and makes index.html the default page.
app.mount("/", StaticFiles(directory=".", html=True), name="static")


# --- Part 3: The Runner ---
# This is the crucial part that fixes the error. It explicitly starts the server.

if __name__ == "__main__":
    # Uvicorn is the server that runs our FastAPI application.
    # host="0.0.0.0" makes it accessible within the Hugging Face environment.
    # port=7860 is the standard port Hugging Face Spaces expects.
    uvicorn.run(app, host="0.0.0.0", port=7860)