Spaces:
Runtime error
Runtime error
Create package.py
Browse files- package.py +60 -0
package.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import matplotlib.pyplot as plt
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import csv
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
API_URL = "https://api-inference.huggingface.co/models/OttoYu/Tree-Inspection"
|
| 8 |
+
headers = {"Authorization": "Bearer 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"}
|
| 9 |
+
|
| 10 |
+
def TreeAI(image_path):
|
| 11 |
+
def query(filename):
|
| 12 |
+
with open(filename, "rb") as f:
|
| 13 |
+
data = f.read()
|
| 14 |
+
response = requests.post(API_URL, headers=headers, data=data)
|
| 15 |
+
return response.json()
|
| 16 |
+
|
| 17 |
+
output = query(image_path)
|
| 18 |
+
|
| 19 |
+
if "error" in output:
|
| 20 |
+
print("Error:", output["error"])
|
| 21 |
+
else:
|
| 22 |
+
for result in output:
|
| 23 |
+
label = result["label"]
|
| 24 |
+
confidence = result["score"]
|
| 25 |
+
print("Prediction:", label, ",", confidence, "%")
|
| 26 |
+
|
| 27 |
+
image = Image.open(image_path)
|
| 28 |
+
plt.imshow(image)
|
| 29 |
+
plt.axis('off')
|
| 30 |
+
plt.show()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def TreeAI_Batch(folder_path, output_csv):
|
| 34 |
+
image_paths = []
|
| 35 |
+
for filename in os.listdir(folder_path):
|
| 36 |
+
if filename.endswith((".jpg", ".jpeg", ".png")):
|
| 37 |
+
image_paths.append(os.path.join(folder_path, filename))
|
| 38 |
+
|
| 39 |
+
num_images = len(image_paths)
|
| 40 |
+
results = []
|
| 41 |
+
|
| 42 |
+
for i, image_path in enumerate(image_paths):
|
| 43 |
+
print(f"Processing image {i+1}/{num_images}...")
|
| 44 |
+
|
| 45 |
+
output = query(image_path)
|
| 46 |
+
|
| 47 |
+
if "error" in output:
|
| 48 |
+
print("Error:", output["error"])
|
| 49 |
+
else:
|
| 50 |
+
for result in output:
|
| 51 |
+
filename = os.path.basename(image_path)
|
| 52 |
+
label = result["label"]
|
| 53 |
+
confidence = result["score"]
|
| 54 |
+
results.append([filename, label, confidence])
|
| 55 |
+
|
| 56 |
+
with open(output_csv, "w", newline="") as csvfile:
|
| 57 |
+
writer = csv.writer(csvfile)
|
| 58 |
+
writer.writerow(["Filename", "Prediction", "Confidence"])
|
| 59 |
+
writer.writerows(results)
|
| 60 |
+
|