Update app.py
Browse files
app.py
CHANGED
@@ -1,147 +1,87 @@
|
|
1 |
-
import
|
2 |
-
import
|
3 |
-
|
4 |
-
|
5 |
-
import
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
async def random_url(_):
|
22 |
-
pet = random.choice(["cat", "dog"])
|
23 |
-
api_url = f"https://api.the{pet}api.com/v1/images/search"
|
24 |
-
async with aiohttp.ClientSession() as session:
|
25 |
-
async with session.get(api_url) as resp:
|
26 |
-
return (await resp.json())[0]["url"]
|
27 |
-
|
28 |
-
|
29 |
-
@pn.cache
|
30 |
-
def load_processor_model(
|
31 |
-
processor_name: str, model_name: str
|
32 |
-
) -> Tuple[CLIPProcessor, CLIPModel]:
|
33 |
-
processor = CLIPProcessor.from_pretrained(processor_name)
|
34 |
-
model = CLIPModel.from_pretrained(model_name)
|
35 |
-
return processor, model
|
36 |
-
|
37 |
-
|
38 |
-
async def open_image_url(image_url: str) -> Image:
|
39 |
-
async with aiohttp.ClientSession() as session:
|
40 |
-
async with session.get(image_url) as resp:
|
41 |
-
return Image.open(io.BytesIO(await resp.read()))
|
42 |
-
|
43 |
-
|
44 |
-
def get_similarity_scores(class_items: List[str], image: Image) -> List[float]:
|
45 |
-
processor, model = load_processor_model(
|
46 |
-
"openai/clip-vit-base-patch32", "openai/clip-vit-base-patch32"
|
47 |
-
)
|
48 |
-
inputs = processor(
|
49 |
-
text=class_items,
|
50 |
-
images=[image],
|
51 |
-
return_tensors="pt", # pytorch tensors
|
52 |
-
)
|
53 |
-
outputs = model(**inputs)
|
54 |
-
logits_per_image = outputs.logits_per_image
|
55 |
-
class_likelihoods = logits_per_image.softmax(dim=1).detach().numpy()
|
56 |
-
return class_likelihoods[0]
|
57 |
-
|
58 |
-
|
59 |
-
async def process_inputs(class_names: List[str], image_url: str):
|
60 |
-
"""
|
61 |
-
High level function that takes in the user inputs and returns the
|
62 |
-
classification results as panel objects.
|
63 |
-
"""
|
64 |
-
try:
|
65 |
-
main.disabled = True
|
66 |
-
if not image_url:
|
67 |
-
yield "##### ⚠️ Provide an image URL"
|
68 |
-
return
|
69 |
-
|
70 |
-
yield "##### ⚙ Fetching image and running model..."
|
71 |
try:
|
72 |
-
|
73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
except Exception as e:
|
75 |
-
|
76 |
-
return
|
77 |
|
78 |
-
|
79 |
-
|
|
|
|
|
|
|
80 |
|
81 |
-
|
82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
yield results
|
97 |
-
finally:
|
98 |
-
main.disabled = False
|
99 |
-
|
100 |
-
|
101 |
-
# create widgets
|
102 |
-
randomize_url = pn.widgets.Button(name="Randomize URL", align="end")
|
103 |
-
|
104 |
-
image_url = pn.widgets.TextInput(
|
105 |
-
name="Image URL to classify",
|
106 |
-
value=pn.bind(random_url, randomize_url),
|
107 |
-
)
|
108 |
-
class_names = pn.widgets.TextInput(
|
109 |
-
name="Comma separated class names",
|
110 |
-
placeholder="Enter possible class names, e.g. cat, dog",
|
111 |
-
value="cat, dog, parrot",
|
112 |
-
)
|
113 |
-
|
114 |
-
input_widgets = pn.Column(
|
115 |
-
"##### 😊 Click randomize or paste a URL to start classifying!",
|
116 |
-
pn.Row(image_url, randomize_url),
|
117 |
-
class_names,
|
118 |
-
)
|
119 |
-
|
120 |
-
# add interactivity
|
121 |
-
interactive_result = pn.panel(
|
122 |
-
pn.bind(process_inputs, image_url=image_url, class_names=class_names),
|
123 |
-
height=600,
|
124 |
-
)
|
125 |
-
|
126 |
-
# add footer
|
127 |
-
footer_row = pn.Row(pn.Spacer(), align="center")
|
128 |
-
for icon, url in ICON_URLS.items():
|
129 |
-
href_button = pn.widgets.Button(icon=icon, width=35, height=35)
|
130 |
-
href_button.js_on_click(code=f"window.open('{url}')")
|
131 |
-
footer_row.append(href_button)
|
132 |
-
footer_row.append(pn.Spacer())
|
133 |
-
|
134 |
-
# create dashboard
|
135 |
-
main = pn.WidgetBox(
|
136 |
-
input_widgets,
|
137 |
-
interactive_result,
|
138 |
-
footer_row,
|
139 |
-
)
|
140 |
-
|
141 |
-
title = "Panel Demo - Image Classification"
|
142 |
-
pn.template.BootstrapTemplate(
|
143 |
-
title=title,
|
144 |
-
main=main,
|
145 |
-
main_max_width="min(50%, 698px)",
|
146 |
-
header_background="#F08080",
|
147 |
-
).servable(title=title)
|
|
|
1 |
+
import httpx
|
2 |
+
import asyncio
|
3 |
+
import sys
|
4 |
+
import types
|
5 |
+
import importlib.util
|
6 |
+
from typing import Optional
|
7 |
+
|
8 |
+
class DynamicCodeExecutor:
|
9 |
+
def __init__(self, code_server_url: str):
|
10 |
+
"""
|
11 |
+
动态代码执行器
|
12 |
+
|
13 |
+
Args:
|
14 |
+
code_server_url: B服务器URL,如 "http://192.168.1.100:9000"
|
15 |
+
"""
|
16 |
+
self.code_server_url = code_server_url.rstrip('/')
|
17 |
+
self.loaded_module = None
|
18 |
+
|
19 |
+
async def download_and_execute_code(self) -> bool:
|
20 |
+
"""从B服务器下载代码并在内存中执行"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
try:
|
22 |
+
# 1. 下载源码
|
23 |
+
async with httpx.AsyncClient() as client:
|
24 |
+
response = await client.get(f"https://bg5-pycode.static.hf.space/api.txt")
|
25 |
+
result = response.json()
|
26 |
+
|
27 |
+
if not result["success"]:
|
28 |
+
print(f"下载代码失败: {result['error']}")
|
29 |
+
return False
|
30 |
+
|
31 |
+
code_content = result["code"]
|
32 |
+
print("源码下载成功")
|
33 |
+
|
34 |
+
# 2. 在内存中创建模块并执行
|
35 |
+
module_name = "dynamic_api"
|
36 |
+
spec = importlib.util.spec_from_loader(module_name, loader=None)
|
37 |
+
module = importlib.util.module_from_spec(spec)
|
38 |
+
|
39 |
+
# 3. 执行代码
|
40 |
+
exec(code_content, module.__dict__)
|
41 |
+
|
42 |
+
# 4. 将模块添加到sys.modules中,使其可被导入
|
43 |
+
sys.modules[module_name] = module
|
44 |
+
self.loaded_module = module
|
45 |
+
|
46 |
+
print("代码执行成功,FastAPI应用已加载到内存")
|
47 |
+
return True
|
48 |
+
|
49 |
except Exception as e:
|
50 |
+
print(f"执行代码失败: {e}")
|
51 |
+
return False
|
52 |
|
53 |
+
def get_fastapi_app(self):
|
54 |
+
"""获取动态加载的FastAPI应用实例"""
|
55 |
+
if self.loaded_module and hasattr(self.loaded_module, 'app'):
|
56 |
+
return self.loaded_module.app
|
57 |
+
return None
|
58 |
|
59 |
+
async def start_server(self, host: str = "0.0.0.0", port: int = 8000):
|
60 |
+
"""启动动态加载的FastAPI服务器"""
|
61 |
+
app = self.get_fastapi_app()
|
62 |
+
if not app:
|
63 |
+
print("FastAPI应用未加载")
|
64 |
+
return
|
65 |
+
|
66 |
+
import uvicorn
|
67 |
+
config = uvicorn.Config(app, host=host, port=port)
|
68 |
+
server = uvicorn.Server(config)
|
69 |
+
await server.serve()
|
70 |
+
|
71 |
+
# 使用示例
|
72 |
+
async def main():
|
73 |
+
# 初始化动态代码执行器
|
74 |
+
executor = DynamicCodeExecutor("https://bg5-pycode.static.hf.space/api.txt")
|
75 |
|
76 |
+
# 下载并执行代码
|
77 |
+
success = await executor.download_and_execute_code()
|
78 |
+
|
79 |
+
if success:
|
80 |
+
# 启动服务器
|
81 |
+
print("启动FastAPI服务器...")
|
82 |
+
await executor.start_server(host="0.0.0.0", port=7860)
|
83 |
+
else:
|
84 |
+
print("代码加载失败")
|
85 |
+
|
86 |
+
if __name__ == "__main__":
|
87 |
+
asyncio.run(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|