Creating TG Bot
Browse files- Dockerfile +16 -0
- app.py +235 -0
- requirements.txt +12 -0
Dockerfile
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Read the doc: https://huggingface.co/docs/hub/spaces-sdks-docker
|
| 2 |
+
# you will also find guides on how best to write your Dockerfile
|
| 3 |
+
|
| 4 |
+
FROM python:3.9
|
| 5 |
+
|
| 6 |
+
RUN useradd -m -u 1000 user
|
| 7 |
+
USER user
|
| 8 |
+
ENV PATH="/home/user/.local/bin:$PATH"
|
| 9 |
+
|
| 10 |
+
WORKDIR /app
|
| 11 |
+
|
| 12 |
+
COPY --chown=user ./requirements.txt requirements.txt
|
| 13 |
+
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
| 14 |
+
|
| 15 |
+
COPY --chown=user . /app
|
| 16 |
+
CMD ["gunicorn", "--workers", "1", "--timeout", "120", "--bind", "0.0.0.0:7860", "app:app"]
|
app.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
from torchvision import models as torchvision_models # Explicitly use torchvision models
|
| 6 |
+
from torchvision import transforms
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from flask import Flask, request, jsonify
|
| 9 |
+
from huggingface_hub import hf_hub_download # To download the specific .pth file
|
| 10 |
+
import os
|
| 11 |
+
import json
|
| 12 |
+
from groq import Groq
|
| 13 |
+
import logging
|
| 14 |
+
from telegram import Update
|
| 15 |
+
from telegram.ext import (
|
| 16 |
+
ApplicationBuilder,
|
| 17 |
+
ContextTypes,
|
| 18 |
+
CommandHandler,
|
| 19 |
+
MessageHandler,
|
| 20 |
+
filters
|
| 21 |
+
)
|
| 22 |
+
from google import genai
|
| 23 |
+
from google.genai import types
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
API_KEY_1 = os.getenv("API_KEY")
|
| 27 |
+
API_KEY_2 = os.getenv("GEMINI")
|
| 28 |
+
TASK = os.getenv("TASK")
|
| 29 |
+
client = genai.Client(api_key=API_KEY_2)
|
| 30 |
+
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 None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def translate(message):
|
| 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=SYSTEM),
|
| 69 |
+
contents=message
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
message_body = extract_json_from_response(response)
|
| 74 |
+
|
| 75 |
+
return message_body
|
| 76 |
+
|
| 77 |
+
except Exception as e:
|
| 78 |
+
logging.error(f"Error while translating message: {e}")
|
| 79 |
+
return {} # Return an empty dict in case of any unexpected errors
|
| 80 |
+
|
| 81 |
+
def gen_message(data_dict):
|
| 82 |
+
logging.info(data_dict)
|
| 83 |
+
if not data_dict['symptoms'] or not data_dict['diseases']:
|
| 84 |
+
message_body = f"""
|
| 85 |
+
Hi there, I'm Med-AI-Care, your virtual health assistant.
|
| 86 |
+
|
| 87 |
+
I understood your message as:
|
| 88 |
+
**"{data_dict['translation']}"**
|
| 89 |
+
|
| 90 |
+
Thank you for reaching out. Right now, I couldn't detect specific symptoms or conditions based on your message. But you're not alone — it's okay to feel unsure, and I'm still here to support you.
|
| 91 |
+
|
| 92 |
+
**My Analysis**:
|
| 93 |
+
{data_dict['analysis']}
|
| 94 |
+
|
| 95 |
+
**Recommendation**:
|
| 96 |
+
{data_dict['recommendation']}
|
| 97 |
+
|
| 98 |
+
I'm an AI assistant, not a doctor. For any health concern, please consult a licensed medical professional.
|
| 99 |
+
|
| 100 |
+
Take care, and feel free to share more if you'd like me to help further.
|
| 101 |
+
""".replace("*","\n")
|
| 102 |
+
else:
|
| 103 |
+
message_body = f"""
|
| 104 |
+
Hi there, I'm Med-AI-Care, your virtual health assistant.
|
| 105 |
+
|
| 106 |
+
You said:
|
| 107 |
+
**"{data_dict['translation']}"**
|
| 108 |
+
|
| 109 |
+
Here are the symptoms I picked up:
|
| 110 |
+
**{', '.join(data_dict['symptoms']).capitalize()}**
|
| 111 |
+
|
| 112 |
+
Possible conditions based on your symptoms:
|
| 113 |
+
{chr(10).join([f"- {disease}: {likelihood}" for disease, likelihood in data_dict['diseases'].items()])}
|
| 114 |
+
|
| 115 |
+
**My Analysis**:
|
| 116 |
+
{data_dict['analysis']}
|
| 117 |
+
|
| 118 |
+
📝 **Recommendation**:
|
| 119 |
+
{data_dict['recommendation']}
|
| 120 |
+
|
| 121 |
+
I'm just an AI helper — not a doctor. Please follow up with a healthcare professional for proper diagnosis and treatment.
|
| 122 |
+
|
| 123 |
+
Thanks for reaching out. I'm here if you need more help.
|
| 124 |
+
""".replace("*","\n")
|
| 125 |
+
|
| 126 |
+
return message_body
|
| 127 |
+
|
| 128 |
+
def chat(cmd):
|
| 129 |
+
client = Groq(api_key=API_KEY_1)
|
| 130 |
+
completion = client.chat.completions.create(
|
| 131 |
+
model="meta-llama/llama-4-scout-17b-16e-instruct",
|
| 132 |
+
messages=[
|
| 133 |
+
{
|
| 134 |
+
"role": "system",
|
| 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 |
+
if not in_block:
|
| 160 |
+
in_block = True
|
| 161 |
+
else:
|
| 162 |
+
break
|
| 163 |
+
elif in_block and line.strip().lower() != "json":
|
| 164 |
+
result+=line
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
try:
|
| 168 |
+
result_json = json.loads(result)
|
| 169 |
+
print(result_json)
|
| 170 |
+
lang = result_json["input_lang"]
|
| 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 |
+
print("Failed to parse JSON:", e)
|
| 179 |
+
output,data_dict,message_body = chat(cmd)
|
| 180 |
+
|
| 181 |
+
return output,data_dict,message_body
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
bot_token = "7952675957:AAEQFfIjzTqVdntOsUPRXW62UusPc0zFGLo"
|
| 185 |
+
|
| 186 |
+
# /start command
|
| 187 |
+
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 188 |
+
welcome_message = """
|
| 189 |
+
Hello! 👋 Welcome to Med-AI-Care, your trusted virtual health assistant.
|
| 190 |
+
|
| 191 |
+
Our mission is to provide you with intelligent, personalized, and data-driven insights to help you better understand your health. By analyzing the symptoms you share, we aim to offer thoughtful analysis and recommend possible next steps tailored just for you.
|
| 192 |
+
|
| 193 |
+
Whenever you're ready, just tell me about how you're feeling, and we'll start your health assessment together.
|
| 194 |
+
|
| 195 |
+
Remember, while I’m here to guide you, this is an AI-powered assistant and not a substitute for professional medical advice. For urgent or serious concerns, please consult a healthcare professional.
|
| 196 |
+
|
| 197 |
+
Let’s take this step toward better health—together! 💙
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
await context.bot.send_message(chat_id=update.effective_chat.id, text = welcome_message)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
# Handle regular text messages
|
| 205 |
+
async def query(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 206 |
+
message = update.message.text
|
| 207 |
+
output,data,message_body = chat(message)
|
| 208 |
+
await context.bot.send_message(chat_id=update.effective_chat.id, text=message_body)
|
| 209 |
+
|
| 210 |
+
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 211 |
+
# Log the error or send it to your logging system
|
| 212 |
+
print(f"Exception while handling an update: {context.error}")
|
| 213 |
+
|
| 214 |
+
# Optional: Notify the user
|
| 215 |
+
if isinstance(update, Update) and update.effective_chat:
|
| 216 |
+
await context.bot.send_message(chat_id=update.effective_chat.id,
|
| 217 |
+
text="Server Busy. Please Try Again Later.")
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
# --- Flask App Initialization ---
|
| 221 |
+
app = Flask(__name__)
|
| 222 |
+
|
| 223 |
+
@app.route("/", methods=["GET"])
|
| 224 |
+
def home():
|
| 225 |
+
|
| 226 |
+
return "ConvNeXt Skin Disease Prediction API. Use POST to /predict with an image file."
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
application = ApplicationBuilder().token(bot_token).build()
|
| 230 |
+
|
| 231 |
+
application.add_handler(CommandHandler('start', start))
|
| 232 |
+
application.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), query))
|
| 233 |
+
application.add_error_handler(error_handler)
|
| 234 |
+
application.run_polling()
|
| 235 |
+
|
requirements.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
flask
|
| 2 |
+
gunicorn
|
| 3 |
+
torch
|
| 4 |
+
torchvision
|
| 5 |
+
Pillow
|
| 6 |
+
huggingface_hub
|
| 7 |
+
numpy
|
| 8 |
+
groq
|
| 9 |
+
twilio
|
| 10 |
+
python-telegram-bot
|
| 11 |
+
transformers
|
| 12 |
+
google-genai
|