Multilingual
Browse files
app.py
CHANGED
|
@@ -31,155 +31,152 @@ SYSTEM = os.getenv("SYSTEM")
|
|
| 31 |
|
| 32 |
# Optional: Set up logging if required for production.
|
| 33 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
def extract_json_from_response(response):
|
| 36 |
message_body = response.text
|
| 37 |
-
|
| 38 |
-
# Try to locate code block with triple backticks
|
| 39 |
if "```" in message_body:
|
| 40 |
start = message_body.find("```")
|
| 41 |
end = message_body.find("```", start + 3)
|
| 42 |
-
|
| 43 |
if end != -1:
|
| 44 |
-
# Strip optional 'json' or other format specifier
|
| 45 |
code_block = message_body[start + 3:end].strip()
|
| 46 |
if code_block.startswith("json"):
|
| 47 |
code_block = code_block[4:].strip()
|
| 48 |
message_body = code_block
|
| 49 |
else:
|
| 50 |
-
# Only one set of backticks found, possibly malformed
|
| 51 |
message_body = message_body[start + 3:].strip()
|
| 52 |
-
|
| 53 |
-
# If there's no backtick block, assume it's plain JSON
|
| 54 |
try:
|
| 55 |
parsed_json = json.loads(message_body)
|
| 56 |
logging.info("Parsed JSON: %s", parsed_json)
|
| 57 |
return parsed_json
|
| 58 |
except json.JSONDecodeError as e:
|
| 59 |
logging.error("Failed to parse JSON: %s", e)
|
| 60 |
-
return
|
| 61 |
-
|
| 62 |
|
| 63 |
-
def
|
| 64 |
try:
|
| 65 |
-
# Request to generate content using the model
|
| 66 |
response = client.models.generate_content(
|
| 67 |
model="gemini-2.0-flash",
|
| 68 |
-
config=types.GenerateContentConfig(system_instruction=
|
| 69 |
-
contents=
|
| 70 |
)
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
| 74 |
|
| 75 |
-
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
except Exception as e:
|
| 78 |
-
logging.error(f"
|
| 79 |
-
return {
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
def gen_message(data_dict):
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
Hi there, I'm Med-AI-Care, your virtual health assistant.
|
| 86 |
|
| 87 |
I understood your message as:
|
| 88 |
-
|
| 89 |
|
| 90 |
-
Thank you for reaching out.
|
| 91 |
|
| 92 |
-
|
| 93 |
-
{data_dict
|
| 94 |
|
| 95 |
-
|
| 96 |
-
{data_dict
|
| 97 |
|
| 98 |
-
|
| 99 |
|
| 100 |
-
Take care
|
| 101 |
-
|
| 102 |
else:
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
| 105 |
|
| 106 |
You said:
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
| 111 |
|
| 112 |
-
|
| 113 |
-
{
|
| 114 |
|
| 115 |
-
|
| 116 |
-
{data_dict
|
| 117 |
|
| 118 |
-
|
| 119 |
-
{data_dict['recommendation']}
|
| 120 |
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
-
|
| 124 |
-
""".replace("*","")
|
| 125 |
-
|
| 126 |
-
return message_body
|
| 127 |
|
| 128 |
def chat(cmd):
|
| 129 |
-
|
| 130 |
-
|
|
|
|
|
|
|
| 131 |
model="meta-llama/llama-4-scout-17b-16e-instruct",
|
| 132 |
messages=[
|
| 133 |
-
|
| 134 |
-
"role": "
|
| 135 |
-
"content": TASK
|
| 136 |
-
},
|
| 137 |
-
{
|
| 138 |
-
"role": "user",
|
| 139 |
-
"content": cmd
|
| 140 |
-
}
|
| 141 |
],
|
| 142 |
temperature=1,
|
| 143 |
max_completion_tokens=1024,
|
| 144 |
top_p=1,
|
| 145 |
stream=True,
|
| 146 |
-
stop=None,
|
| 147 |
)
|
| 148 |
|
| 149 |
output = []
|
| 150 |
for chunk in completion:
|
| 151 |
output.append(chunk.choices[0].delta.content or "")
|
| 152 |
|
| 153 |
-
|
| 154 |
-
in_block = False
|
| 155 |
result = ""
|
| 156 |
-
|
| 157 |
for line in output:
|
| 158 |
if line.strip() == "```":
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
elif in_block and line.strip().lower() != "json":
|
| 164 |
-
result+=line
|
| 165 |
-
|
| 166 |
|
| 167 |
try:
|
| 168 |
result_json = json.loads(result)
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
if lang != "English":
|
| 172 |
-
data_dict = translate(result)
|
| 173 |
-
message_body = gen_message(data_dict)
|
| 174 |
-
else:
|
| 175 |
-
data_dict = result_json
|
| 176 |
-
message_body = gen_message(data_dict)
|
| 177 |
except json.JSONDecodeError as e:
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
return output,data_dict,message_body
|
| 182 |
|
|
|
|
| 183 |
|
| 184 |
bot_token = os.getenv("BOT")
|
| 185 |
|
|
|
|
| 31 |
|
| 32 |
# Optional: Set up logging if required for production.
|
| 33 |
logging.basicConfig(level=logging.INFO)
|
| 34 |
+
LANGUAGE_DETECTION_PROMPT = os.getenv("Language")
|
| 35 |
+
|
| 36 |
+
# ---------- Utility Functions ----------
|
| 37 |
|
| 38 |
def extract_json_from_response(response):
|
| 39 |
message_body = response.text
|
|
|
|
|
|
|
| 40 |
if "```" in message_body:
|
| 41 |
start = message_body.find("```")
|
| 42 |
end = message_body.find("```", start + 3)
|
|
|
|
| 43 |
if end != -1:
|
|
|
|
| 44 |
code_block = message_body[start + 3:end].strip()
|
| 45 |
if code_block.startswith("json"):
|
| 46 |
code_block = code_block[4:].strip()
|
| 47 |
message_body = code_block
|
| 48 |
else:
|
|
|
|
| 49 |
message_body = message_body[start + 3:].strip()
|
| 50 |
+
|
|
|
|
| 51 |
try:
|
| 52 |
parsed_json = json.loads(message_body)
|
| 53 |
logging.info("Parsed JSON: %s", parsed_json)
|
| 54 |
return parsed_json
|
| 55 |
except json.JSONDecodeError as e:
|
| 56 |
logging.error("Failed to parse JSON: %s", e)
|
| 57 |
+
return {}
|
|
|
|
| 58 |
|
| 59 |
+
def detect_language(text):
|
| 60 |
try:
|
|
|
|
| 61 |
response = client.models.generate_content(
|
| 62 |
model="gemini-2.0-flash",
|
| 63 |
+
config=types.GenerateContentConfig(system_instruction=LANGUAGE_DETECTION_PROMPT),
|
| 64 |
+
contents=[{"role": "user", "parts": [{"text": text}]}]
|
| 65 |
)
|
| 66 |
+
detected_json = extract_json_from_response(response)
|
| 67 |
+
return detected_json.get("input_lang", "English")
|
| 68 |
+
except Exception as e:
|
| 69 |
+
logging.error(f"Language detection failed: {e}")
|
| 70 |
+
return "English"
|
| 71 |
|
| 72 |
+
def translate(content, target_language):
|
| 73 |
+
try:
|
| 74 |
+
if not content:
|
| 75 |
+
return {"translation": ""}
|
| 76 |
+
response = client.models.generate_content(
|
| 77 |
+
model="gemini-2.0-flash",
|
| 78 |
+
config=types.GenerateContentConfig(system_instruction=f"Translate the following content into {target_language}. Respond with plain text only."),
|
| 79 |
+
contents=[{"role": "user", "parts": [{"text": content}]}]
|
| 80 |
+
)
|
| 81 |
+
return extract_json_from_response(response) or {"translation": response.text.strip()}
|
| 82 |
except Exception as e:
|
| 83 |
+
logging.error(f"Translation failed: {e}")
|
| 84 |
+
return {"translation": content}
|
| 85 |
+
|
| 86 |
+
# ---------- Message Generator ----------
|
| 87 |
|
| 88 |
+
def gen_message(data_dict, language="English"):
|
| 89 |
+
if not data_dict.get("symptoms") or not data_dict.get("diseases"):
|
| 90 |
+
template = f"""
|
| 91 |
+
Hi there, I'm Med-AI-Care, your virtual health assistant.
|
|
|
|
| 92 |
|
| 93 |
I understood your message as:
|
| 94 |
+
"{data_dict.get('translation')}"
|
| 95 |
|
| 96 |
+
Thank you for reaching out. I couldn't detect specific symptoms or conditions. It's okay to feel unsure — I'm still here to support you.
|
| 97 |
|
| 98 |
+
My Analysis:
|
| 99 |
+
{data_dict.get('analysis')}
|
| 100 |
|
| 101 |
+
Recommendation:
|
| 102 |
+
{data_dict.get('recommendation')}
|
| 103 |
|
| 104 |
+
Please consult a licensed medical professional for any health concerns.
|
| 105 |
|
| 106 |
+
Take care!
|
| 107 |
+
"""
|
| 108 |
else:
|
| 109 |
+
symptoms = ', '.join(data_dict.get("symptoms")).capitalize()
|
| 110 |
+
diseases = '\n'.join([f"- {disease}: {likelihood}" for disease, likelihood in data_dict.get("diseases").items()])
|
| 111 |
+
template = f"""
|
| 112 |
+
Hi there, I'm Med-AI-Care, your virtual health assistant.
|
| 113 |
|
| 114 |
You said:
|
| 115 |
+
"{data_dict.get('translation')}"
|
| 116 |
+
|
| 117 |
+
Symptoms detected:
|
| 118 |
+
{symptoms}
|
| 119 |
|
| 120 |
+
Possible conditions:
|
| 121 |
+
{diseases}
|
| 122 |
|
| 123 |
+
My Analysis:
|
| 124 |
+
{data_dict.get('analysis')}
|
| 125 |
|
| 126 |
+
Recommendation:
|
| 127 |
+
{data_dict.get('recommendation')}
|
| 128 |
|
| 129 |
+
I'm not a doctor — please follow up with a healthcare professional.
|
|
|
|
| 130 |
|
| 131 |
+
Thanks for reaching out!
|
| 132 |
+
"""
|
| 133 |
+
if language != "English":
|
| 134 |
+
translated = translate(template, language)
|
| 135 |
+
return translated.get("translation", template)
|
| 136 |
+
return template
|
| 137 |
|
| 138 |
+
# ---------- Core Chat Function ----------
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
def chat(cmd):
|
| 141 |
+
language = detect_language(cmd)
|
| 142 |
+
|
| 143 |
+
client_instance = Groq(api_key=API_KEY_1)
|
| 144 |
+
completion = client_instance.chat.completions.create(
|
| 145 |
model="meta-llama/llama-4-scout-17b-16e-instruct",
|
| 146 |
messages=[
|
| 147 |
+
{"role": "system", "content": TASK},
|
| 148 |
+
{"role": "user", "content": cmd}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
],
|
| 150 |
temperature=1,
|
| 151 |
max_completion_tokens=1024,
|
| 152 |
top_p=1,
|
| 153 |
stream=True,
|
|
|
|
| 154 |
)
|
| 155 |
|
| 156 |
output = []
|
| 157 |
for chunk in completion:
|
| 158 |
output.append(chunk.choices[0].delta.content or "")
|
| 159 |
|
| 160 |
+
# Extract JSON from response
|
|
|
|
| 161 |
result = ""
|
| 162 |
+
in_block = False
|
| 163 |
for line in output:
|
| 164 |
if line.strip() == "```":
|
| 165 |
+
in_block = not in_block
|
| 166 |
+
continue
|
| 167 |
+
if in_block and line.strip().lower() != "json":
|
| 168 |
+
result += line
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
try:
|
| 171 |
result_json = json.loads(result)
|
| 172 |
+
data_dict = result_json if language == "English" else translate(result, language)
|
| 173 |
+
message_body = gen_message(data_dict, language)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
except json.JSONDecodeError as e:
|
| 175 |
+
logging.error("Final JSON parsing failed: %s", e)
|
| 176 |
+
data_dict = {}
|
| 177 |
+
message_body = "Sorry, I had trouble understanding your input."
|
|
|
|
| 178 |
|
| 179 |
+
return output, data_dict, message_body
|
| 180 |
|
| 181 |
bot_token = os.getenv("BOT")
|
| 182 |
|