import os from dotenv import dotenv_values import subprocess import sys sys.path.append('/path/to/python/openai/modules') # use 'pip show openai' to get the path from openai import OpenAI client = OpenAI( base_url = "https://integrate.api.nvidia.com/v1", api_key = "nvapi--" ) def update_status(message): """Update status message in LibreOffice using Zenity.""" progress_command = [ "zenity", "--progress", "--text=%s" % message, "--pulsate", "--auto-close", ] subprocess.Popen(progress_command) def granite(): doc = XSCRIPTCONTEXT.getDocument() selection = doc.getCurrentSelection() if selection.supportsService("com.sun.star.text.TextRanges"): total_ranges = len(selection) for i, textRange in enumerate(selection): message = f"Chamando a IBM Granite ..." update_status(message) prompt = textRange.getString() generated_text = f"IBM Granite responde: {prompt}" response = client.chat.completions.create( model="ibm/granite-34b-code-instruct", messages=[ { "role": "user", "content": generated_text, } ], temperature=0.5, top_p=1, max_tokens=1024, stream=True ) output_text = "" for chunk in response: if chunk.choices[0].delta.content is not None: output_text += chunk.choices[0].delta.content cursor = doc.getCurrentController().getViewCursor() docText = doc.Text # Set Selected Text as Title text = textRange.getString() text_with_newline = text + "\n" textRange.setString(text_with_newline) # Insert Open AI response to current document docText.insertString(cursor, output_text, False) # Apply styling textCursor = textRange.getText().createTextCursorByRange(textRange) textCursor.setPropertyValue("CharWeight", 150) # Close the Zenity progress dialog when processing is complete subprocess.run(["pkill", "zenity"]) else: return "Invalid selection"