|
| 1 | +import io |
| 2 | +import re |
| 3 | +import sys |
| 4 | +import json |
| 5 | +import tempfile |
| 6 | +import contextlib |
| 7 | +from aiohttp import ClientSession, ClientTimeout |
| 8 | + |
| 9 | +from dffml.cli.cli import CLI |
| 10 | +from dffml import op, config, Definition, BaseSecret |
| 11 | + |
| 12 | +ACCESSTOKEN = Definition(name="access_tok3n", primitive="str") |
| 13 | +ROOMNAME = Definition(name="room_name", primitive="str") |
| 14 | +ROOMID = Definition(name="room_id", primitive="str") |
| 15 | +MESSAGE = Definition(name="message", primitive="str") |
| 16 | +TOSEND = Definition(name="to_send", primitive="str") |
| 17 | + |
| 18 | + |
| 19 | +@config |
| 20 | +class GitterChannelConfig: |
| 21 | + secret: BaseSecret |
| 22 | + |
| 23 | + |
| 24 | +@op( |
| 25 | + inputs={"room_uri": ROOMNAME}, |
| 26 | + outputs={"room_id": ROOMID}, |
| 27 | + config_cls=GitterChannelConfig, |
| 28 | + imp_enter={ |
| 29 | + "secret": lambda self: self.config.secret, |
| 30 | + "session": lambda self: ClientSession(trust_env=True), |
| 31 | + }, |
| 32 | + ctx_enter={"sctx": lambda self: self.parent.secret()}, |
| 33 | +) |
| 34 | +async def get_room_id(self, room_uri): |
| 35 | + # Get unique roomid from room uri |
| 36 | + access_token = await self.sctx.get("access_token") |
| 37 | + headers = { |
| 38 | + "Content-Type": "application/json", |
| 39 | + "Accept": "application/json", |
| 40 | + "Authorization": f"Bearer {access_token}", |
| 41 | + } |
| 42 | + |
| 43 | + api_url = await self.sctx.get("api_url") |
| 44 | + url = f"{api_url}/rooms" |
| 45 | + async with self.parent.session.post( |
| 46 | + url, json={"uri": room_uri}, headers=headers |
| 47 | + ) as resp: |
| 48 | + response = await resp.json() |
| 49 | + return {"room_id": response["id"]} |
| 50 | + |
| 51 | + |
| 52 | +@op( |
| 53 | + inputs={"room_id": ROOMID}, |
| 54 | + outputs={"message": MESSAGE}, |
| 55 | + config_cls=GitterChannelConfig, |
| 56 | + imp_enter={ |
| 57 | + "secret": lambda self: self.config.secret, |
| 58 | + "session": lambda self: ClientSession( |
| 59 | + trust_env=True, timeout=ClientTimeout(total=None) |
| 60 | + ), |
| 61 | + }, |
| 62 | + ctx_enter={"sctx": lambda self: self.parent.secret()}, |
| 63 | +) |
| 64 | +async def stream_chat(self, room_id): |
| 65 | + # Listen to messages in room |
| 66 | + access_token = await self.sctx.get("access_token") |
| 67 | + headers = { |
| 68 | + "Accept": "application/json", |
| 69 | + "Authorization": f"Bearer {access_token}", |
| 70 | + } |
| 71 | + stream_url = await self.sctx.get("stream_url") |
| 72 | + |
| 73 | + url = f"{stream_url}/rooms/{room_id}/chatMessages" |
| 74 | + botname = await self.sctx.get("botname") |
| 75 | + |
| 76 | + async with self.parent.session.get(url, headers=headers) as resp: |
| 77 | + async for data in resp.content: |
| 78 | + # Gitter sends " \n" at some intervals |
| 79 | + if data == " \n".encode(): |
| 80 | + continue |
| 81 | + print(f"\n\n Got data {data} \n\n") |
| 82 | + data = json.loads(data.strip()) |
| 83 | + message = data["text"] |
| 84 | + # Only listen to messages directed to bot |
| 85 | + if f"@{botname}" not in message: |
| 86 | + continue |
| 87 | + yield {"message": message} |
| 88 | + |
| 89 | + |
| 90 | +@op( |
| 91 | + inputs={"message": TOSEND, "room_id": ROOMID}, |
| 92 | + config_cls=GitterChannelConfig, |
| 93 | + imp_enter={ |
| 94 | + "secret": lambda self: self.config.secret, |
| 95 | + "session": lambda self: ClientSession(trust_env=True), |
| 96 | + }, |
| 97 | + ctx_enter={"sctx": lambda self: self.parent.secret()}, |
| 98 | +) |
| 99 | +async def send_message(self, message, room_id): |
| 100 | + access_token = await self.sctx.get("access_token") |
| 101 | + headers = { |
| 102 | + "Content-Type": "application/json", |
| 103 | + "Accept": "application/json", |
| 104 | + "Authorization": f"Bearer {access_token}", |
| 105 | + } |
| 106 | + try: |
| 107 | + message = json.loads(message) |
| 108 | + message = json.dumps(message, indent=4, sort_keys=True) |
| 109 | + except: |
| 110 | + pass |
| 111 | + |
| 112 | + # For new line we need \\n,else Gitter api |
| 113 | + # responds with 'Bad Request' |
| 114 | + message = message.replace("\n", "\\n") |
| 115 | + api_url = await self.sctx.get("api_url") |
| 116 | + url = f"{api_url}/rooms/{room_id}/chatMessages" |
| 117 | + |
| 118 | + async with self.parent.session.post( |
| 119 | + url, headers=headers, json={"text": message} |
| 120 | + ) as resp: |
| 121 | + response = await resp.json() |
| 122 | + return |
| 123 | + |
| 124 | + |
| 125 | +@op( |
| 126 | + inputs={"message": MESSAGE,}, |
| 127 | + outputs={"message": TOSEND}, |
| 128 | + config_cls=GitterChannelConfig, |
| 129 | + imp_enter={"secret": lambda self: self.config.secret}, |
| 130 | + ctx_enter={"sctx": lambda self: self.parent.secret()}, |
| 131 | +) |
| 132 | +async def interpret_message(self, message): |
| 133 | + greet = ["hey", "hello", "hi"] |
| 134 | + for x in greet: |
| 135 | + if x in message.lower(): |
| 136 | + return {"message": "Hey Hooman ฅ^•ﻌ•^ฅ"} |
| 137 | + |
| 138 | + def extract_data(raw_data): |
| 139 | + raw_data = raw_data.split("data:") |
| 140 | + data = {"model-data": raw_data[1]} |
| 141 | + raw_data = raw_data[0].split("\n") |
| 142 | + for x in raw_data: |
| 143 | + k, *v = x.split(":") |
| 144 | + if isinstance(v, list): # for features |
| 145 | + v = ":".join(v) |
| 146 | + k = k.strip() |
| 147 | + v = v.strip() |
| 148 | + if k: # avoid blank |
| 149 | + data[k] = v |
| 150 | + return data |
| 151 | + |
| 152 | + # Removing username from message |
| 153 | + # The regex matches @ followed by anything that |
| 154 | + # is not a whitespace in the first group and |
| 155 | + # the rest of the string in the second group. |
| 156 | + # We replace the string by the second group. |
| 157 | + message = re.sub(r"(@[^\s]+)(.*)", r"\2", message).strip() |
| 158 | + |
| 159 | + if message.lower().startswith("train model"): |
| 160 | + return {"message": "Gimme more details!!"} |
| 161 | + |
| 162 | + elif message.lower().startswith("predict:"): |
| 163 | + # Only replace first occurence of predict |
| 164 | + # because the feature to predict will be labeled predict |
| 165 | + raw_data = message.replace("predict:", "", 1).strip() |
| 166 | + cmds = ["predict", "all"] |
| 167 | + |
| 168 | + elif message.lower().startswith("details:"): |
| 169 | + raw_data = message.replace("details:", "",).strip() |
| 170 | + cmds = ["train"] |
| 171 | + |
| 172 | + else: |
| 173 | + return {"message": " Oops ,I didnt get that ᕙ(⇀‸↼‶)ᕗ "} |
| 174 | + |
| 175 | + # If predict or train, extract data |
| 176 | + data = extract_data(raw_data) |
| 177 | + if "model-type" in data: |
| 178 | + model_type = data["model-type"] |
| 179 | + if "model-name" in data: |
| 180 | + model_name = data["model-name"] |
| 181 | + else: |
| 182 | + model_name = "mymodel" |
| 183 | + |
| 184 | + features = data["features"].split(" ") |
| 185 | + predict = data["predict"] |
| 186 | + model_data = data["model-data"] |
| 187 | + |
| 188 | + with tempfile.NamedTemporaryFile(suffix=".csv") as fileobj: |
| 189 | + fileobj.write(model_data.lstrip().encode()) |
| 190 | + fileobj.seek(0) |
| 191 | + |
| 192 | + stdout = io.StringIO() |
| 193 | + with contextlib.redirect_stdout(stdout): |
| 194 | + preds = await CLI.cli( |
| 195 | + *cmds, |
| 196 | + "-model", |
| 197 | + model_type, |
| 198 | + "-model-directory", |
| 199 | + model_name, |
| 200 | + "-model-features", |
| 201 | + *features, |
| 202 | + "-model-predict", |
| 203 | + predict, |
| 204 | + "-sources", |
| 205 | + "f=csv", |
| 206 | + "-source-filename", |
| 207 | + fileobj.name, |
| 208 | + ) |
| 209 | + sys.stdout.flush() |
| 210 | + |
| 211 | + if "train" in cmds: |
| 212 | + return {"message": "Done!!"} |
| 213 | + else: |
| 214 | + m = {} |
| 215 | + for pred in preds: |
| 216 | + pred = pred.predictions() |
| 217 | + m.update({p: pred[p]["value"] for p in pred}) |
| 218 | + message = [f"{k}: {v}" for k, v in m.items()] |
| 219 | + message = "\n".join(message) |
| 220 | + return {"message": message} |
0 commit comments