MahatirTusher commited on
Commit
7ce08d2
·
verified ·
1 Parent(s): 3a8ed2e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -25
app.py CHANGED
@@ -15,67 +15,84 @@ except Exception as e:
15
  # OpenRouter.ai Configuration
16
  OPENROUTER_API_KEY = "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"
17
  OPENROUTER_API_URL = "https://openrouter.ai/api/v1/chat/completions"
18
- MODEL_NAME = "mistralai/mistral-small-24b-instruct-2501:free" # Mistral model via OpenRouter
19
 
 
20
  input_shape = (224, 224, 3)
21
 
22
  def preprocess_image(image, target_size):
23
- # ... (keep your existing preprocessing code) ...
 
 
 
 
 
 
 
24
 
25
  def get_medical_guidelines(wound_type):
26
- """
27
- Fetch medical guidelines using OpenRouter.ai's Mistral model.
28
- """
29
  headers = {
30
  "Authorization": f"Bearer {OPENROUTER_API_KEY}",
31
  "Content-Type": "application/json",
32
- "HTTP-Referer": "https://your-huggingface-space-url.com", # Optional
33
- "X-Title": "Wound Classifier" # Optional
34
  }
35
 
36
- prompt = f"""
37
- As a medical professional, provide detailed guidelines for treating a {wound_type} wound.
38
- Include steps for first aid, precautions, and when to seek professional help.
39
- """
40
 
41
  data = {
42
  "model": MODEL_NAME,
43
  "messages": [{"role": "user", "content": prompt}],
44
- "temperature": 0.7 # Adjust for creativity vs. precision
45
  }
46
 
47
  try:
48
  response = requests.post(OPENROUTER_API_URL, headers=headers, json=data)
49
  response.raise_for_status()
50
- result = response.json()
51
- return result["choices"][0]["message"]["content"]
52
  except Exception as e:
53
  return f"Error fetching guidelines: {str(e)}"
54
 
55
  def predict(image):
 
56
  try:
57
- # ... (keep your existing preprocessing and prediction code) ...
 
 
58
 
59
- # After getting `predicted_class`:
 
 
 
 
 
 
 
 
 
 
 
 
60
  guidelines = get_medical_guidelines(predicted_class)
61
-
62
- return {
63
- "predictions": results, # Your existing classification results
64
- "treatment_guidelines": guidelines # From OpenRouter.ai
65
- }
66
-
67
  except Exception as e:
68
  return {"error": str(e)}
69
 
70
- # Update Gradio interface to show both outputs
71
  iface = gr.Interface(
72
  fn=predict,
73
  inputs=gr.Image(type="pil"),
74
  outputs=[
75
- gr.Label(num_top_classes=18, label="Classification Results"),
76
  gr.Textbox(label="Medical Guidelines", lines=5)
77
  ],
78
- live=True
 
 
79
  )
80
 
81
  iface.launch(server_name="0.0.0.0", server_port=7860)
 
15
  # OpenRouter.ai Configuration
16
  OPENROUTER_API_KEY = "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"
17
  OPENROUTER_API_URL = "https://openrouter.ai/api/v1/chat/completions"
18
+ MODEL_NAME = "mistralai/mistral-small-24b-instruct-2501:free"
19
 
20
+ # Define input shape
21
  input_shape = (224, 224, 3)
22
 
23
  def preprocess_image(image, target_size):
24
+ """Preprocess the input image for the model."""
25
+ if image is None:
26
+ raise ValueError("No image provided")
27
+ image = image.convert("RGB") # Ensure RGB format
28
+ image = image.resize(target_size)
29
+ image_array = np.array(image)
30
+ image_array = image_array / 255.0 # Normalize
31
+ return image_array
32
 
33
  def get_medical_guidelines(wound_type):
34
+ """Fetch medical guidelines using OpenRouter.ai's API."""
 
 
35
  headers = {
36
  "Authorization": f"Bearer {OPENROUTER_API_KEY}",
37
  "Content-Type": "application/json",
38
+ "HTTP-Referer": "https://huggingface.co/spaces/MahatirTusher/Wound_Treatment",
39
+ "X-Title": "Wound_Treatment"
40
  }
41
 
42
+ prompt = f"""As a medical professional, provide detailed guidelines for treating a {wound_type} wound.
43
+ Include first aid steps, precautions, and when to seek professional help."""
 
 
44
 
45
  data = {
46
  "model": MODEL_NAME,
47
  "messages": [{"role": "user", "content": prompt}],
48
+ "temperature": 0.7
49
  }
50
 
51
  try:
52
  response = requests.post(OPENROUTER_API_URL, headers=headers, json=data)
53
  response.raise_for_status()
54
+ return response.json()["choices"][0]["message"]["content"]
 
55
  except Exception as e:
56
  return f"Error fetching guidelines: {str(e)}"
57
 
58
  def predict(image):
59
+ """Main prediction function."""
60
  try:
61
+ # Preprocess image
62
+ input_data = preprocess_image(image, (input_shape[0], input_shape[1]))
63
+ input_data = np.expand_dims(input_data, axis=0)
64
 
65
+ # Load class labels
66
+ with open('./classes.txt', 'r') as file:
67
+ class_labels = file.read().splitlines()
68
+
69
+ if len(class_labels) != model.output_shape[-1]:
70
+ raise ValueError("Class labels mismatch with model output")
71
+
72
+ # Make prediction
73
+ predictions = model.predict(input_data)
74
+ results = {class_labels[i]: float(predictions[0][i]) for i in range(len(class_labels))}
75
+ predicted_class = class_labels[np.argmax(predictions)]
76
+
77
+ # Get medical guidelines
78
  guidelines = get_medical_guidelines(predicted_class)
79
+
80
+ return {"predictions": results, "treatment_guidelines": guidelines}
81
+
 
 
 
82
  except Exception as e:
83
  return {"error": str(e)}
84
 
85
+ # Gradio Interface
86
  iface = gr.Interface(
87
  fn=predict,
88
  inputs=gr.Image(type="pil"),
89
  outputs=[
90
+ gr.Label(num_top_classes=3, label="Classification Results"),
91
  gr.Textbox(label="Medical Guidelines", lines=5)
92
  ],
93
+ live=True,
94
+ title="Wound Classification & Treatment Advisor",
95
+ description="Upload a wound image for classification and medical guidelines."
96
  )
97
 
98
  iface.launch(server_name="0.0.0.0", server_port=7860)