ciaochris commited on
Commit
e120be1
·
verified ·
1 Parent(s): 3ff07f2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -108
app.py CHANGED
@@ -1,118 +1,50 @@
1
- import os
2
  import gradio as gr
 
3
  from groq import Groq
4
- import io
5
- import base64
6
- import logging
7
- from typing import Dict, Any
8
-
9
- from dotenv import load_dotenv
10
- from flask import Flask, request, jsonify
11
- from huggingface_hub import login
12
- import requests
13
- from PIL import Image
14
- from werkzeug.utils import secure_filename
15
-
16
- # Configure logging
17
- logging.basicConfig(level=logging.INFO)
18
- logger = logging.getLogger(__name__)
19
-
20
- # Load environment variables
21
- load_dotenv()
22
 
23
- # Initialize Flask app
24
- app = Flask(__name__)
 
 
25
 
26
- # Hugging Face and Groq API configuration
27
- HUGGINGFACE_TOKEN = os.environ.get("HUGGINGFACE_TOKEN")
28
- GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
29
- GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
30
-
31
- # Login to Hugging Face
32
- if HUGGINGFACE_TOKEN:
33
- login(HUGGINGFACE_TOKEN)
34
- else:
35
- logger.warning("HUGGINGFACE_TOKEN not set. Some features may be limited.")
36
-
37
- # Define allowed file extensions
38
- ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
39
-
40
- def allowed_file(filename: str) -> bool:
41
- return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
42
-
43
- def groq_process(image: Image.Image) -> Dict[str, Any]:
44
- """
45
- Process the image using Groq's API for medical image analysis.
46
- """
47
- headers = {
48
- "Authorization": f"Bearer {GROQ_API_KEY}",
49
- "Content-Type": "application/json"
50
- }
51
 
52
- # Convert image to base64
53
- buffered = io.BytesIO()
54
- image.save(buffered, format="PNG")
55
- img_str = base64.b64encode(buffered.getvalue()).decode()
56
 
57
- payload = {
58
- "model": "mixtral-8x7b-32768",
59
- "messages": [
60
- {"role": "system", "content": "You are an AI trained to analyze medical images. Provide a detailed analysis of the image, noting any abnormalities or potential areas of concern. Remember to state that this is an AI analysis and should be reviewed by a medical professional."},
61
- {"role": "user", "content": f"Analyze this medical image in detail: data:image/png;base64,{img_str}"}
62
- ],
63
- "max_tokens": 500
64
- }
65
 
66
- try:
67
- response = requests.post(GROQ_API_URL, headers=headers, json=payload, timeout=30)
68
- response.raise_for_status()
69
- return {"success": True, "analysis": response.json()['choices'][0]['message']['content']}
70
- except requests.exceptions.RequestException as e:
71
- logger.error(f"Error in Groq API request: {str(e)}")
72
- return {"success": False, "error": "Error in processing the image"}
73
-
74
- def analyze_medical_image(image_file) -> Dict[str, Any]:
75
- """
76
- Analyze a medical image file.
77
- """
78
- try:
79
- image = Image.open(image_file)
80
- analysis_result = groq_process(image)
81
- return analysis_result
82
- except Exception as e:
83
- logger.error(f"Error in image analysis: {str(e)}")
84
- return {"success": False, "error": "Error in analyzing the image"}
85
-
86
- @app.route('/analyze-medical-image', methods=['POST'])
87
- def analyze_route():
88
- """
89
- Route to handle medical image analysis requests.
90
  """
91
- if 'image' not in request.files:
92
- return jsonify({"error": "No image file provided"}), 400
93
 
94
- file = request.files['image']
95
- if file.filename == '':
96
- return jsonify({"error": "No selected file"}), 400
 
 
 
 
 
 
 
 
97
 
98
- if file and allowed_file(file.filename):
99
- filename = secure_filename(file.filename)
100
- analysis_result = analyze_medical_image(file)
101
-
102
- if analysis_result['success']:
103
- return jsonify({
104
- "filename": filename,
105
- "analysis": analysis_result['analysis'],
106
- "disclaimer": "This analysis is provided by an AI system and should be reviewed by a qualified medical professional. It is not a substitute for professional medical advice, diagnosis, or treatment."
107
- })
108
- else:
109
- return jsonify({"error": analysis_result['error']}), 500
110
- else:
111
- return jsonify({"error": "Invalid file type. Allowed types are png, jpg, jpeg"}), 400
112
-
113
- @app.route('/', methods=['GET'])
114
- def index():
115
- return "Medical Image Analysis Tool - For research and educational purposes only. Not for clinical use."
116
-
117
- if __name__ == "__main__":
118
- app.run(host="0.0.0.0", port=7860)
 
 
1
  import gradio as gr
2
+ import os
3
  from groq import Groq
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ # Initialize Groq client
6
+ client = Groq(
7
+ api_key=os.environ.get("GROQ_API_KEY"),
8
+ )
9
 
10
+ def get_diagnosis(symptoms):
11
+ # IMPORTANT: This is a simplified example and should not be used for actual medical diagnosis
12
+ prompt = f"""
13
+ Given the following symptoms, provide a preliminary analysis of potential cancer risks.
14
+ This is not a definitive diagnosis and should not replace professional medical advice.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ Symptoms: {symptoms}
 
 
 
17
 
18
+ Please provide:
19
+ 1. Potential cancer types that might be associated with these symptoms
20
+ 2. Recommendations for further medical tests or consultations
21
+ 3. General health advice
 
 
 
 
22
 
23
+ Remember to emphasize the importance of consulting with a medical professional for accurate diagnosis and treatment.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  """
 
 
25
 
26
+ chat_completion = client.chat.completions.create(
27
+ messages=[
28
+ {
29
+ "role": "user",
30
+ "content": prompt,
31
+ }
32
+ ],
33
+ model="mixtral-8x7b-32768",
34
+ temperature=0.5,
35
+ max_tokens=1000,
36
+ )
37
 
38
+ return chat_completion.choices[0].message.content
39
+
40
+ # Create Gradio interface
41
+ iface = gr.Interface(
42
+ fn=get_diagnosis,
43
+ inputs=gr.Textbox(lines=5, label="Enter symptoms (separated by commas)"),
44
+ outputs="text",
45
+ title="Cancer Risk Assessment Tool",
46
+ description="This tool provides a preliminary analysis based on symptoms. It is not a substitute for professional medical advice, diagnosis, or treatment.",
47
+ )
48
+
49
+ # Launch the app
50
+ iface.launch())