Spaces:
Running
Running
QalamHipHop commited on
Commit ·
334d32b
1
Parent(s): ad5656b
Fix build error and consolidate project: restored all algorithms and goals
Browse files- Dockerfile +5 -17
- app.py +255 -82
- requirements.txt +4 -34
Dockerfile
CHANGED
|
@@ -1,22 +1,10 @@
|
|
| 1 |
-
FROM python:3.11
|
| 2 |
|
| 3 |
-
WORKDIR /
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
curl \
|
| 8 |
-
software-properties-common \
|
| 9 |
-
git \
|
| 10 |
-
&& rm -rf /var/lib/apt/lists/*
|
| 11 |
-
|
| 12 |
-
COPY requirements_enhanced.txt .
|
| 13 |
-
RUN pip3 install --no-cache-dir -r requirements_enhanced.txt
|
| 14 |
|
| 15 |
COPY . .
|
| 16 |
|
| 17 |
-
|
| 18 |
-
EXPOSE 8000
|
| 19 |
-
EXPOSE 7860
|
| 20 |
-
|
| 21 |
-
# Command to run the Gradio UI by default
|
| 22 |
-
CMD ["python3", "app_enhanced.py"]
|
|
|
|
| 1 |
+
FROM python:3.11
|
| 2 |
|
| 3 |
+
WORKDIR /code
|
| 4 |
|
| 5 |
+
COPY ./requirements.txt /code/requirements.txt
|
| 6 |
+
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
COPY . .
|
| 9 |
|
| 10 |
+
CMD ["python", "app.py"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app.py
CHANGED
|
@@ -1,89 +1,262 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import httpx
|
| 3 |
import asyncio
|
| 4 |
-
import os
|
| 5 |
import json
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
refresh_btn.click(get_system_status, outputs=status_output)
|
| 66 |
-
|
| 67 |
-
with gr.Column():
|
| 68 |
-
gr.Markdown("### 🚀 Operations")
|
| 69 |
-
cycle_btn = gr.Button("⚡ Trigger Research Cycle", variant="secondary")
|
| 70 |
-
cycle_output = gr.Markdown()
|
| 71 |
-
cycle_btn.click(trigger_cycle, outputs=cycle_output)
|
| 72 |
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
if __name__ == "__main__":
|
| 89 |
-
demo.launch(
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
import asyncio
|
|
|
|
| 3 |
import json
|
| 4 |
+
import hashlib
|
| 5 |
+
import hmac
|
| 6 |
+
import time
|
| 7 |
+
import logging
|
| 8 |
+
import os
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from typing import List, Dict, Any, Optional, Tuple
|
| 11 |
+
from dataclasses import dataclass, asdict, field
|
| 12 |
+
from enum import Enum
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
# Third-party imports
|
| 16 |
+
from openai import AsyncOpenAI
|
| 17 |
+
import numpy as np
|
| 18 |
+
import faiss
|
| 19 |
+
from sentence_transformers import SentenceTransformer, CrossEncoder
|
| 20 |
+
|
| 21 |
+
# Configure logging
|
| 22 |
+
logging.basicConfig(level=logging.INFO)
|
| 23 |
+
logger = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
# ==================== Data Models ====================
|
| 26 |
+
|
| 27 |
+
class ResearchCategory(str, Enum):
|
| 28 |
+
PHYSICS = "physics"
|
| 29 |
+
ENGINEERING = "engineering"
|
| 30 |
+
ECONOMICS = "economics"
|
| 31 |
+
SAFETY = "safety"
|
| 32 |
+
NOVEL_APPLICATIONS = "novel_applications"
|
| 33 |
+
AI_INTEGRATION = "ai_integration"
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class EvaluationScore:
|
| 37 |
+
scientific_accuracy: float
|
| 38 |
+
novelty_score: float
|
| 39 |
+
usefulness_score: float
|
| 40 |
+
self_consistency: float
|
| 41 |
+
overall_score: float
|
| 42 |
+
|
| 43 |
+
def dict(self):
|
| 44 |
+
return asdict(self)
|
| 45 |
+
|
| 46 |
+
@dataclass
|
| 47 |
+
class ResearchQuestion:
|
| 48 |
+
id: str
|
| 49 |
+
question: str
|
| 50 |
+
category: ResearchCategory
|
| 51 |
+
complexity_level: int
|
| 52 |
+
timestamp: datetime
|
| 53 |
+
keywords: List[str] = field(default_factory=list)
|
| 54 |
+
|
| 55 |
+
@dataclass
|
| 56 |
+
class ResearchAnswer:
|
| 57 |
+
id: str
|
| 58 |
+
question_id: str
|
| 59 |
+
answer: str
|
| 60 |
+
sources: List[Dict[str, str]]
|
| 61 |
+
equations: List[str]
|
| 62 |
+
examples: List[str]
|
| 63 |
+
citations: List[str]
|
| 64 |
+
timestamp: datetime
|
| 65 |
+
model_version: str
|
| 66 |
+
evaluation_scores: EvaluationScore
|
| 67 |
+
|
| 68 |
+
# ==================== Blockchain ====================
|
| 69 |
+
|
| 70 |
+
class TransactionType(str, Enum):
|
| 71 |
+
KNOWLEDGE_RECORD = "knowledge_record"
|
| 72 |
+
NES_MINT = "nes_mint"
|
| 73 |
+
NES_TRANSFER = "nes_transfer"
|
| 74 |
+
|
| 75 |
+
@dataclass
|
| 76 |
+
class Transaction:
|
| 77 |
+
tx_id: str
|
| 78 |
+
tx_type: TransactionType
|
| 79 |
+
timestamp: float
|
| 80 |
+
data: Dict[str, Any]
|
| 81 |
+
sender: str
|
| 82 |
+
receiver: str
|
| 83 |
+
amount: float
|
| 84 |
+
nonce: int
|
| 85 |
+
signature: str = ""
|
| 86 |
+
|
| 87 |
+
def to_dict(self):
|
| 88 |
+
return {
|
| 89 |
+
"tx_id": self.tx_id,
|
| 90 |
+
"tx_type": self.tx_type.value,
|
| 91 |
+
"timestamp": self.timestamp,
|
| 92 |
+
"data": self.data,
|
| 93 |
+
"sender": self.sender,
|
| 94 |
+
"receiver": self.receiver,
|
| 95 |
+
"amount": self.amount,
|
| 96 |
+
"nonce": self.nonce,
|
| 97 |
+
"signature": self.signature
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
@dataclass
|
| 101 |
+
class Block:
|
| 102 |
+
block_number: int
|
| 103 |
+
timestamp: float
|
| 104 |
+
transactions: List[Transaction]
|
| 105 |
+
previous_hash: str
|
| 106 |
+
miner: str
|
| 107 |
+
merkle_root: str
|
| 108 |
+
nonce: int = 0
|
| 109 |
+
difficulty: int = 4
|
| 110 |
+
|
| 111 |
+
def calculate_hash(self) -> str:
|
| 112 |
+
block_data = {
|
| 113 |
+
"block_number": self.block_number,
|
| 114 |
+
"timestamp": self.timestamp,
|
| 115 |
+
"transactions": [tx.to_dict() for tx in self.transactions],
|
| 116 |
+
"previous_hash": self.previous_hash,
|
| 117 |
+
"miner": self.miner,
|
| 118 |
+
"merkle_root": self.merkle_root,
|
| 119 |
+
"nonce": self.nonce
|
| 120 |
+
}
|
| 121 |
+
return hashlib.sha256(json.dumps(block_data, sort_keys=True).encode()).hexdigest()
|
| 122 |
+
|
| 123 |
+
def mine_block(self):
|
| 124 |
+
target = "0" * self.difficulty
|
| 125 |
+
while not self.calculate_hash().startswith(target):
|
| 126 |
+
self.nonce += 1
|
| 127 |
+
|
| 128 |
+
class VirtualLedger:
|
| 129 |
+
def __init__(self):
|
| 130 |
+
self.chain: List[Block] = []
|
| 131 |
+
self.pending_transactions: List[Transaction] = []
|
| 132 |
+
self.balances: Dict[str, float] = {"nuclear-intelligence": 1000000.0}
|
| 133 |
+
self._create_genesis_block()
|
| 134 |
+
|
| 135 |
+
def _create_genesis_block(self):
|
| 136 |
+
genesis = Block(0, time.time(), [], "0", "genesis", hashlib.sha256(b"").hexdigest())
|
| 137 |
+
genesis.mine_block()
|
| 138 |
+
self.chain.append(genesis)
|
| 139 |
+
|
| 140 |
+
def add_transaction(self, tx_type, data, sender, receiver, amount=0.0):
|
| 141 |
+
tx_id = hashlib.md5(f"{sender}{receiver}{time.time()}".encode()).hexdigest()[:16]
|
| 142 |
+
tx = Transaction(tx_id, tx_type, time.time(), data, sender, receiver, amount, len(self.pending_transactions))
|
| 143 |
+
self.pending_transactions.append(tx)
|
| 144 |
+
return tx_id
|
| 145 |
+
|
| 146 |
+
def mint_nes_token(self, answer_id, question, answer, evaluation_scores, answer_metadata):
|
| 147 |
+
token_data = {
|
| 148 |
+
"token_type": "NES",
|
| 149 |
+
"token_value": 1.0,
|
| 150 |
+
"answer_id": answer_id,
|
| 151 |
+
"question": question[:500],
|
| 152 |
+
"answer_hash": hashlib.sha256(answer.encode()).hexdigest(),
|
| 153 |
+
"evaluation_scores": evaluation_scores,
|
| 154 |
+
"timestamp": datetime.now().isoformat()
|
| 155 |
+
}
|
| 156 |
+
tx_id = self.add_transaction(TransactionType.NES_MINT, token_data, "nuclear-intelligence", answer_id, 1.0)
|
| 157 |
+
self.balances[answer_id] = self.balances.get(answer_id, 0.0) + 1.0
|
| 158 |
+
return {"tx_id": tx_id, "token_data": token_data}
|
| 159 |
+
|
| 160 |
+
def mine_pending_block(self):
|
| 161 |
+
if not self.pending_transactions: return None
|
| 162 |
+
last_block = self.chain[-1]
|
| 163 |
+
new_block = Block(len(self.chain), time.time(), self.pending_transactions.copy(),
|
| 164 |
+
last_block.calculate_hash(), "nuclear-intelligence", "root")
|
| 165 |
+
new_block.mine_block()
|
| 166 |
+
self.chain.append(new_block)
|
| 167 |
+
self.pending_transactions = []
|
| 168 |
+
return new_block
|
| 169 |
+
|
| 170 |
+
# ==================== Core Intelligence ====================
|
| 171 |
+
|
| 172 |
+
class NuclearIntelligenceCore:
|
| 173 |
+
def __init__(self, api_key):
|
| 174 |
+
self.client = AsyncOpenAI(api_key=api_key)
|
| 175 |
+
self.knowledge_base = {}
|
| 176 |
+
self.embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 177 |
+
self.index = faiss.IndexFlatL2(384)
|
| 178 |
+
self.docs = []
|
| 179 |
+
|
| 180 |
+
async def _call_llm(self, prompt):
|
| 181 |
+
response = await self.client.chat.completions.create(
|
| 182 |
+
model="gpt-4-turbo",
|
| 183 |
+
messages=[{"role": "user", "content": prompt}],
|
| 184 |
+
response_format={"type": "json_object"}
|
| 185 |
+
)
|
| 186 |
+
return response.choices[0].message.content
|
| 187 |
+
|
| 188 |
+
async def generate_complex_questions(self, num=3):
|
| 189 |
+
prompt = f"Generate {num} complex nuclear energy research questions in JSON format: {{'questions': [{{'question': str, 'category': str, 'complexity': int, 'keywords': [str]}}]}}"
|
| 190 |
+
res = await self._call_llm(prompt)
|
| 191 |
+
data = json.loads(res)
|
| 192 |
+
questions = []
|
| 193 |
+
for q in data['questions']:
|
| 194 |
+
questions.append(ResearchQuestion(hashlib.md5(q['question'].encode()).hexdigest()[:12],
|
| 195 |
+
q['question'], ResearchCategory(q.get('category', 'physics')),
|
| 196 |
+
q.get('complexity', 7), datetime.now(), q.get('keywords', [])))
|
| 197 |
+
return questions
|
| 198 |
+
|
| 199 |
+
async def conduct_deep_research(self, question: ResearchQuestion):
|
| 200 |
+
prompt = f"Research this nuclear question: {question.question}. Provide JSON: {{'answer': str, 'sources': [{{'title': str, 'url': str}}], 'equations': [str], 'examples': [str], 'citations': [str]}}"
|
| 201 |
+
res = await self._call_llm(prompt)
|
| 202 |
+
data = json.loads(res)
|
| 203 |
+
return ResearchAnswer(hashlib.md5(f"{question.id}{time.time()}".encode()).hexdigest()[:12],
|
| 204 |
+
question.id, data['answer'], data.get('sources', []), data.get('equations', []),
|
| 205 |
+
data.get('examples', []), data.get('citations', []), datetime.now(), "gpt-4-turbo",
|
| 206 |
+
EvaluationScore(0,0,0,0,0))
|
| 207 |
+
|
| 208 |
+
async def evaluate_answer(self, answer: ResearchAnswer):
|
| 209 |
+
prompt = f"Evaluate this answer: {answer.answer[:1000]}. Provide JSON scores 0-100: {{'scientific_accuracy': int, 'novelty_score': int, 'usefulness_score': int, 'self_consistency': int, 'overall_score': int}}"
|
| 210 |
+
res = await self._call_llm(prompt)
|
| 211 |
+
data = json.loads(res)
|
| 212 |
+
return EvaluationScore(**data)
|
| 213 |
+
|
| 214 |
+
def add_to_knowledge_base(self, answer: ResearchAnswer):
|
| 215 |
+
self.knowledge_base[answer.id] = asdict(answer)
|
| 216 |
+
emb = self.embedding_model.encode(answer.answer).astype('float32')
|
| 217 |
+
self.index.add(np.array([emb]))
|
| 218 |
+
self.docs.append(answer.answer)
|
| 219 |
+
|
| 220 |
+
# ==================== UI ====================
|
| 221 |
+
|
| 222 |
+
core = None
|
| 223 |
+
ledger = VirtualLedger()
|
| 224 |
+
|
| 225 |
+
async def run_cycle(api_key):
|
| 226 |
+
global core
|
| 227 |
+
if not core: core = NuclearIntelligenceCore(api_key)
|
| 228 |
|
| 229 |
+
questions = await core.generate_complex_questions(1)
|
| 230 |
+
results = []
|
| 231 |
+
for q in questions:
|
| 232 |
+
ans = await core.conduct_deep_research(q)
|
| 233 |
+
score = await core.evaluate_answer(ans)
|
| 234 |
+
ans.evaluation_scores = score
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
|
| 236 |
+
if score.scientific_accuracy >= 93:
|
| 237 |
+
mint = ledger.mint_nes_token(ans.id, q.question, ans.answer, score.dict(), asdict(ans))
|
| 238 |
+
core.add_to_knowledge_base(ans)
|
| 239 |
+
results.append(f"✅ Minted NES for: {q.question[:50]}... (Score: {score.overall_score})")
|
| 240 |
+
else:
|
| 241 |
+
results.append(f"❌ Failed Accuracy: {q.question[:50]}... (Score: {score.scientific_accuracy})")
|
| 242 |
+
|
| 243 |
+
ledger.mine_pending_block()
|
| 244 |
+
return "\n".join(results), f"Total NES: {sum(ledger.balances.values()) - 1000000.0}"
|
| 245 |
+
|
| 246 |
+
def ui_run(api_key):
|
| 247 |
+
return asyncio.run(run_cycle(api_key))
|
| 248 |
+
|
| 249 |
+
with gr.Blocks(title="Nuclear Intelligence") as demo:
|
| 250 |
+
gr.Markdown("# ⚛️ Nuclear Intelligence System v2.0")
|
| 251 |
+
with gr.Row():
|
| 252 |
+
key_input = gr.Textbox(label="OpenAI API Key", type="password", value=os.getenv("OPENAI_API_KEY", ""))
|
| 253 |
+
run_btn = gr.Button("Execute Research Cycle")
|
| 254 |
+
|
| 255 |
+
with gr.Row():
|
| 256 |
+
output = gr.Textbox(label="Cycle Output", lines=10)
|
| 257 |
+
stats = gr.Label(label="NES Tokens Minted")
|
| 258 |
+
|
| 259 |
+
run_btn.click(ui_run, inputs=[key_input], outputs=[output, stats])
|
| 260 |
|
| 261 |
if __name__ == "__main__":
|
| 262 |
+
demo.launch()
|
requirements.txt
CHANGED
|
@@ -1,35 +1,5 @@
|
|
| 1 |
-
fastapi==0.104.1
|
| 2 |
-
uvicorn==0.24.0
|
| 3 |
-
pydantic==2.5.0
|
| 4 |
-
python-dotenv==1.0.0
|
| 5 |
-
requests==2.31.0
|
| 6 |
-
aiohttp==3.9.1
|
| 7 |
-
openai==1.3.0
|
| 8 |
-
langchain==0.1.0
|
| 9 |
-
langchain-community==0.0.10
|
| 10 |
-
langchain-openai==0.0.5
|
| 11 |
-
faiss-cpu==1.7.4
|
| 12 |
-
sentence-transformers==2.2.2
|
| 13 |
-
numpy==1.24.3
|
| 14 |
-
pandas==2.1.3
|
| 15 |
-
scikit-learn==1.3.2
|
| 16 |
-
torch==2.1.1
|
| 17 |
-
transformers==4.35.2
|
| 18 |
-
arxiv==1.4.7
|
| 19 |
-
feedparser==6.0.10
|
| 20 |
-
beautifulsoup4==4.12.2
|
| 21 |
-
lxml==4.9.3
|
| 22 |
-
PyYAML==6.0.1
|
| 23 |
-
cryptography==41.0.7
|
| 24 |
-
redis==5.0.1
|
| 25 |
-
psycopg2-binary==2.9.9
|
| 26 |
-
sqlalchemy==2.0.23
|
| 27 |
-
alembic==1.13.0
|
| 28 |
gradio==4.36.1
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
tenacity==8.2.3
|
| 34 |
-
tqdm==4.66.1
|
| 35 |
-
loguru==0.7.2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
gradio==4.36.1
|
| 2 |
+
openai>=1.0.0
|
| 3 |
+
sentence-transformers
|
| 4 |
+
faiss-cpu
|
| 5 |
+
numpy
|
|
|
|
|
|
|
|
|