Advertisement
icarussiano

Untitled

Mar 26th, 2024 (edited)
582
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.49 KB | None | 0 0
  1. import html
  2. import logging
  3. import urllib.parse
  4. from uuid import uuid4
  5. import requests
  6. import wolframalpha
  7. from more_itertools import peekable
  8. from telegram import InlineQueryResultArticle, InputTextMessageContent, Update, InlineQueryResultPhoto
  9. from telegram.constants import ParseMode
  10. from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, InlineQueryHandler
  11. from telegram.helpers import mention_html
  12. import os
  13. import vertexai
  14. from vertexai.generative_models import GenerativeModel, Part
  15.  
  16. os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/home/Icarussiano/provagemini-417819.json'
  17. #setup Gemini
  18. project_id = "provagemini-417819"
  19. location = "us-central1"
  20. vertexai.init(project=project_id, location=location)
  21. model = GenerativeModel("gemini-1.0-pro")
  22.  
  23. #setup logger
  24. logging.basicConfig(
  25.     format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
  26. )
  27. # set higher logging level for httpx to avoid all GET and POST requests being logged
  28. logging.getLogger("httpx").setLevel(logging.WARNING)
  29. logger = logging.getLogger(__name__)
  30.  
  31. TOKEN = os.getenv('TOKEN')
  32. appid = os.getenv('API_key')
  33. wolfram_client = wolframalpha.Client(appid)
  34.  
  35.  
  36. async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
  37.     """Send a message when the command /start is issued."""
  38.     user_id = update.effective_user.id
  39.     name = update.effective_user.full_name
  40.     menzione = mention_html(user_id, name)
  41.     await update.message.reply_html(
  42.         f"Ciao {menzione}! Sono un bot che ti aiuta a rispondere alle domande usando WolframAlpha. Scrivi /help per "
  43.         f"sapere come usarmi.")
  44.  
  45.  
  46. async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
  47.     """Send a message when the command /help is issued."""
  48.     help_text = "Puoi usare i seguenti comandi:\n\n"
  49.     help_text += "/short <query>: Risponderò usando l'API short answers di WolframAlpha\n"
  50.     help_text += "/img <query>: Risponderò con l'immagine del risultato di WolframAlpha\n"
  51.     help_text += ("/query <query>: Risponderò in modo dettagliato, riportando tutte le informazioni testuali "
  52.                   "disponibili\n")
  53.     help_text += "\nPuoi anche usare il bot inline, scrivendo @simplewolframbot <query> ;"
  54.     await update.message.reply_text(help_text)
  55.  
  56.  
  57. async def simple_query(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
  58.     """Handle the /simple command. This is run when you type: /simple <query>"""
  59.     query = ' '.join(update.message.text.split()[1:])
  60.     query_url = urllib.parse.quote_plus(query)
  61.     short_url = f"http://api.wolframalpha.com/v1/result?appid={appid}&i={query_url}"
  62.     res = requests.get(short_url).text
  63.     await update.message.reply_text(res)
  64.  
  65.  
  66. async def img(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
  67.     """Handle the /img command. This is run when you type: /img <query>"""
  68.     query = ' '.join(update.message.text.split()[1:])
  69.     query_url = urllib.parse.quote_plus(query)
  70.     photo_url = f"http://api.wolframalpha.com/v1/simple?appid={appid}&i={query_url}"
  71.     res = requests.get(photo_url)
  72.     with open('output.png', 'wb') as f:
  73.         f.write(res.content)
  74.     await update.message.reply_photo(open('output.png', 'rb'))
  75.  
  76.  
  77. async def reply_query(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
  78.     """Handle the /query command. This is run when you type: /query <query>"""
  79.     query = ' '.join(update.message.text.split()[1:])
  80.     res = wolfram_client.query(query)
  81.     result_text = ""
  82.     if peekable(res.results):
  83.         for pod in res.results:
  84.             for subpod in pod.subpods:
  85.                 result_text += f"{subpod.plaintext}\n"
  86.     else:
  87.         for pod in res.pods:
  88.             result_text += f"\n{pod.title}\n"
  89.             for subpod in pod.subpods:
  90.                 result_text += f"{subpod.plaintext}\n"
  91.     if len(result_text) > 4096:
  92.         result_text = result_text[:4096]
  93.     await update.message.reply_text(result_text)
  94.  
  95.  
  96. async def inline_query(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
  97.     """Handle the inline query. This is run when you type: @simplewolframbot <query>"""
  98.     query = update.inline_query.query
  99.     if not query:  # empty query should not be handled
  100.         return
  101.     elif ';' in query:
  102.         query = query[:-1]
  103.         query_url = urllib.parse.quote_plus(query)
  104.         photo_url = f"http://api.wolframalpha.com/v1/simple?appid={appid}&i={query_url}"
  105.         res = wolfram_client.query(query)
  106.         result_text = ""
  107.         if peekable(res.results):
  108.             for pod in res.results:
  109.                 for subpod in pod.subpods:
  110.                     if subpod.plaintext:
  111.                         result_text += f"{html.escape(subpod.plaintext)}\n"
  112.         else:
  113.             for pod in res.pods:
  114.                 result_text += f"\n<b>{pod.title}</b>\n"
  115.                 length = len(f"\n<b>{pod.title}</b>\n")
  116.                 for subpod in pod.subpods:
  117.                     if subpod.plaintext:
  118.                         result_text += f"{html.escape(subpod.plaintext)}\n"
  119.                     else:
  120.                         result_text = result_text[:-length]
  121.  
  122.         short_url = f"http://api.wolframalpha.com/v1/result?appid={appid}&i={query_url}"
  123.         req = requests.get(short_url).text
  124.         message = InputTextMessageContent(f"<b>{html.escape(query)}</b> \n{result_text}", parse_mode=ParseMode.HTML)
  125.         rapido = InputTextMessageContent(f"<b>{html.escape(query)}</b> \n{html.escape(req)}", parse_mode=ParseMode.HTML)
  126.         if len(message.message_text) > 4096:
  127.             message = InputTextMessageContent(message.message_text[:4096], parse_mode=ParseMode.HTML)
  128.         if len(rapido.message_text) > 4096:
  129.             rapido = InputTextMessageContent(rapido.message_text[:4096], parse_mode=ParseMode.HTML)
  130.         latex = f"Convert the following text in LaTex inline expression. Answer only with the LaTex code delimited by dollar sign. \nText: {query}={result_text}"
  131.         responses = model.generate_content(latex, stream=True)
  132.         latex_text = ''.join([response.text for response in responses])
  133.         #latex_text = responses.text
  134.         latex_text = latex_text.lstrip('$')
  135.         latex_text = latex_text.rstrip('$')
  136.         latex_text = f"${latex_text}$"
  137.  
  138.         results = [
  139.             InlineQueryResultArticle(
  140.                 id=str(uuid4()),
  141.                 title="Risposta rapida",
  142.                 input_message_content=rapido,
  143.             ),
  144.             InlineQueryResultArticle(
  145.                 id=str(uuid4()),
  146.                 title="Risposta testuale completa",
  147.                 input_message_content=message,
  148.             ),
  149.             InlineQueryResultArticle(
  150.                 id=str(uuid4()),
  151.                 title="LaTeX(sperimental)",
  152.                 input_message_content=InputTextMessageContent(latex_text, parse_mode=ParseMode.HTML),
  153.             ),
  154.             InlineQueryResultPhoto(
  155.                 id=str(uuid4()),
  156.                 title="Immagine",
  157.                 photo_url=photo_url,
  158.                 thumbnail_url=photo_url,
  159.             ),
  160.  
  161.         ]
  162.  
  163.         await update.inline_query.answer(results)
  164.  
  165.  
  166. app = ApplicationBuilder().token(TOKEN).build()
  167. app.add_handler(CommandHandler("query", reply_query))
  168. app.add_handler(CommandHandler("start", start))
  169. app.add_handler(CommandHandler("help", help_command))
  170. app.add_handler(CommandHandler("img", img))
  171. app.add_handler(CommandHandler("short", simple_query))
  172. app.add_handler(InlineQueryHandler(inline_query))
  173. app.run_polling()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement