shukdevdatta123 commited on
Commit
41eb236
·
verified ·
1 Parent(s): e92dcfb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -42
app.py CHANGED
@@ -1,42 +1,98 @@
1
- from Crypto.Cipher import AES
2
- from Crypto.Protocol.KDF import PBKDF2
3
- import os
4
- import tempfile
5
- from dotenv import load_dotenv
6
-
7
- load_dotenv() # Load all environment variables
8
-
9
- def unpad(data):
10
- return data[:-data[-1]]
11
-
12
- def decrypt_and_run():
13
- # Get password from Hugging Face Secrets environment variable
14
- password = os.getenv("PASSWORD")
15
- if not password:
16
- raise ValueError("PASSWORD secret not found in environment variables")
17
-
18
- password = password.encode()
19
-
20
- with open("code.enc", "rb") as f:
21
- encrypted = f.read()
22
-
23
- salt = encrypted[:16]
24
- iv = encrypted[16:32]
25
- ciphertext = encrypted[32:]
26
-
27
- key = PBKDF2(password, salt, dkLen=32, count=1000000)
28
- cipher = AES.new(key, AES.MODE_CBC, iv)
29
-
30
- plaintext = unpad(cipher.decrypt(ciphertext))
31
-
32
- with tempfile.NamedTemporaryFile(suffix=".py", delete=False, mode='wb') as tmp:
33
- tmp.write(plaintext)
34
- tmp.flush()
35
- print(f"[INFO] Running decrypted code from {tmp.name}")
36
- os.system(f"python {tmp.name}")
37
-
38
- if __name__ == "__main__":
39
- decrypt_and_run()
40
-
41
- # This script decrypts the encrypted code and runs it.
42
- # Ensure you have the PASSWORD secret set in your Hugging Face Secrets
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import base64
3
+ from groq import Groq
4
+ import tempfile
5
+ import os
6
+
7
+ def encode_image(image_path):
8
+ """Convert an image to base64 encoding"""
9
+ with open(image_path, "rb") as image_file:
10
+ return base64.b64encode(image_file.read()).decode('utf-8')
11
+
12
+ def extract_medicines(image, api_key):
13
+ """Extract medicine names from prescription image using Groq API"""
14
+ if not api_key:
15
+ return "Please provide a Groq API key"
16
+
17
+ if image is None:
18
+ return "Please upload a prescription image"
19
+
20
+ try:
21
+ # Save the uploaded image to a temporary file
22
+ with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as temp_image:
23
+ image_path = temp_image.name
24
+ image.save(image_path)
25
+
26
+ # Encode the image to base64
27
+ base64_image = encode_image(image_path)
28
+
29
+ # Clean up the temporary file
30
+ os.unlink(image_path)
31
+
32
+ # Initialize Groq client with the provided API key
33
+ client = Groq(api_key=api_key)
34
+
35
+ # Create the prompt specifically asking for medicine names only
36
+ prompt = "This is an image of a medical prescription. Extract and list ONLY the names of medicines/drugs/medications from this prescription. Do not include dosages, frequencies, or other information. Return just a simple list of medicine names, one per line."
37
+
38
+ # Make the API call
39
+ chat_completion = client.chat.completions.create(
40
+ messages=[
41
+ {
42
+ "role": "user",
43
+ "content": [
44
+ {"type": "text", "text": prompt},
45
+ {
46
+ "type": "image_url",
47
+ "image_url": {
48
+ "url": f"data:image/jpeg;base64,{base64_image}",
49
+ },
50
+ },
51
+ ],
52
+ }
53
+ ],
54
+ model="meta-llama/llama-4-scout-17b-16e-instruct",
55
+ )
56
+
57
+ # Return the extracted medicine names
58
+ return chat_completion.choices[0].message.content
59
+
60
+ except Exception as e:
61
+ return f"An error occurred: {str(e)}"
62
+
63
+ # Create the Gradio interface
64
+ with gr.Blocks(title="Prescription Medicine Extractor", theme=gr.themes.Ocean()) as app:
65
+ gr.Markdown("# Medicine Name Extractor from Prescriptions")
66
+ gr.Markdown("Upload a prescription image and enter your Groq API key to extract medicine names")
67
+
68
+ with gr.Row():
69
+ with gr.Column():
70
+ api_key_input = gr.Textbox(
71
+ label="Groq API Key",
72
+ placeholder="Enter your Groq API key here",
73
+ type="password"
74
+ )
75
+ image_input = gr.Image(label="Upload Prescription Image", type="pil")
76
+ extract_button = gr.Button("Extract Medicine Names")
77
+
78
+ with gr.Column():
79
+ output = gr.Textbox(label="Extracted Medicine Names", lines=10)
80
+
81
+ extract_button.click(
82
+ fn=extract_medicines,
83
+ inputs=[image_input, api_key_input],
84
+ outputs=output
85
+ )
86
+
87
+ gr.Markdown("""
88
+ ## Instructions
89
+ 1. Enter your Groq API key
90
+ 2. Upload a clear image of a medical prescription
91
+ 3. Click "Extract Medicine Names"
92
+ 4. The application will return only the names of medicines from the prescription
93
+
94
+ **Note:** Your API key is not stored and is only used for making requests to the Groq API.
95
+ """)
96
+
97
+ if __name__ == "__main__":
98
+ app.launch()