如何通过浏览器在服务器上运行Python版Google Vision云端应用
Hey there! Since you're new to Python and trying to get Google Vision's landmark detection up and running on your server (http://18.217.137.107), let's break this down into simple, step-by-step actions you can follow. I'll cover everything from initial setup to testing the app.
First, you need a service account key to authenticate your server with Google Vision API. Here's how to get it:
- Head to the Google Cloud Console, select your project (or create one if you haven't), then navigate to IAM & Admin > Service Accounts.
- Create a new service account, assign it the Cloud Vision API User role, then download the JSON key file.
Next, get this key onto your server:
- Use
scpfrom your local machine to upload the file:scp /path/to/your-service-key.json your-server-username@18.217.137.107:/path/you/want/on/server/ - Log into your server via
ssh, then set an environment variable so the Google SDK can find the key:
(To make this permanent, you can add this line to yourexport GOOGLE_APPLICATION_CREDENTIALS="/path/you/want/on/server/your-service-key.json"~/.bashrcor~/.profilefile and runsource ~/.bashrc.)
Make sure your server has Python and the necessary packages:
- If Python/pip isn't installed (Ubuntu example):
sudo apt update && sudo apt install python3 python3-pip -y - Install the Google Cloud Vision library:
pip3 install google-cloud-vision
Let's create a basic Python script to test landmark detection. Create a file named landmark_detector.py on your server with this code:
import io from google.cloud import vision_v1 def detect_landmarks(image_path): """Detects landmarks in a local image file.""" # Initialize the Vision client client = vision_v1.ImageAnnotatorClient() # Read the image content with io.open(image_path, 'rb') as image_file: content = image_file.read() image = vision_v1.Image(content=content) # Send the image to Google Vision for analysis response = client.landmark_detection(image=image) landmarks = response.landmark_annotations # Print the results print("Detected Landmarks:") for landmark in landmarks: print(f"- {landmark.description}") for location in landmark.locations: lat_lng = location.lat_lng print(f" Coordinates: Lat {lat_lng.latitude}, Lng {lat_lng.longitude}") # Handle errors if response.error.message: raise Exception(f"Vision API Error: {response.error.message}") # Test with a local image if __name__ == "__main__": # Replace 'test_landmark.jpg' with your image file path detect_landmarks("test_landmark.jpg")
Now, upload a test image (like a photo of the Eiffel Tower or Mount Everest) to the same directory as the script, naming it test_landmark.jpg.
On your server, navigate to the directory with the script and image, then run:
python3 landmark_detector.py
If everything works, you should see the landmark name and coordinates printed in your terminal.
If you want to access this functionality via your server's URL (http://18.217.137.107), you can wrap the code in a simple Flask web app:
- Install Flask:
pip3 install flask - Create a file named
app.pywith this code:
import io
from flask import Flask, request, jsonify
from google.cloud import vision_v1
app = Flask(name)
client = vision_v1.ImageAnnotatorClient()
@app.route('/detect-landmarks', methods=['POST'])
def detect_landmarks_api():
if 'image' not in request.files:
return jsonify({"error": "No image file provided"}), 400
image_file = request.files['image'] content = image_file.read() image = vision_v1.Image(content=content) response = client.landmark_detection(image=image) landmarks = response.landmark_annotations result = [] for landmark in landmarks: landmark_info = { "name": landmark.description, "coordinates": [] } for loc in landmark.locations: lat_lng = loc.lat_lng landmark_info["coordinates"].append({ "latitude": lat_lng.latitude, "longitude": lat_lng.longitude }) result.append(landmark_info) if response.error.message: return jsonify({"error": response.error.message}), 500 return jsonify({"detected_landmarks": result})
if name == "main":
# Run the server on all interfaces so it's accessible via your server IP
app.run(host='0.0.0.0', port=8080)
3. Run the app: ```bash python3 app.py
- Test it from your local machine with
curl:
You'll get a JSON response with the detected landmarks.curl -X POST -F "image=@/path/to/your/test/image.jpg" http://18.217.137.107:8080/detect-landmarks
- Authentication Errors: Double-check that the
GOOGLE_APPLICATION_CREDENTIALSpath is correct, and the key file has proper permissions (chmod 600 your-service-key.jsonto restrict access). - Package Installation Issues: Upgrade pip first with
pip3 install --upgrade pipif you run into errors installinggoogle-cloud-vision. - Server Access: Ensure your server's firewall allows outgoing connections to Google's API endpoints, and incoming connections on port 8080 (if you're running the web app).
内容的提问来源于stack exchange,提问作者user9394885

