File size: 9,589 Bytes
d33203e
 
 
 
 
8a74c03
3ae1127
8a74c03
 
44413bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d33203e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a74c03
 
 
 
 
 
 
 
 
 
 
 
 
d33203e
8a74c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d33203e
 
8a74c03
a5ab0c0
8a74c03
 
 
 
a5ab0c0
 
d33203e
 
 
 
8a74c03
 
 
d33203e
8a74c03
 
 
a5ab0c0
8a74c03
 
 
 
 
 
 
d33203e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a74c03
d33203e
 
8a74c03
d33203e
 
8a74c03
d33203e
 
 
 
 
 
 
8a74c03
d33203e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de27cb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d33203e
 
 
d5db6c8
 
 
 
 
 
44413bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5db6c8
de27cb2
 
d5db6c8
 
d33203e
 
d5db6c8
 
8a74c03
 
d33203e
 
 
 
 
8a74c03
d33203e
d5db6c8
 
d33203e
 
 
 
 
 
 
 
 
d5db6c8
 
 
d33203e
 
d5db6c8
 
 
 
 
d33203e
d5db6c8
 
d33203e
 
d5db6c8
d33203e
 
d5db6c8
d33203e
 
8a74c03
d5db6c8
8a74c03
 
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#!/usr/bin/env python3
"""
Main Streamlit application for video frame analysis with ontology-based risk assessment
Refactored for better code organization and maintainability
"""
import streamlit as st

import json
from dotenv import load_dotenv
# --- Reproducibility & Threading ---
import os, random
import numpy as np

# Falls torch/cv2 verfügbar sind: Seeds/Threads setzen
try:
    import torch
    TORCH_AVAILABLE = True
except Exception:
    TORCH_AVAILABLE = False

try:
    import cv2
    CV2_AVAILABLE = True
except Exception:
    CV2_AVAILABLE = False

SEED = 42
random.seed(SEED)
np.random.seed(SEED)
os.environ["PYTHONHASHSEED"] = str(SEED)

if TORCH_AVAILABLE:
    torch.manual_seed(SEED)
    torch.set_num_threads(1)  # vermeidet non-deterministische Parallel-Reduktionen
    # Optional (nur wenn keine Fehlermeldung kommt):
    # torch.use_deterministic_algorithms(True)

if CV2_AVAILABLE:
    try:
        cv2.setNumThreads(1)   # OpenCV deterministischer
    except Exception:
        pass



# Import our modular components
from video_processing import extract_frames_from_video
from ontology_integration import analyze_scene_with_ontology, extract_scene_description
from model_processing import process_frame
from ui_components import (
    render_sidebar_config,
    render_input_section,
    render_prompt_section,
    render_process_button,
    render_results_header,
    render_frame_result,
    render_validation_errors,
    render_instructions
)

# Try to import local models, fall back gracefully if not available
try:
    from local_models import get_local_model_manager
    LOCAL_MODELS_AVAILABLE = True
except ImportError as e:
    LOCAL_MODELS_AVAILABLE = False
    print(f"Local models not available: {e}")
    def get_local_model_manager():
        return None

# Load environment variables
load_dotenv()


def load_settings():
    """Load settings from JSON file"""
    try:
        with open('settings.json', 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        return {}


@st.cache_resource
def initialize_local_models():
    """Initialize local model manager"""
    return get_local_model_manager()


def initialize_app():
    """Initialize the Streamlit application"""
    st.set_page_config(
        page_title="Masterarbeit – Prototyp zur Bahngleiserfassung",
        page_icon="🎥",
        layout="wide"
    )
    
    st.title("🎥 Masterarbeit – Prototyp zur Bahngleiserfassung")
    st.markdown(" Dieses Tool wurde im Rahmen einer Masterarbeit entwickelt. Es dient zur **Analyse von Videoaufnahmen auf sicherheitskritische Situationen** im Bahnumfeld. Der Prototyp verwendet **lokale KI-Modelle**, um Personen im Gleisbereich zu erkennen,  und kombiniert diese Erkennung mit einer ontologiebasierten Risikobewertung zur Einschätzung  potenzieller Gefahren.")


def setup_local_models():
    """Setup local models and return availability status"""
    local_manager = None
    local_models_available = False
    
    if LOCAL_MODELS_AVAILABLE:
        try:
            local_manager = initialize_local_models()
            local_models_available = True
            st.success("🤖 Die lokalen Modelle wurden erfolgreich geladen.!")
        except Exception as e:
            st.warning(f"Local AI models not available: {str(e)}")
            st.info("💡 Install AI packages: `pip install torch torchvision transformers accelerate sentencepiece`")
            local_models_available = False
    else:
        st.info("💡 Local AI models not installed. Install with: `pip install torch torchvision transformers accelerate sentencepiece`")
    
    return local_manager, local_models_available


def process_video_frames(video_file, config, local_manager=None):
    """
    Process all frames in the video and return results
    """
    # Extract frames
    frames = extract_frames_from_video(video_file, config["fps"])
    
    if not frames:
        st.error("No frames could be extracted from the video")
        return []
    
    st.success(f"Extracted {len(frames)} frames from video")
    
    # Process each frame
    results = []
    progress_bar = st.progress(0)
    
    # Add prompt to config for processing
    processing_config = config.copy()
    processing_config["prompt"] = config.get("prompt", "")
    
    for i, frame_data in enumerate(frames):
        with st.spinner(f"Analyzing frame {i+1}/{len(frames)}..."):
            # Process frame with selected model
            result = process_frame(frame_data, processing_config, local_manager)
            
            # Extract scene description for ontology analysis
            scene_description = extract_scene_description(result)
            
            # Apply ontology analysis
            ontology_analysis = analyze_scene_with_ontology(scene_description, config["use_ontology"])
            
            results.append({
                'frame_number': frame_data['frame_number'],
                'timestamp': frame_data['timestamp'],
                'image': frame_data['frame'],
                'result': result,
                'ontology_analysis': ontology_analysis
            })
            
            progress_bar.progress((i + 1) / len(frames))
    
    return results


def validate_inputs(video_file, prompt, config, local_models_available):
    """
    Validate all required inputs
    """
    model_type = config["model_type"]
    selected_model = config["selected_model"]
    api_token = config["api_token"]
    
    # Check basic requirements
    if not video_file:
        return False
    
    # Check prompt requirements
    if not prompt and not (model_type == "Local Models" and selected_model == "Person on Track Detector"):
        return False
    
    # Check API token for remote models
    if not api_token and model_type == "Remote API":
        return False
    
    # Check local models availability
    if model_type == "Local Models" and not local_models_available:
        return False
    
    return True
# --- Passwort-Check (aus secrets oder Env) ---
import os

def check_password() -> bool:
    st.sidebar.title("🔐 Zugriff")
    password = st.sidebar.text_input("Passwort", type="password")

    if password == "rexhbeqaj":  # <-- dein Passwort hier
        st.sidebar.success("Zugang erlaubt ✅")
        return True
    elif password:
        st.sidebar.error("❌ Falsches Passwort")
    return False




def main():
    """Main application entry point"""

    # 1) Seite konfigurieren (muss der erste Streamlit-Call sein)
    initialize_app()

    # 2) Diagnostics anzeigen (Versionen)
    with st.expander("Diagnostics (Versionen)"):
        versions = {}
        try:
            import cv2; versions["opencv"] = cv2.__version__
        except Exception: versions["opencv"] = "n/a"
        try:
            import numpy as _np; versions["numpy"] = _np.__version__
        except Exception: versions["numpy"] = "n/a"
        try:
            import torch as _torch; versions["torch"] = _torch.__version__
        except Exception: versions["torch"] = "n/a"
        try:
            import transformers as _tf; versions["transformers"] = _tf.__version__
        except Exception: versions["transformers"] = "n/a"
        try:
            import PIL; versions["pillow"] = PIL.__version__
        except Exception: versions["pillow"] = "n/a"
        st.write(versions)

    # 3) Passwort prüfen
    if not check_password():
        st.stop()

    # 4) Settings & Modelle
    settings = load_settings()
    local_manager, local_models_available = setup_local_models()

    # 5) Layout & UI
    col1, col2 = st.columns([1, 1])
    with col1:
        config = render_sidebar_config(settings, local_models_available, local_manager)
        input_data = render_input_section()
        video_file = input_data["video_file"]
        prompt = render_prompt_section(config)
        process_button = render_process_button()
    with col2:
        results_container = render_results_header()

    # 6) Logik
    if process_button:
        if validate_inputs(video_file, prompt, config, local_models_available):
            config["prompt"] = prompt
            with st.spinner("Processing video..."):
                results = process_video_frames(video_file, config, local_manager)
                if results:
                    with results_container:
                        st.subheader("Analysis Results")
                        severity_counts = {}
                        for r in results:
                            sev = r['ontology_analysis'].get('severity', 'NONE')
                            severity_counts[sev] = severity_counts.get(sev, 0) + 1
                        if config["use_ontology"] and severity_counts:
                            st.write("**Summary:**")
                            cols = st.columns(len(severity_counts))
                            icon = {'NONE':'✅','LOW':'🟢','MEDIUM':'🟠','HIGH':'⚠️','CRITICAL':'🚨'}
                            for i,(sev,cnt) in enumerate(severity_counts.items()):
                                with cols[i]:
                                    st.metric(f"{icon.get(sev,'❓')} {sev}", cnt)
                            st.divider()
                        for rd in results:
                            render_frame_result(rd)
        else:
            render_validation_errors(
                video_file, prompt, config["api_token"],
                config["model_type"], local_models_available, config["selected_model"]
            )

    render_instructions()



if __name__ == "__main__":
    main()