Leonydis137 commited on
Commit
75b07a4
·
verified ·
1 Parent(s): b6695fe

Upload 5 files

Browse files
Files changed (5) hide show
  1. app.py +30 -122
  2. correction.py +9 -0
  3. diagnostics.py +44 -21
  4. learning.py +9 -0
  5. requirements.txt +2 -7
app.py CHANGED
@@ -1,135 +1,43 @@
1
- from fastapi import FastAPI, HTTPException
2
- from pydantic import BaseModel, constr
3
- import uuid, time, logging, os
4
- from huggingface_hub import hf_hub_download
5
- from ctransformers import AutoModelForCausalLM
6
- import gradio as gr
7
 
8
- # ---------------- Requirements ----------------
9
- # Make sure your requirements.txt includes:
10
- # gradio
11
- # fastapi
12
- # uvicorn
13
- # pydantic
14
- # huggingface_hub
15
- # ctransformers
16
 
17
- # ---------------- Logging ----------------
18
- logging.basicConfig(filename="log.txt", level=logging.INFO)
19
 
20
- # ---------------- Memory ----------------
21
- memory_store = {}
22
- def add_to_memory(session_id, prompt, response):
23
- memory_store.setdefault(session_id, []).append((prompt, response))
24
- def get_memory(session_id):
25
- return memory_store.get(session_id, [])
26
- def get_summary(session_id):
27
- msgs = get_memory(session_id)
28
- if not msgs:
29
- return ""
30
- return "\n".join([f"Q: {q}\nA: {a}" for q, a in msgs[-3:]])
31
 
32
- # ---------------- Download GGUF & Model Loading ----------------
33
- # Defer heavy download/load until first request to speed up startup
34
- model_path = None
35
- llm = None
36
 
37
- def ensure_model_loaded():
38
- global model_path, llm
39
- if llm is not None:
40
- return
41
- # Download GGUF blob
42
- model_path = hf_hub_download(
43
- repo_id="TheBloke/zephyr-7B-alpha-GGUF",
44
- filename="zephyr-7b-alpha.Q4_K_M.gguf",
45
- cache_dir="/mnt/models"
46
- )
47
- print(f"✅ Downloaded GGUF model to: {model_path}")
48
- # Load via ctransformers
49
- llm = AutoModelForCausalLM.from_pretrained(
50
- model_path,
51
- model_type="llama"
52
- )
53
 
54
- # ---------------- Generation Helper ----------------
55
- def generate_text(prompt: str) -> str:
56
- ensure_model_loaded()
57
- return llm.generate(
58
- prompt=prompt,
59
- max_new_tokens=256,
60
- temperature=0.7
61
- )
62
 
63
- # ---------------- FastAPI Setup ----------------
64
- app = FastAPI()
 
65
 
66
- class GenerateRequest(BaseModel):
67
- prompt: constr(min_length=5, max_length=1000)
68
- session_id: constr(min_length=3, max_length=50)
69
 
70
- @app.get("/status")
71
- def status():
72
- return {
73
- "message": "✅ Autonomous AI API is live",
74
- "routes": ["/status", "/generate", "/generate [POST]", "/memory/{session_id}", "/summary/{session_id}", "/ui"]
75
- }
76
 
77
- @app.get("/generate")
78
- def generate_get(prompt: str):
79
- return {"response": generate_text(prompt)}
80
 
81
- @app.post("/generate")
82
- def generate_post(data: GenerateRequest):
83
- start = time.time()
84
- try:
85
- response = generate_text(data.prompt)
86
- latency = round(time.time() - start, 2)
87
- add_to_memory(data.session_id, data.prompt, response)
88
- logging.info(f"[{data.session_id}] processed in {latency}s")
89
- return {"session_id": data.session_id, "response": response, "latency": latency}
90
- except Exception as e:
91
- raise HTTPException(status_code=500, detail=str(e))
92
 
93
- @app.get("/memory/{session_id}")
 
 
94
 
95
- def session_memory(session_id: str):
96
- return {"session_id": session_id, "history": get_memory(session_id)}
97
-
98
- @app.get("/summary/{session_id}")
99
- def memory_summary(session_id: str):
100
- return {"session_id": session_id, "summary": get_summary(session_id)}
101
-
102
- # ---------------- Gradio UI ----------------
103
- def agent_interface(goal: str) -> str:
104
- session_id = str(uuid.uuid4())[:8]
105
- context = get_summary(session_id)
106
- prompt = f"{context}\nGoal: {goal}" if context else goal
107
- result = generate_text(prompt)
108
- add_to_memory(session_id, goal, result)
109
- return f"Session ID: {session_id}\n\n{result}"
110
-
111
- with gr.Blocks() as demo:
112
- gr.Markdown("## 🤖 Autonomous Agent Interface")
113
- inp = gr.Textbox(label="Your Goal", placeholder="e.g. Plan my day...")
114
- out = gr.Textbox(label="Agent Output", lines=10)
115
- btn = gr.Button("Run")
116
- btn.click(agent_interface, inputs=[inp], outputs=[out])
117
-
118
- # Mount Gradio onto FastAPI
119
- from fastapi.middleware.cors import CORSMiddleware
120
- app = gr.mount_gradio_app(app, demo, path="/ui")
121
- app.add_middleware(
122
- CORSMiddleware,
123
- allow_origins=["*"],
124
- allow_methods=["*"],
125
- allow_headers=["*"],
126
- )
127
-
128
- # ---------------- Initialization Confirmation ----------------
129
- print("🚀 Application initialized and ready to serve!")
130
-
131
- # ---------------- Run Server ----------------
132
- if __name__ == "__main__":
133
- import uvicorn
134
- port = int(os.environ.get("PORT", 7865))
135
- uvicorn.run(app, host="0.0.0.0", port=port)
 
 
 
 
 
 
 
1
 
2
+ import streamlit as st
 
 
 
 
 
 
 
3
 
4
+ st.title("Autonomous AI for Hugging Face Spaces")
 
5
 
6
+ st.write("This AI can go online, diagnose itself, learn, and correct errors.")
 
 
 
 
 
 
 
 
 
 
7
 
8
+ # Placeholder for system status
9
+ if 'status' not in st.session_state:
10
+ st.session_state['status'] = 'Idle'
 
11
 
12
+ st.write("System Status:", st.session_state['status'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ # Buttons for control
15
+ if st.button('Run Diagnostics'):
16
+ st.session_state['status'] = 'Running Diagnostics...'
17
+ # Call diagnostics function here
 
 
 
 
18
 
19
+ if st.button('Self-Teach'):
20
+ st.session_state['status'] = 'Learning...'
21
+ # Call learning function here
22
 
23
+ if st.button('Self-Correct'):
24
+ st.session_state['status'] = 'Correcting Errors...'
25
+ # Call correction function here
26
 
27
+ st.write("Control Panel")
 
 
 
 
 
28
 
29
+ import diagnostics
30
+ import learning
31
+ import correction
32
 
33
+ if st.button('Run Diagnostics'):
34
+ result = diagnostics.run_diagnostics()
35
+ st.write('Diagnostics Result:', result)
 
 
 
 
 
 
 
 
36
 
37
+ if st.button('Self-Teach'):
38
+ result = learning.self_learn()
39
+ st.write('Learning Result:', result)
40
 
41
+ if st.button('Self-Correct'):
42
+ result = correction.self_correct()
43
+ st.write('Correction Result:', result)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
correction.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+
2
+ def self_correct():
3
+ # Simulate fault correction with random success
4
+ import random
5
+ fixed = random.choice([True, False])
6
+ if fixed:
7
+ return "Faults corrected successfully."
8
+ else:
9
+ return "Fault correction failed."
diagnostics.py CHANGED
@@ -1,24 +1,47 @@
 
1
 
2
- import traceback
3
- from datetime import datetime
 
 
 
 
 
 
4
 
5
- class DiagnosticEngine:
6
- def __init__(self):
7
- self.error_logs = []
8
 
9
- def capture_exception(self, e, context=""):
10
- tb = traceback.format_exc()
11
- error_entry = {
12
- "timestamp": datetime.utcnow().isoformat(),
13
- "error": str(e),
14
- "traceback": tb,
15
- "context": context
16
- }
17
- self.error_logs.append(error_entry)
18
- return error_entry
19
-
20
- def get_logs(self):
21
- return self.error_logs
22
-
23
- def last_error(self):
24
- return self.error_logs[-1] if self.error_logs else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
 
3
+ def run_diagnostics():
4
+ # Simulate system checks
5
+ import random
6
+ issues_found = random.choice([False, True])
7
+ if issues_found:
8
+ return "Issues detected: Fault in module X."
9
+ else:
10
+ return "Diagnostics complete. No issues found."
11
 
 
 
 
12
 
13
+ def run_diagnostics():
14
+ import random
15
+ import logging
16
+ # Setup logging
17
+ log_file = 'diagnostics_log.txt'
18
+ if os.path.exists(log_file):
19
+ os.remove(log_file)
20
+ logging.basicConfig(filename=log_file, level=logging.INFO)
21
+
22
+ issues = []
23
+ # Check CPU load
24
+ cpu_load = random.uniform(0, 100)
25
+ logging.info('CPU load: ' + str(cpu_load))
26
+ if cpu_load > 75:
27
+ issues.append('High CPU load')
28
+ # Check memory usage
29
+ mem_usage = random.uniform(0, 100)
30
+ logging.info('Memory usage: ' + str(mem_usage))
31
+ if mem_usage > 80:
32
+ issues.append('High memory usage')
33
+ # Check disk space
34
+ disk_space = random.uniform(0, 100)
35
+ logging.info('Disk space: ' + str(disk_space))
36
+ if disk_space < 20:
37
+ issues.append('Low disk space')
38
+ # Check network connectivity
39
+ network_status = random.choice([True, False])
40
+ logging.info('Network connectivity: ' + str(network_status))
41
+ if not network_status:
42
+ issues.append('Network connectivity issues')
43
+
44
+ if issues:
45
+ return 'Issues detected: ' + ', '.join(issues)
46
+ else:
47
+ return 'Diagnostics complete. No issues found.'
learning.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+
2
+ def self_learn():
3
+ # Simulate a learning process with random success
4
+ import random
5
+ improvement = random.choice([True, False])
6
+ if improvement:
7
+ return "Learning successful: Model parameters improved."
8
+ else:
9
+ return "Learning attempt failed: No improvement detected."
requirements.txt CHANGED
@@ -1,7 +1,2 @@
1
- ctransformers
2
- fastapi
3
- uvicorn
4
- gradio
5
- pydantic
6
- torch
7
- huggingface_hub
 
1
+
2
+ streamlit