import os import json from openai import OpenAI # ------------------------------------------------- # Customer / Willkommensseite # ------------------------------------------------- BASE_DIR = os.path.dirname(os.path.abspath(__file__)) MEDIA_DIR = os.path.join(BASE_DIR, "media") WELCOME_FILENAME = "welcome.html" def get_openai_client(): """Initialize OpenAI client from environment variable""" # api_key = os.getenv("OPENAI_API_KEY") api_key = "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" if not api_key: raise ValueError("OPENAI_API_KEY environment variable not set") return OpenAI(api_key=api_key) def get_brandfetch_logo(domain): """Try to fetch a logo URL from Brandfetch CDN.""" print(f"🔍 Generate - Versuche Brandfetch für Domain: {domain}") # Direct CDN URL construction - Brandfetch provides logos via cdn.brandfetch.io logo_url = f"https://cdn.brandfetch.io/{domain}/logo?c=1idyd4Tpb2nKaXIIc8T" # if validate_logo_url(logo_url): print(f"✅ Generate - Brandfetch Logo gefunden: {logo_url}") return logo_url # return None def search_customer_logo(customer_name): print(f"✅ Generate - Suche nach Kundenlogo für: {customer_name}") """Search for customer logo URL using OpenAI and web search""" try: client = get_openai_client() response = client.chat.completions.create( model="gpt-4", messages=[ { "role": "system", "content": """Du bist ein Experte für die Suche nach Domain Namen. Du findest anhand des Firmennamens die richtige Domain dazu Gib nur den Domain Namen zurück, keine weiteren Informationen. FALLBACK: Wenn du kein direkt Aufrufbare Domain findest, antworte mit "FALLBACK".""" }, { "role": "user", "content": f"Finde die Domain für dasUnternehmen: {customer_name}" } ], temperature=0.1, max_tokens=100 ) logo_url = response.choices[0].message.content.strip() print (f"🔍 OpenAI Logo-URL: {logo_url}") if logo_url.upper() == "FALLBACK": logo_url = None if logo_url: brandfetch_url = get_brandfetch_logo(logo_url) if brandfetch_url: return brandfetch_url return None except Exception as e: print(f"❌ Logo search error: {e}") return None def generate_welcome_html(customer_names, logo_urls, site="stuttgart"): site_display = site.capitalize() names_str = ", ".join(customer_names) if customer_names else "Unbekannt" print(f"✅ Generate - Willkommensseite wird generiert für: {names_str} (site: {site})") site_display = site.capitalize() cancom_svg = '''''' logo_html = "" for i, (name, url) in enumerate(zip(customer_names, logo_urls)): if url: logo_html += f'''
''' html_content = f""" Willkommen bei CANCOM
meets
{logo_html}
Herzlich Willkommen
in unserer
Niederlassung {site_display}!
""" return html_content def save_welcome_page(customer_names, logo_urls, site="stuttgart"): """Save welcome page and return filename""" try: welcome_dir = os.path.join(MEDIA_DIR, site, "lobby") os.makedirs(welcome_dir, exist_ok=True) filepath = os.path.join(os.path.abspath(welcome_dir), WELCOME_FILENAME) html_content = generate_welcome_html(customer_names, logo_urls, site=site) with open(filepath, "w", encoding="utf-8") as f: f.write(html_content) if os.path.getsize(filepath) == 0: raise IOError("File not written") names_str = ", ".join(customer_names) print(f"✅ Generate - Willkommensseite generiert für: {names_str} (site: {site})") print(f"✅ Generate - Willkommensseite gespeichert in: {filepath}") return WELCOME_FILENAME except Exception as e: print(f"❌ Error saving welcome page: {e}") return None def add_customer_to_lobby_playlist(html_filename, site="stuttgart"): """Add customer welcome page to lobby playlist for a specific site""" try: # Import here to avoid circular imports from app import load_config, save_config config = load_config() sites_cfg = config.setdefault("sites", {}) site_cfg = sites_cfg.setdefault(site, {"screens": {}}) screens = site_cfg.setdefault("screens", {}) lobby = screens.setdefault("lobby", {}) playlist = lobby.setdefault("playlist", []) full_filename = f"{html_filename}" playlist[:] = [ item for item in playlist if not ( (isinstance(item, str) and item == full_filename) or (isinstance(item, dict) and item.get("name") == full_filename) ) ] playlist.insert(0, full_filename) save_config(config) print(f"✅ Generate - Willkommensseite in Lobby-Playliste platziert (site: {site})") return True except Exception as e: print(f"❌ Generate - Error adding to playlist: {e}") return False