latterworks commited on
Commit
74cb9b4
·
verified ·
1 Parent(s): 0119ca8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -49
app.py CHANGED
@@ -1,64 +1,113 @@
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
 
 
 
 
 
 
 
8
 
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
 
 
27
 
28
- response = ""
 
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
 
 
38
 
39
- response += token
40
- yield response
 
 
 
 
 
 
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
  ],
 
 
 
 
60
  )
61
 
62
-
63
  if __name__ == "__main__":
64
- demo.launch()
 
 
1
+ import shodan
2
  import gradio as gr
3
+ import logging
4
+ from abc import ABC, abstractmethod
5
+ from typing import List, Optional
6
+ import json
7
+ import asyncio
8
 
9
+ # Logging setup
10
+ logging.basicConfig(
11
+ level=logging.INFO,
12
+ format="%(asctime)s [%(levelname)s] %(message)s",
13
+ handlers=[logging.StreamHandler()]
14
+ )
15
+ logger = logging.getLogger(__name__)
16
+
17
+ # Custom exceptions
18
+ class ScannerException(Exception):
19
+ """Base exception for scanner errors."""
20
+ pass
21
 
22
+ # Instance class (assuming a basic structure since it wasn’t provided)
23
+ class Instance:
24
+ """Represents an Ollama instance."""
25
+ def __init__(self, ip: str, port: int, owner_id: Optional[str] = None):
26
+ self.ip = ip
27
+ self.port = port
28
+ self.owner_id = owner_id
29
 
30
+ @classmethod
31
+ def from_shodan(cls, result: dict, owner_id: Optional[str] = None) -> 'Instance':
32
+ """Create Instance from Shodan result."""
33
+ return cls(ip=result['ip_str'], port=result['port'], owner_id=owner_id)
 
 
 
 
 
34
 
35
+ def to_dict(self) -> dict:
36
+ """Convert to dict for JSON output."""
37
+ return {"ip": self.ip, "port": self.port, "owner_id": self.owner_id}
 
 
38
 
39
+ # Scanner interface
40
+ class IScanner(ABC):
41
+ """Scanner interface for finding Ollama instances."""
42
+ @abstractmethod
43
+ async def scan_instances(self, limit: int = 100) -> List[Instance]:
44
+ pass
45
 
46
+ # ShodanScanner implementation
47
+ class ShodanScanner(IScanner):
48
+ """Scanner for finding public Ollama instances using Shodan."""
49
+ def __init__(self, api_key: str, owner_id: Optional[str] = None):
50
+ self.api_key = api_key
51
+ self.owner_id = owner_id
52
 
53
+ async def scan_instances(self, limit: int = 100) -> List[Instance]:
54
+ """Scan for Ollama instances using Shodan."""
55
+ try:
56
+ api = shodan.Shodan(self.api_key)
57
+ results = api.search('port:11434 "Ollama"', limit=limit)
58
+ instances = [Instance.from_shodan(result, self.owner_id) for result in results['matches']]
59
+ return instances
60
+ except shodan.APIError as e:
61
+ raise ScannerException(f"Shodan API error: {str(e)}")
62
+ except Exception as e:
63
+ raise ScannerException(f"Error during Shodan scan: {str(e)}")
64
 
65
+ # Gradio processing function
66
+ async def scan_ollama_instances(api_key: str, limit: int, owner_id: str = "") -> str:
67
+ """Process Shodan scan and return results."""
68
+ try:
69
+ if not api_key:
70
+ return "Yo, drop a Shodan API key, fam!"
71
+
72
+ scanner = ShodanScanner(api_key, owner_id if owner_id else None)
73
+ instances = await scanner.scan_instances(limit=limit)
74
+
75
+ if not instances:
76
+ return "No Ollama instances found, dawg!"
77
 
78
+ output = ["Found Ollama Instances:"]
79
+ for i, instance in enumerate(instances, 1):
80
+ output.append(f"{i}. {json.dumps(instance.to_dict(), indent=2)}")
81
+
82
+ logger.info(f"Scanned {len(instances)} Ollama instances")
83
+ return "\n\n".join(output)
84
+
85
+ except ScannerException as e:
86
+ logger.error(f"Scan failed: {str(e)}")
87
+ return f"Scan crashed: {str(e)}"
88
+ except Exception as e:
89
+ logger.error(f"Unexpected error: {str(e)}")
90
+ return f"Shit hit the fan, fam: {str(e)}"
91
 
92
+ # Gradio wrapper to run async function
93
+ def gradio_scan(api_key: str, limit: int, owner_id: str) -> str:
94
+ """Wrapper to run async scan in Gradio."""
95
+ return asyncio.run(scan_ollama_instances(api_key, limit, owner_id))
96
+
97
+ # Gradio interface
98
+ demo = gr.Interface(
99
+ fn=gradio_scan,
100
+ inputs=[
101
+ gr.Textbox(label="Shodan API Key", placeholder="Enter your Shodan API key here", type="password"),
102
+ gr.Slider(label="Max Results", minimum=1, maximum=1000, value=100, step=1),
103
+ gr.Textbox(label="Owner ID (Optional)", placeholder="e.g., your_user_id", value="")
 
 
 
 
104
  ],
105
+ outputs=gr.Textbox(label="Ollama Instances Found"),
106
+ title="Ollama Instance Scanner",
107
+ description="Scan for public Ollama instances using Shodan, Bay Area style! Drop your API key and let’s roll.",
108
+ allow_flagging="never"
109
  )
110
 
 
111
  if __name__ == "__main__":
112
+ logger.info("Firin’ up the Ollama scanner on Gradio...")
113
+ demo.launch(server_name="0.0.0.0", server_port=7860)