shukdevdatta123 commited on
Commit
4905934
·
verified ·
1 Parent(s): ee5ea31

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -75
app.py CHANGED
@@ -1,49 +1,31 @@
1
  import gradio as gr
2
  from openai import OpenAI
3
- import re
4
 
5
- def get_openrouter_client(api_key):
6
- """Initialize OpenRouter client with user-provided API key"""
7
- if not api_key or api_key.strip() == "":
8
- return None, "Please enter your OpenRouter API key"
9
 
10
  try:
11
  client = OpenAI(
12
  base_url="https://openrouter.ai/api/v1",
13
- api_key=api_key
14
  )
15
- return client, None
16
- except Exception as e:
17
- return None, f"Error initializing client: {str(e)}"
18
-
19
- def extract_medicine_names(image, api_key):
20
- """Extract medicine names from a prescription image using Gemini via OpenRouter"""
21
- if not image:
22
- return "Please upload a prescription image."
23
-
24
- # Get client with user-provided API key
25
- client, error = get_openrouter_client(api_key)
26
- if error:
27
- return error
28
-
29
- try:
30
- response = client.chat.completions.create(
31
  extra_headers={
32
- "HTTP-Referer": "https://medicine-extractor-app.com",
33
  "X-Title": "Medicine Name Extractor",
34
  },
35
  model="google/gemini-2.0-flash-exp:free",
36
  messages=[
37
- {
38
- "role": "system",
39
- "content": "You are an AI specialized in extracting medication names from prescription images. Only list the medication names, nothing else."
40
- },
41
  {
42
  "role": "user",
43
  "content": [
44
  {
45
  "type": "text",
46
- "text": "Extract ONLY the names of medications from this prescription image. Provide them as a numbered list. If this isn't a medical prescription, respond with 'No prescription detected'."
47
  },
48
  {
49
  "type": "image_url",
@@ -53,72 +35,50 @@ def extract_medicine_names(image, api_key):
53
  }
54
  ]
55
  }
56
- ],
57
- max_tokens=300
58
  )
59
 
60
- result = response.choices[0].message.content.strip()
61
-
62
- # Check if no prescription was detected
63
- if "No prescription detected" in result:
64
- return "No prescription detected in the image."
65
-
66
- # Clean up the response to just include the medication names
67
- # Remove any explanatory text that might appear before or after the list
68
- medicines = []
69
- for line in result.split('\n'):
70
- # Look for numbered lines or lines starting with medication names
71
- if re.match(r'^\d+\.', line.strip()):
72
- # Extract text after the number and period
73
- med_name = re.sub(r'^\d+\.\s*', '', line.strip())
74
- medicines.append(med_name)
75
-
76
- if not medicines:
77
- # If numbered list processing didn't work, return the raw output
78
- return result
79
-
80
- return "\n".join([f"{i+1}. {med}" for i, med in enumerate(medicines)])
81
-
82
  except Exception as e:
83
  return f"Error: {str(e)}"
84
 
85
  # Create the Gradio interface
86
- with gr.Blocks(title="Prescription Medicine Extractor") as app:
87
- gr.Markdown("# Prescription Medicine Name Extractor")
88
- gr.Markdown("Upload a prescription image to extract medication names.")
89
-
90
- api_key = gr.Textbox(
91
- label="OpenRouter API Key",
92
- placeholder="Enter your OpenRouter API key here",
93
- type="password"
94
- )
95
 
96
  with gr.Row():
97
  with gr.Column():
98
- image_input = gr.Image(type="filepath", label="Upload Prescription Image")
99
- submit_btn = gr.Button("Extract Medicine Names", variant="primary")
 
 
 
 
 
 
 
 
100
 
101
  with gr.Column():
102
  output = gr.Textbox(label="Extracted Medicine Names", lines=10)
103
 
104
- submit_btn.click(
105
- fn=extract_medicine_names,
106
- inputs=[image_input, api_key],
107
- outputs=[output]
108
  )
109
 
110
  gr.Markdown("""
111
- ## Usage Instructions
112
- 1. Enter your OpenRouter API key (get one from https://openrouter.ai)
113
- 2. Upload a clear image of a medical prescription
114
- 3. Click the "Extract Medicine Names" button
115
- 4. The names of medications will be displayed in the output box
116
 
117
- **Note:** For best results, ensure the image is clear and the text is readable.
118
- **Privacy Notice:** Your API key and images are processed only during the active session and are not stored.
119
  """)
120
 
121
  # Launch the app
122
  if __name__ == "__main__":
123
- print("Starting Prescription Medicine Name Extractor application...")
124
  app.launch()
 
1
  import gradio as gr
2
  from openai import OpenAI
3
+ import os
4
 
5
+ def extract_medicine_names(api_key, image):
6
+ """Extract medicine names from a prescription image using OpenRouter and Gemini."""
7
+ if not api_key.strip():
8
+ return "Error: Please provide a valid OpenRouter API key."
9
 
10
  try:
11
  client = OpenAI(
12
  base_url="https://openrouter.ai/api/v1",
13
+ api_key=api_key,
14
  )
15
+
16
+ completion = client.chat.completions.create(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  extra_headers={
18
+ "HTTP-Referer": "gradio-medicine-extractor-app",
19
  "X-Title": "Medicine Name Extractor",
20
  },
21
  model="google/gemini-2.0-flash-exp:free",
22
  messages=[
 
 
 
 
23
  {
24
  "role": "user",
25
  "content": [
26
  {
27
  "type": "text",
28
+ "text": "This is a medical prescription image. Please analyze it and ONLY extract the medicine names. Return just a bulleted list of medicine names found, nothing else. If you can't identify any medicines or this isn't a prescription, please respond with 'No medicine names detected'."
29
  },
30
  {
31
  "type": "image_url",
 
35
  }
36
  ]
37
  }
38
+ ]
 
39
  )
40
 
41
+ return completion.choices[0].message.content
42
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  except Exception as e:
44
  return f"Error: {str(e)}"
45
 
46
  # Create the Gradio interface
47
+ with gr.Blocks(title="Medicine Name Extractor") as app:
48
+ gr.Markdown("# Medicine Name Extractor from Prescriptions")
49
+ gr.Markdown("Upload a prescription image to extract medicine names.")
 
 
 
 
 
 
50
 
51
  with gr.Row():
52
  with gr.Column():
53
+ api_key = gr.Textbox(
54
+ label="OpenRouter API Key",
55
+ placeholder="Enter your OpenRouter API key",
56
+ type="password"
57
+ )
58
+ img_input = gr.Image(
59
+ label="Upload Prescription Image",
60
+ type="filepath"
61
+ )
62
+ extract_btn = gr.Button("Extract Medicine Names")
63
 
64
  with gr.Column():
65
  output = gr.Textbox(label="Extracted Medicine Names", lines=10)
66
 
67
+ extract_btn.click(
68
+ fn=extract_medicine_names,
69
+ inputs=[api_key, img_input],
70
+ outputs=output
71
  )
72
 
73
  gr.Markdown("""
74
+ ## How to use:
75
+ 1. Enter your OpenRouter API key
76
+ 2. Upload a prescription image
77
+ 3. Click 'Extract Medicine Names'
 
78
 
79
+ The app will process the image and extract only the medicine names from the prescription.
 
80
  """)
81
 
82
  # Launch the app
83
  if __name__ == "__main__":
 
84
  app.launch()