async def test_eval_start(self):
     try:
         async_session = WolframLanguageAsyncSession(
             kernel_path, kernel_loglevel=logging.INFO)
         res = await async_session.evaluate(wl.Plus(1, 1))
         self.assertTrue(res, 2)
     finally:
         if async_session:
             await async_session.terminate()
async def main():
    async with WolframLanguageAsyncSession() as async_session:
        start = time.perf_counter()
        print('Starting two tasks sequentially.')
        result1 = await delayed_evaluation(1, async_session, wl.Range(3))
        # Compute the Total of the previous evaluation result:
        result2 = await delayed_evaluation(1, async_session, wl.Total(result1))
        print('After %.02fs, both evaluations finished returning: %s, %s' %
              (time.perf_counter() - start, result1, result2))
 async def test_pool_from_one_kernel(self):
     await self.pool.terminate()
     session = WolframLanguageAsyncSession(kernel_path)
     async with WolframEvaluatorPool(session,
                                     kernel_loglevel=logging.INFO,
                                     STARTUP_TIMEOUT=5,
                                     TERMINATE_TIMEOUT=3) as pool:
         await self._pool_evaluation_check(pool)
     self.assertFalse(session.started)
     self.assertTrue(session.stopped)
Exemplo n.º 4
0
async def main():
    async with WolframLanguageAsyncSession() as async_session:
        start = time.perf_counter()
        print('Running two tasks concurrently.')
        task1 = asyncio.ensure_future(
            delayed_evaluation(1, async_session, '"hello"'))
        task2 = asyncio.ensure_future(
            delayed_evaluation(1, async_session, '"world!"'))
        # wait for the two tasks to finish
        result1 = await task1
        result2 = await task2
        print('After %.02fs, both evaluations finished returning: %s, %s' %
              (time.perf_counter() - start, result1, result2))
Exemplo n.º 5
0
def create_session(path=None,
                   poolsize=1,
                   inputform_string_evaluation=False,
                   **opts):
    if poolsize <= 1:
        return WolframLanguageAsyncSession(
            path,
            inputform_string_evaluation=inputform_string_evaluation,
            **opts)
    return WolframEvaluatorPool(
        path,
        poolsize=poolsize,
        inputform_string_evaluation=inputform_string_evaluation,
        **opts)
Exemplo n.º 6
0
 async def test_pool_from_mixed_kernel_cloud_path(self):
     await self.pool.terminate()
     sessions = (WolframCloudAsyncSession(
         credentials=secured_authentication_key,
         server=server), WolframLanguageAsyncSession(self.KERNEL_PATH),
                 self.KERNEL_PATH)
     async with WolframEvaluatorPool(sessions,
                                     kernel_loglevel=logging.INFO,
                                     STARTUP_TIMEOUT=5,
                                     TERMINATE_TIMEOUT=3) as pool:
         await self._pool_evaluation_check(pool)
     for session in sessions:
         if not isinstance(session, six.string_types):
             self.assertFalse(session.started)
             self.assertTrue(session.stopped)
def create_session(path=None,
                   poolsize=1,
                   inputform_string_evaluation=False,
                   kernel_loglevel=logging.INFO,
                   **opts):
    if poolsize <= 1:
        return WolframLanguageAsyncSession(
            path,
            inputform_string_evaluation=inputform_string_evaluation,
            kernel_loglevel=kernel_loglevel,
            **opts)
    return WolframEvaluatorPool(
        path,
        poolsize=poolsize,
        inputform_string_evaluation=inputform_string_evaluation,
        kernel_loglevel=kernel_loglevel,
        **opts)
Exemplo n.º 8
0
async def bark(ctx,*, script):
    # Prepares the user input to be passed into Wolfram functions that export the output image, and limit the time of the computation 
    async with ctx.typing():
        begin = f'Export["{img_path}", TimeConstrained[Style['
        end = ', Large], 60, "Your computation has exceeded one minute."]]'
        export = begin + script + end

        async with WolframLanguageAsyncSession(kernel_path) as session:
            #await session.start()
            try:
                eval = await session.evaluate_wrap(wlexpr(export))

                # Check for errors before sending result
                log = str(eval.messages)

                if len(log) > 256:
                    #log = log[0 : 255 : 1] # Shorten length of string to 255 characters to satify discord embed char limit
                    log = 'Errors were detected during computation'
                if log != 'None':
                    if (log).startswith('(\'Invalid syntax'):
                        log = createEmbed('Invalid syntax!')
                        await ctx.send(embed = log)
                    else:
                        log = createEmbed(log)
                        enlarge()
                        await ctx.send(file=discord.File(img_path))
                        await ctx.send(embed = log) 
                else:
                    # No errors, continue
                    if not enlarge():
                        await ctx.send('Not enough memory to perform this operation!')
                    
                    # Send image from Wolfram calculation results
                    await ctx.send(file=discord.File(img_path))
            except TimeoutError:
                log = createEmbed('Timeout Error: Computation took too long!')
                await ctx.send(embed = log)

            # Send Goodbye Embed message
            end_message = discord.Embed(
                title = f'**Learn more the about Wolfram Language**',
                color = discord.Color.blue(),
                description = f'Requested by\n{ctx.message.author.mention}',
                url = 'https://reference.wolfram.com/language/')
            end_message.set_thumbnail(url = 'https://media1.tenor.com/images/ed4da9a1bdbd4ff952638b19afa96506/tenor.gif?itemid=12660466')
            await ctx.send(embed = end_message)
 def setUpClass(cls):
     cls.async_session = WolframLanguageAsyncSession(
         kernel_path, kernel_loglevel=logging.INFO)
     cls.async_session.set_parameter("STARTUP_TIMEOUT", 5)
     cls.async_session.set_parameter("TERMINATE_TIMEOUT", 3)
     LOOP.run_until_complete(cls.async_session.start())
Exemplo n.º 10
0

# Enlarges image output from Wolfram calculation, and then saves as png #
def enlarge():
    img = Image.open(img_path, 'r')
    img_w, img_h = img.size

    background = Image.new('RGB', (img_w + 25, img_h + 25),
                           (255, 255, 255, 255))
    bg_w, bg_h = background.size
    background.paste(img, (13, 12))
    final = PIL.ImageOps.invert(background)
    final.save(img_path)


session = WolframLanguageAsyncSession(kernel_path)
session.start()


class Bark(commands.Cog):
    def __init__(self, client):
        self.client = client

    #### Commands ####

    # Echo
    @commands.command()
    @commands.has_any_role('Owners', 'Moderator', 'Admin')
    async def echo(
            self, ctx, *,
            message):  ## Repeats message given by user calling the command
Exemplo n.º 11
0
 def setupKernelSession(cls):
     cls.async_session = WolframLanguageAsyncSession(
         cls.KERNEL_PATH, kernel_loglevel=logging.INFO)
     cls.async_session.set_parameter('STARTUP_TIMEOUT', 5)
     cls.async_session.set_parameter('TERMINATE_TIMEOUT', 3)
     LOOP.run_until_complete(cls.async_session.start())
Exemplo n.º 12
0
async def session(ctx):

    async with ctx.typing():
        channel = ctx.message.channel
        def check(m):
            return m.channel == channel and ((m.content).startswith('wl ') or (m.content).startswith('```wl ')) and m.author == ctx.message.author

    async with WolframLanguageAsyncSession(kernel_path) as session:

        async with ctx.typing():
            # Start Asynchronous Wolfram Kernel thread #
            await session.start()
            # Tell user that the session has successfully started
            start_alert = discord.Embed(
                title = f'**Wolfram Session Started!**',
                color = discord.Color.blue(),
                description = f'Initiated by\n{ctx.message.author.mention}')
            await ctx.send(embed = start_alert)

        # Prepares the user input to be passed into Wolfram functions that export the output image, and limit the time of the computation 
        begin = f'Export["{img_path}", TimeConstrained['
        end = ', 60, "Your computation has exceeded one minute."]]'

        # Wait for discord user to enter input, and save message to msg.
        msg = await client.wait_for('message', check = check)

        # save string from message object to a string variable
        wolfcommand = msg.content 
        if wolfcommand.startswith('wl '):
            wolfcommand = wolfcommand.replace('wl ', '')
        elif wolfcommand.startswith('```wl '):
            wolfcommand = wolfcommand.replace('```', '')
            wolfcommand = wolfcommand.replace('wl ', '')
        #wolfcommand = wolfcommand.replace('wl ', '')

        # concatenate the full command for passing to Wolfram
        export = begin + wolfcommand + end 


        # Loop session, sending output from initial input, taking in new input, repeat.
        while msg.content != 'wl exit' and msg.content != '```wl exit' :
            if msg.content != 'wl exit' and msg.content != '```wl exit':
                try:
                    async with ctx.typing():
                        await session.evaluate(wlexpr(export))
                        # if not enlarge():
                        #     await ctx.send('Not enough memory to perform this operation!')
                        try:
                            await asyncio.wait_for(enlarge(), 5) # Time out image processing at 10 seconds
                        except Exception:
                            log = createEmbed('Timeout Error: Computation took too long!')
                            await ctx.send(embed = log)
                            # Send image from Wolfram calculation results
                            await ctx.send(file=discord.File(img_path))
                    
                    # Wait for new input from user
                    msg = await client.wait_for('message', check = check)
                    wolfcommand = msg.content 
                    if wolfcommand.startswith('wl '):
                        wolfcommand = wolfcommand.replace('wl ', '')
                    elif wolfcommand.startswith('```wl '):
                        wolfcommand = wolfcommand.replace('```', '')
                        wolfcommand = wolfcommand.replace('wl ', '')
                    export = begin + wolfcommand + end
                except WolframLanguageException as err:
                    error = err
                    await ctx.send(error)

        # Loop seninent value detected, closes connection to wolfram kernel
        await session.stop()

    # Send Embed message for end of session #
    end_message = discord.Embed(
        title = f'**Wolfram session terminated!**',
        color = discord.Color.blue(),
        description = f'Session started by\n{ctx.message.author.mention}')
    await ctx.send(embed = end_message)