Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import requests
|
| 3 |
import json
|
|
@@ -7,11 +11,8 @@ import base64
|
|
| 7 |
import pandas as pd
|
| 8 |
import zipfile
|
| 9 |
import PyPDF2
|
| 10 |
-
import os
|
| 11 |
|
| 12 |
# --- Konfiguration ---
|
| 13 |
-
# ACHTUNG: Der 'PermissionError' tritt bei Streamlit-Initialisierung auf.
|
| 14 |
-
# Ein Code-Fix kann das Problem nur umgehen, nicht beheben.
|
| 15 |
st.set_page_config(page_title="OpenRouter Free Interface", layout="wide", initial_sidebar_state="expanded")
|
| 16 |
OPENROUTER_API_BASE = "https://openrouter.ai/api/v1"
|
| 17 |
|
|
@@ -20,6 +21,7 @@ st.title("💸 OpenRouter Free-Tier Interface")
|
|
| 20 |
st.markdown("""
|
| 21 |
**Willkommen im All-OpenRouter-Free-Interface Deluxe!**
|
| 22 |
Chatte mit **kostenlosen (Free-Tier)** Modellen über die OpenRouter API.
|
|
|
|
| 23 |
""")
|
| 24 |
|
| 25 |
# --- Session State Management ---
|
|
@@ -28,18 +30,21 @@ if "messages" not in st.session_state:
|
|
| 28 |
if "uploaded_content" not in st.session_state:
|
| 29 |
st.session_state.uploaded_content = None
|
| 30 |
|
| 31 |
-
|
|
|
|
| 32 |
def encode_image(image):
|
| 33 |
buf = io.BytesIO()
|
| 34 |
image.save(buf, format="JPEG")
|
| 35 |
return base64.b64encode(buf.getvalue()).decode("utf-8")
|
| 36 |
|
|
|
|
| 37 |
def process_file(uploaded_file):
|
| 38 |
file_type = uploaded_file.name.split('.')[-1].lower()
|
| 39 |
text_exts = ('.txt', '.csv', '.py', '.html', '.js', '.css', '.json', '.xml', '.sql', '.xlsx')
|
| 40 |
-
|
| 41 |
if file_type in ["jpg", "jpeg", "png"]:
|
| 42 |
return {"type": "image", "content": Image.open(uploaded_file).convert('RGB')}
|
|
|
|
| 43 |
if file_type in ["txt"] + [ext.strip('.') for ext in text_exts if ext not in ('.csv', '.xlsx')]:
|
| 44 |
return {"type": "text", "content": uploaded_file.read().decode("utf-8", errors="ignore")}
|
| 45 |
if file_type in ["csv", "xlsx"]:
|
|
@@ -67,9 +72,10 @@ def process_file(uploaded_file):
|
|
| 67 |
return {"type": "error", "content": f"ZIP Fehler: {e}"}
|
| 68 |
return {"type": "error", "content": "Nicht unterstütztes Dateiformat."}
|
| 69 |
|
| 70 |
-
|
|
|
|
| 71 |
def fetch_model_contexts(api_key):
|
| 72 |
-
"""Lädt alle Modelle + deren context_length.
|
| 73 |
if not api_key:
|
| 74 |
return {}
|
| 75 |
headers = {"Authorization": f"Bearer {api_key}"}
|
|
@@ -83,7 +89,6 @@ def fetch_model_contexts(api_key):
|
|
| 83 |
contexts[mid] = ctx
|
| 84 |
return contexts
|
| 85 |
except Exception as e:
|
| 86 |
-
# st.warning weggelassen, um Render-Loop-Probleme zu vermeiden
|
| 87 |
return {}
|
| 88 |
|
| 89 |
|
|
@@ -103,10 +108,7 @@ with st.sidebar:
|
|
| 103 |
|
| 104 |
model = st.selectbox("Wähle ein Modell", FREE_MODEL_LIST, index=0)
|
| 105 |
|
| 106 |
-
# 🔑 WICHTIG: Context-Länge holen ABER mit Fallback
|
| 107 |
-
# Der Aufruf erfolgt jetzt nur einmal, wenn die Sidebar geladen wird
|
| 108 |
model_contexts = fetch_model_contexts(api_key)
|
| 109 |
-
# Verwende 4096 als stabilen Fallback, wenn der API-Key fehlt oder der Fetch fehlschlägt
|
| 110 |
default_ctx = model_contexts.get(model, 4096)
|
| 111 |
|
| 112 |
temperature = st.slider("Temperature", 0.0, 1.0, 0.7)
|
|
@@ -127,18 +129,16 @@ with st.sidebar:
|
|
| 127 |
|
| 128 |
st.markdown("""
|
| 129 |
---
|
| 130 |
-
🧠 **Hinweis:**
|
| 131 |
""")
|
| 132 |
|
| 133 |
|
| 134 |
-
# --- Datei Upload & Preview Logik
|
| 135 |
uploaded_file = st.file_uploader("Upload File (optional)",
|
| 136 |
type=["jpg", "jpeg", "png", "txt", "pdf", "zip", "csv", "xlsx", "html", "css", "js", "py"])
|
| 137 |
|
| 138 |
-
# Logik wie in der Gemini UI: Nur verarbeiten, wenn eine neue Datei hochgeladen wird und KEIN Inhalt im State ist
|
| 139 |
if uploaded_file and st.session_state.uploaded_content is None:
|
| 140 |
st.session_state.uploaded_content = process_file(uploaded_file)
|
| 141 |
-
# KEIN st.experimental_rerun() hier.
|
| 142 |
|
| 143 |
if st.session_state.uploaded_content:
|
| 144 |
processed = st.session_state.uploaded_content
|
|
@@ -155,13 +155,12 @@ if st.session_state.uploaded_content:
|
|
| 155 |
st.experimental_rerun()
|
| 156 |
|
| 157 |
|
| 158 |
-
# --- Chat Verlauf anzeigen & API Call
|
| 159 |
for msg in st.session_state.messages:
|
| 160 |
with st.chat_message(msg["role"]):
|
| 161 |
st.markdown(msg["content"])
|
| 162 |
|
| 163 |
def call_openrouter(model, messages, temp, max_tok, key):
|
| 164 |
-
# ... (API Call Funktion)
|
| 165 |
headers = {
|
| 166 |
"Authorization": f"Bearer {key}",
|
| 167 |
"Content-Type": "application/json",
|
|
@@ -174,7 +173,7 @@ def call_openrouter(model, messages, temp, max_tok, key):
|
|
| 174 |
"temperature": temp,
|
| 175 |
"max_tokens": max_tok,
|
| 176 |
}
|
| 177 |
-
|
| 178 |
res = requests.post(f"{OPENROUTER_API_BASE}/chat/completions", headers=headers, data=json.dumps(payload))
|
| 179 |
if res.status_code == 200:
|
| 180 |
try:
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
# Setze die Umgebungsvariable, BEVOR streamlit initialisiert wird (Muss ganz oben stehen!)
|
| 3 |
+
os.environ["STREAMLIT_GATHER_USAGE_STATS"] = "false"
|
| 4 |
+
|
| 5 |
import streamlit as st
|
| 6 |
import requests
|
| 7 |
import json
|
|
|
|
| 11 |
import pandas as pd
|
| 12 |
import zipfile
|
| 13 |
import PyPDF2
|
|
|
|
| 14 |
|
| 15 |
# --- Konfiguration ---
|
|
|
|
|
|
|
| 16 |
st.set_page_config(page_title="OpenRouter Free Interface", layout="wide", initial_sidebar_state="expanded")
|
| 17 |
OPENROUTER_API_BASE = "https://openrouter.ai/api/v1"
|
| 18 |
|
|
|
|
| 21 |
st.markdown("""
|
| 22 |
**Willkommen im All-OpenRouter-Free-Interface Deluxe!**
|
| 23 |
Chatte mit **kostenlosen (Free-Tier)** Modellen über die OpenRouter API.
|
| 24 |
+
Alle Modelle unterliegen den OpenRouter-Ratenbegrenzungen.
|
| 25 |
""")
|
| 26 |
|
| 27 |
# --- Session State Management ---
|
|
|
|
| 30 |
if "uploaded_content" not in st.session_state:
|
| 31 |
st.session_state.uploaded_content = None
|
| 32 |
|
| 33 |
+
|
| 34 |
+
# --- Datei-Verarbeitung ---
|
| 35 |
def encode_image(image):
|
| 36 |
buf = io.BytesIO()
|
| 37 |
image.save(buf, format="JPEG")
|
| 38 |
return base64.b64encode(buf.getvalue()).decode("utf-8")
|
| 39 |
|
| 40 |
+
|
| 41 |
def process_file(uploaded_file):
|
| 42 |
file_type = uploaded_file.name.split('.')[-1].lower()
|
| 43 |
text_exts = ('.txt', '.csv', '.py', '.html', '.js', '.css', '.json', '.xml', '.sql', '.xlsx')
|
| 44 |
+
|
| 45 |
if file_type in ["jpg", "jpeg", "png"]:
|
| 46 |
return {"type": "image", "content": Image.open(uploaded_file).convert('RGB')}
|
| 47 |
+
# ... (Rest der process_file Funktion, unverändert)
|
| 48 |
if file_type in ["txt"] + [ext.strip('.') for ext in text_exts if ext not in ('.csv', '.xlsx')]:
|
| 49 |
return {"type": "text", "content": uploaded_file.read().decode("utf-8", errors="ignore")}
|
| 50 |
if file_type in ["csv", "xlsx"]:
|
|
|
|
| 72 |
return {"type": "error", "content": f"ZIP Fehler: {e}"}
|
| 73 |
return {"type": "error", "content": "Nicht unterstütztes Dateiformat."}
|
| 74 |
|
| 75 |
+
|
| 76 |
+
# --- Context-Length Fetch (Ohne Caching für maximale Kompatibilität) ---
|
| 77 |
def fetch_model_contexts(api_key):
|
| 78 |
+
"""Lädt alle Modelle + deren context_length."""
|
| 79 |
if not api_key:
|
| 80 |
return {}
|
| 81 |
headers = {"Authorization": f"Bearer {api_key}"}
|
|
|
|
| 89 |
contexts[mid] = ctx
|
| 90 |
return contexts
|
| 91 |
except Exception as e:
|
|
|
|
| 92 |
return {}
|
| 93 |
|
| 94 |
|
|
|
|
| 108 |
|
| 109 |
model = st.selectbox("Wähle ein Modell", FREE_MODEL_LIST, index=0)
|
| 110 |
|
|
|
|
|
|
|
| 111 |
model_contexts = fetch_model_contexts(api_key)
|
|
|
|
| 112 |
default_ctx = model_contexts.get(model, 4096)
|
| 113 |
|
| 114 |
temperature = st.slider("Temperature", 0.0, 1.0, 0.7)
|
|
|
|
| 129 |
|
| 130 |
st.markdown("""
|
| 131 |
---
|
| 132 |
+
🧠 **Hinweis:** Dies umgeht den Schreibfehler in Umgebungen wie Hugging Face Spaces.
|
| 133 |
""")
|
| 134 |
|
| 135 |
|
| 136 |
+
# --- Datei Upload & Preview Logik ---
|
| 137 |
uploaded_file = st.file_uploader("Upload File (optional)",
|
| 138 |
type=["jpg", "jpeg", "png", "txt", "pdf", "zip", "csv", "xlsx", "html", "css", "js", "py"])
|
| 139 |
|
|
|
|
| 140 |
if uploaded_file and st.session_state.uploaded_content is None:
|
| 141 |
st.session_state.uploaded_content = process_file(uploaded_file)
|
|
|
|
| 142 |
|
| 143 |
if st.session_state.uploaded_content:
|
| 144 |
processed = st.session_state.uploaded_content
|
|
|
|
| 155 |
st.experimental_rerun()
|
| 156 |
|
| 157 |
|
| 158 |
+
# --- Chat Verlauf anzeigen & API Call ---
|
| 159 |
for msg in st.session_state.messages:
|
| 160 |
with st.chat_message(msg["role"]):
|
| 161 |
st.markdown(msg["content"])
|
| 162 |
|
| 163 |
def call_openrouter(model, messages, temp, max_tok, key):
|
|
|
|
| 164 |
headers = {
|
| 165 |
"Authorization": f"Bearer {key}",
|
| 166 |
"Content-Type": "application/json",
|
|
|
|
| 173 |
"temperature": temp,
|
| 174 |
"max_tokens": max_tok,
|
| 175 |
}
|
| 176 |
+
# ... (Rest des API Calls)
|
| 177 |
res = requests.post(f"{OPENROUTER_API_BASE}/chat/completions", headers=headers, data=json.dumps(payload))
|
| 178 |
if res.status_code == 200:
|
| 179 |
try:
|