Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,34 +1,22 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
-
from fastapi import FastAPI, HTTPException
|
3 |
-
from pydantic import BaseModel
|
4 |
import json
|
5 |
import time
|
6 |
-
from
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
# Request/Response models
|
12 |
-
class QuizRequest(BaseModel):
|
13 |
-
tema: str
|
14 |
-
språk: Literal["no", "en"] = "no"
|
15 |
-
antall_spørsmål: int = 5
|
16 |
-
type: Literal["sted", "rute"] = "sted"
|
17 |
-
vanskelighetsgrad: int = 3
|
18 |
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
forklaring: str
|
24 |
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
metadata: dict
|
29 |
-
message: str
|
30 |
|
31 |
-
# Hardkodede spørsmål
|
32 |
QUIZ_DATABASE = {
|
33 |
"oslo": [
|
34 |
{
|
@@ -74,66 +62,107 @@ QUIZ_DATABASE = {
|
|
74 |
]
|
75 |
}
|
76 |
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
elif "bergen" in tema_lower:
|
86 |
-
questions = QUIZ_DATABASE["bergen"]
|
87 |
-
elif "historie" in tema_lower:
|
88 |
-
questions = QUIZ_DATABASE["norsk historie"]
|
89 |
-
else:
|
90 |
-
questions = QUIZ_DATABASE["oslo"]
|
91 |
-
|
92 |
-
return questions[:antall]
|
93 |
|
94 |
-
#
|
95 |
-
|
96 |
-
|
97 |
-
|
|
|
|
|
|
|
98 |
|
|
|
99 |
@app.get("/health")
|
100 |
-
async def
|
101 |
-
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
-
@app.post("/generate-quiz"
|
104 |
-
async def
|
105 |
-
|
|
|
|
|
|
|
106 |
try:
|
107 |
-
|
108 |
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
|
|
|
|
118 |
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
125 |
|
126 |
except Exception as e:
|
127 |
-
raise HTTPException(
|
|
|
|
|
|
|
128 |
|
129 |
-
# Gradio interface
|
130 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
try:
|
132 |
-
|
133 |
|
134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
135 |
|
136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
137 |
output += f"📝 **Spørsmål {i}:** {q['spørsmål']}\n"
|
138 |
for j, alt in enumerate(q['alternativer']):
|
139 |
marker = "✅" if j == q['korrekt_svar'] else "❌"
|
@@ -143,28 +172,55 @@ def generate_quiz_gradio(tema, språk, antall, type_val, vanskelighet):
|
|
143 |
return output
|
144 |
|
145 |
except Exception as e:
|
146 |
-
return f"❌ Feil
|
147 |
|
148 |
-
|
149 |
-
|
|
|
|
|
150 |
|
151 |
with gr.Row():
|
152 |
with gr.Column():
|
153 |
-
tema_input = gr.Textbox(
|
154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
155 |
generate_btn = gr.Button("🚀 Generer Quiz", variant="primary")
|
156 |
|
157 |
with gr.Column():
|
158 |
-
output = gr.Textbox(
|
|
|
|
|
|
|
|
|
159 |
|
160 |
generate_btn.click(
|
161 |
-
fn=
|
162 |
-
inputs=[tema_input,
|
163 |
outputs=output
|
164 |
)
|
|
|
|
|
|
|
|
|
165 |
|
|
|
166 |
app = gr.mount_gradio_app(app, demo, path="/")
|
167 |
|
168 |
if __name__ == "__main__":
|
169 |
import uvicorn
|
170 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
1 |
+
import os
|
2 |
import gradio as gr
|
|
|
|
|
3 |
import json
|
4 |
import time
|
5 |
+
from fastapi import FastAPI, HTTPException, Depends, Header
|
6 |
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
7 |
+
from pydantic import BaseModel
|
8 |
+
from typing import Optional
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
+
# Hent API-nøkkel fra miljøvariabler
|
11 |
+
API_KEY = os.getenv("SOACTI_API_KEY")
|
12 |
+
if not API_KEY:
|
13 |
+
raise ValueError("SOACTI_API_KEY miljøvariabel er ikke satt!")
|
|
|
14 |
|
15 |
+
# FastAPI app
|
16 |
+
app = FastAPI(title="SoActi AI Quiz API - Secure")
|
17 |
+
security = HTTPBearer()
|
|
|
|
|
18 |
|
19 |
+
# Hardkodede spørsmål (samme som før)
|
20 |
QUIZ_DATABASE = {
|
21 |
"oslo": [
|
22 |
{
|
|
|
62 |
]
|
63 |
}
|
64 |
|
65 |
+
# API-nøkkel validering
|
66 |
+
async def verify_api_key(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
67 |
+
if credentials.credentials != API_KEY:
|
68 |
+
raise HTTPException(
|
69 |
+
status_code=401,
|
70 |
+
detail="Ugyldig API-nøkkel"
|
71 |
+
)
|
72 |
+
return credentials.credentials
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
|
74 |
+
# Pydantic modeller
|
75 |
+
class QuizRequest(BaseModel):
|
76 |
+
tema: str
|
77 |
+
språk: str = "no"
|
78 |
+
antall_spørsmål: int = 5
|
79 |
+
type: str = "multiple_choice"
|
80 |
+
vanskelighetsgrad: int = 3
|
81 |
|
82 |
+
# API endepunkter
|
83 |
@app.get("/health")
|
84 |
+
async def health_check():
|
85 |
+
"""Offentlig health check"""
|
86 |
+
return {
|
87 |
+
"status": "healthy",
|
88 |
+
"service": "SoActi AI Quiz API",
|
89 |
+
"auth_required": True
|
90 |
+
}
|
91 |
|
92 |
+
@app.post("/generate-quiz")
|
93 |
+
async def generate_quiz_secure(
|
94 |
+
request: QuizRequest,
|
95 |
+
api_key: str = Depends(verify_api_key)
|
96 |
+
):
|
97 |
+
"""Sikret quiz-generering - krever API-nøkkel"""
|
98 |
try:
|
99 |
+
tema_lower = request.tema.lower().strip()
|
100 |
|
101 |
+
# Finn riktige spørsmål
|
102 |
+
if tema_lower in QUIZ_DATABASE:
|
103 |
+
questions = QUIZ_DATABASE[tema_lower]
|
104 |
+
elif "oslo" in tema_lower:
|
105 |
+
questions = QUIZ_DATABASE["oslo"]
|
106 |
+
elif "bergen" in tema_lower:
|
107 |
+
questions = QUIZ_DATABASE["bergen"]
|
108 |
+
elif "historie" in tema_lower:
|
109 |
+
questions = QUIZ_DATABASE["norsk historie"]
|
110 |
+
else:
|
111 |
+
questions = QUIZ_DATABASE["oslo"]
|
112 |
|
113 |
+
# Begrens antall spørsmål
|
114 |
+
selected_questions = questions[:request.antall_spørsmål]
|
115 |
+
|
116 |
+
return {
|
117 |
+
"success": True,
|
118 |
+
"questions": selected_questions,
|
119 |
+
"metadata": {
|
120 |
+
"tema": request.tema,
|
121 |
+
"språk": request.språk,
|
122 |
+
"antall_generert": len(selected_questions),
|
123 |
+
"model_used": "Fallback Database",
|
124 |
+
"generation_time": 0.1,
|
125 |
+
"auth_verified": True
|
126 |
+
}
|
127 |
+
}
|
128 |
|
129 |
except Exception as e:
|
130 |
+
raise HTTPException(
|
131 |
+
status_code=500,
|
132 |
+
detail=f"Feil ved quiz-generering: {str(e)}"
|
133 |
+
)
|
134 |
|
135 |
+
# Gradio interface (kun for testing)
|
136 |
+
def generate_quiz_ui(tema, antall, api_key_input):
|
137 |
+
"""Gradio wrapper med API-nøkkel input"""
|
138 |
+
if not api_key_input:
|
139 |
+
return "❌ API-nøkkel er påkrevd"
|
140 |
+
|
141 |
+
if api_key_input != API_KEY:
|
142 |
+
return "❌ Ugyldig API-nøkkel"
|
143 |
+
|
144 |
try:
|
145 |
+
tema_lower = tema.lower().strip()
|
146 |
|
147 |
+
if tema_lower in QUIZ_DATABASE:
|
148 |
+
questions = QUIZ_DATABASE[tema_lower]
|
149 |
+
elif "oslo" in tema_lower:
|
150 |
+
questions = QUIZ_DATABASE["oslo"]
|
151 |
+
elif "bergen" in tema_lower:
|
152 |
+
questions = QUIZ_DATABASE["bergen"]
|
153 |
+
elif "historie" in tema_lower:
|
154 |
+
questions = QUIZ_DATABASE["norsk historie"]
|
155 |
+
else:
|
156 |
+
questions = QUIZ_DATABASE["oslo"]
|
157 |
|
158 |
+
selected_questions = questions[:antall]
|
159 |
+
|
160 |
+
output = f"✅ **Genererte {len(selected_questions)} spørsmål om '{tema}'**\n\n"
|
161 |
+
output += f"🔐 **Autentisert:** Ja\n"
|
162 |
+
output += f"🤖 **Modell:** Fallback Database\n"
|
163 |
+
output += f"⏱️ **Tid:** 0.1s\n\n"
|
164 |
+
|
165 |
+
for i, q in enumerate(selected_questions, 1):
|
166 |
output += f"📝 **Spørsmål {i}:** {q['spørsmål']}\n"
|
167 |
for j, alt in enumerate(q['alternativer']):
|
168 |
marker = "✅" if j == q['korrekt_svar'] else "❌"
|
|
|
172 |
return output
|
173 |
|
174 |
except Exception as e:
|
175 |
+
return f"❌ **Feil:** {str(e)}"
|
176 |
|
177 |
+
# Gradio interface
|
178 |
+
with gr.Blocks(title="SoActi AI Quiz API - Secure") as demo:
|
179 |
+
gr.Markdown("# 🔐 SoActi AI Quiz API - Sikker Versjon")
|
180 |
+
gr.Markdown("**API krever nå autentisering med Bearer token**")
|
181 |
|
182 |
with gr.Row():
|
183 |
with gr.Column():
|
184 |
+
tema_input = gr.Textbox(
|
185 |
+
label="Tema",
|
186 |
+
value="Oslo",
|
187 |
+
placeholder="Oslo, Bergen, Norsk historie"
|
188 |
+
)
|
189 |
+
antall_input = gr.Slider(
|
190 |
+
minimum=1,
|
191 |
+
maximum=5,
|
192 |
+
step=1,
|
193 |
+
label="Antall spørsmål",
|
194 |
+
value=3
|
195 |
+
)
|
196 |
+
api_key_input = gr.Textbox(
|
197 |
+
label="API-nøkkel (for testing)",
|
198 |
+
type="password",
|
199 |
+
placeholder="Skriv inn API-nøkkel..."
|
200 |
+
)
|
201 |
+
|
202 |
generate_btn = gr.Button("🚀 Generer Quiz", variant="primary")
|
203 |
|
204 |
with gr.Column():
|
205 |
+
output = gr.Textbox(
|
206 |
+
label="Generert Quiz",
|
207 |
+
lines=20,
|
208 |
+
placeholder="Skriv inn API-nøkkel og klikk 'Generer Quiz'..."
|
209 |
+
)
|
210 |
|
211 |
generate_btn.click(
|
212 |
+
fn=generate_quiz_ui,
|
213 |
+
inputs=[tema_input, antall_input, api_key_input],
|
214 |
outputs=output
|
215 |
)
|
216 |
+
|
217 |
+
gr.Markdown("## 🔗 API Endepunkt")
|
218 |
+
gr.Markdown("`POST https://Soacti-soacti-ai-quiz-api.hf.space/generate-quiz`")
|
219 |
+
gr.Markdown("**Header:** `Authorization: Bearer [din-api-nøkkel]`")
|
220 |
|
221 |
+
# Mount Gradio til FastAPI
|
222 |
app = gr.mount_gradio_app(app, demo, path="/")
|
223 |
|
224 |
if __name__ == "__main__":
|
225 |
import uvicorn
|
226 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|