julzrios commited on
Commit
2fb1426
·
verified ·
1 Parent(s): 9c37319

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -100
app.py CHANGED
@@ -1,122 +1,54 @@
1
- """
2
- mAIseums Chatbot - Gradio + JSON RAG + Eve Personality 3.0
3
- World's First Cultural Deep AI
4
- """
5
  import gradio as gr
6
  import os
7
  import requests
8
  import json
9
 
10
- # Load Eve's personality from JSON
11
- with open("eve_personality.json", "r", encoding="utf-8") as f:
12
- EVE_PERSONALITY = json.load(f)
13
-
14
- # Get OpenRouter API key
15
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
16
  if not OPENROUTER_API_KEY:
17
- raise ValueError("Missing OPENROUTER_API_KEY in Secrets")
18
 
19
- # Load cultural masterpieces
20
- def load_masterpieces():
21
- if os.path.exists("masterpieces.json"):
22
- with open("masterpieces.json", "r", encoding="utf-8") as f:
23
- return json.load(f)
24
- return []
25
-
26
- DOCUMENTS = load_masterpieces()
27
  print(f"✅ Loaded {len(DOCUMENTS)} masterpieces.")
28
 
29
- def retrieve_context(query, top_k=2):
30
- """Safe retrieval with numeric sorting only"""
31
- query_lower = query.lower().strip()
32
  scored = []
33
  for doc in DOCUMENTS:
34
- try:
35
- content = doc.get("content", "") or ""
36
- title = doc.get("title", "") or ""
37
- score = content.lower().count(query_lower) + title.lower().count(query_lower)
38
- if score > 0:
39
- scored.append((score, doc))
40
- except:
41
- continue
42
- # FIX: Sort by numeric score only
43
- scored.sort(key=lambda x: x[0], reverse=True)
44
- return [doc for score, doc in scored[:top_k]]
45
 
46
  def chat_with_eve(message, history):
47
- try:
48
- if not message.strip():
49
- return "Please enter a message!"
50
-
51
- context_docs = retrieve_context(message)
52
- if context_docs:
53
- context_text = "\n\n".join([
54
- f"Source: {doc['source']}\nTitle: {doc['title']}\nContent: {doc['content']}"
55
- for doc in context_docs
56
- ])
57
- else:
58
- context_text = "No relevant information found in cultural archives."
59
-
60
- # Build prompt using Eve's personality
61
- system_prompt = f"""
62
- You are {EVE_PERSONALITY["identity"]["name"]}, {EVE_PERSONALITY["identity"]["title"]}.
63
-
64
- Your voice blends:
65
- {' - '.join(EVE_PERSONALITY["voice"]["core_blend"])}
66
-
67
- Rules:
68
- {' '.join(EVE_PERSONALITY["behavior"]["rules"])}
69
-
70
- Response structure:
71
- {EVE_PERSONALITY["behavior"]["response_structure"]["opening"]}
72
- {EVE_PERSONALITY["behavior"]["response_structure"]["body"]}
73
- {EVE_PERSONALITY["behavior"]["response_structure"]["closing"]}
74
 
75
  Context:
76
- {context_text}
77
  """
78
 
79
- response = requests.post(
80
- "https://openrouter.ai/api/v1/chat/completions",
81
- headers={
82
- "Authorization": f"Bearer {OPENROUTER_API_KEY}",
83
- "Content-Type": "application/json",
84
- "HTTP-Referer": "https://huggingface.co/spaces/julzrios/maiseums-final",
85
- "X-Title": "mAIseums ChatBot"
86
- },
87
- json={
88
- "model": "qwen/qwen3-30b-a3b",
89
- "messages": [
90
- {"role": "system", "content": system_prompt},
91
- {"role": "user", "content": message}
92
- ],
93
- "temperature": 0.7,
94
- "max_tokens": 1024
95
- },
96
- timeout=30
97
- )
98
-
99
- if response.status_code == 200:
100
- return response.json()["choices"][0]["message"]["content"]
101
- else:
102
- return "I'm having trouble connecting right now. Please try again in a moment."
103
-
104
- except Exception as e:
105
- return f"Something went wrong. Would you like to try rephrasing your question?"
106
 
107
- # Gradio interface
108
  demo = gr.ChatInterface(
109
  fn=chat_with_eve,
110
- title="🏛️ mAIseums - Meet Eve, Your Cultural Deep AI",
111
- description="Ask me about art, history, and cultural heritage.",
112
- examples=[
113
- "Tell me about Las Meninas",
114
- "What is the Rosetta Stone?",
115
- "Show me The Night Watch",
116
- "Tell me about Habitant Interior from Québec",
117
- "Compare Mona Lisa and Las Meninas"
118
- ]
119
  )
120
-
121
- if __name__ == "__main__":
122
- demo.launch()
 
 
 
 
 
1
  import gradio as gr
2
  import os
3
  import requests
4
  import json
5
 
 
 
 
 
 
6
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
7
  if not OPENROUTER_API_KEY:
8
+ raise ValueError("Missing OPENROUTER_API_KEY")
9
 
10
+ # Load ONLY masterpieces.json
11
+ with open("masterpieces.json", "r") as f:
12
+ DOCUMENTS = json.load(f)
 
 
 
 
 
13
  print(f"✅ Loaded {len(DOCUMENTS)} masterpieces.")
14
 
15
+ def retrieve_context(query):
16
+ query = query.lower()
 
17
  scored = []
18
  for doc in DOCUMENTS:
19
+ score = doc["content"].lower().count(query) + doc["title"].lower().count(query)
20
+ scored.append((score, doc))
21
+ scored.sort(key=lambda x: x[0], reverse=True) # FIX: sort by number
22
+ return [doc for score, doc in scored[:2]]
 
 
 
 
 
 
 
23
 
24
  def chat_with_eve(message, history):
25
+ context_docs = retrieve_context(message)
26
+ context = "\n\n".join([
27
+ f"Source: {doc['source']}\nTitle: {doc['title']}\nContent: {doc['content']}"
28
+ for doc in context_docs
29
+ ]) if context_docs else "No relevant information found."
30
+
31
+ system_prompt = f"""
32
+ You are Eve, the Digital Curator of mAIseums.
33
+ NEVER hallucinate. If the context doesn’t contain the answer, say:
34
+ “That fragment has not yet been revealed in the archives of cultural memory.”
35
+ Use ONLY the context below.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  Context:
38
+ {context}
39
  """
40
 
41
+ response = requests.post(
42
+ "https://openrouter.ai/api/v1/chat/completions",
43
+ headers={"Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json"},
44
+ json={"model": "qwen/qwen3-30b-a3b", "messages": [{"role": "system", "content": system_prompt}, {"role": "user", "content": message}]},
45
+ timeout=30
46
+ )
47
+ return response.json()["choices"][0]["message"]["content"] if response.status_code == 200 else "Error."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
 
49
  demo = gr.ChatInterface(
50
  fn=chat_with_eve,
51
+ title=" TEST: Masterpieces Only",
52
+ examples=["Tell me about Las Meninas", "What is the Rosetta Stone?"]
 
 
 
 
 
 
 
53
  )
54
+ demo.launch()