File size: 5,518 Bytes
08bc52f
a4a35d8
b54977e
 
a4a35d8
 
 
 
 
c015fd4
 
 
a4a35d8
197f492
bdf7057
 
 
 
197f492
 
c33b262
a4a35d8
197f492
 
927848d
7faa9af
bdf7057
 
 
a4a35d8
 
197f492
 
b54977e
927848d
 
 
 
 
 
 
6f82744
927848d
 
6f82744
927848d
 
 
 
 
 
 
 
6f82744
927848d
 
 
 
6f82744
927848d
 
 
08bc52f
197f492
 
 
 
e9dba00
 
 
33d3a46
eff335b
33d3a46
 
 
 
 
 
 
197f492
927848d
197f492
 
 
 
d562426
 
 
197f492
9754a84
017b7a7
197f492
 
9754a84
017b7a7
 
a4a35d8
 
 
bdf7057
 
 
 
8688e31
a4a35d8
bdf7057
 
 
 
a4a35d8
bdf7057
a4a35d8
 
 
 
 
 
 
 
 
 
 
 
 
bdf7057
 
 
197f492
05d53db
d686cc9
a4a35d8
 
 
 
 
 
d686cc9
a4a35d8
197f492
 
 
 
7faa9af
a4a35d8
 
bdf7057
 
 
 
 
 
 
 
 
a4a35d8
c33b262
7faa9af
197f492
 
 
 
 
6f82744
 
197f492
1af6a6a
197f492
 
a4a35d8
 
 
 
 
927848d
6f82744
a4a35d8
80c38e5
33d3a46
a074264
eff335b
c90742c
80c38e5
c90742c
 
 
78ab3ee
80c38e5
7faa9af
8189ef8
8018fb1
6f82744
 
7faa9af
0bf7d6b
179556e
db6195c
 
 
 
 
179556e
db6195c
a4a35d8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
"""Talk to spaces VM via subprocess.check_output."""
# pylint: disable=wrong-import-position

from typing import Optional, Tuple
import sys
from pathlib import Path
if "." not in sys.path:
    sys.path.insert(0, ".")

# import httpx
import subprocess as sp
from shlex import split
import pandas as pd

import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns

# from textwrap import dedent
from inspect import cleandoc
import gradio as gr
import logzero
from logzero import logger

# from gradiobee.seg_text import seg_text

matplotlib.use("Agg")  # non-interactive for plt.savefig
sns.set()
sns.set_style("darkgrid")
logzero.loglevel()  # default to 10


# def greet(command):
def process(command) -> Tuple[str, Optional[str]]:
    """Probe vm."""
    logger.info("input: %s", command)

    try:
        command = str(command).strip()
    except Exception as e:
        _ = str(e)
        return _

    if not command:
        return "gimme something to start with..."

    try:
        # out = sp.check_output(split(command), encoding="utf8", stderr=STDOUT)
        proc = sp.Popen(
            split(command), encoding="utf8", stdout=-1, stderr=-1
        )  # sp.PIPE: -1
        out, err = proc.communicate()
        # success = True
        return f"[{out}], [{err}]"
    except Exception as e:
        out, err = "", str(e)
        # success = False
        # return f"[{out}]", f"[{err}]"
        return f"[{out}], [{err}]"


def process1(command) -> Tuple[str, Optional[str]]:
    """Probe vm."""
    # single line: command
    # logger.info("input:\n\t %s", command)
    # print("print input:\n\t %s" % command)
    # print("print input*:\n\t %s" % "*".join(command.splitlines()))

    logger.info("input: %s", command)

    try:
        command = str(command).strip()
    except Exception as e:
        _ = str(e)
        return _, None

    if not command:
        return "gimme something to start with...", None

    is_command = True
    # is_command = command.strip().splitlines().__len__() < 2 and len(command.strip()) < 500

    if is_command:
        try:
            # out = sp.check_output(split(command), encoding="utf8", stderr=STDOUT)
            proc = sp.Popen(
                split(command), encoding="utf8", stdout=-1, stderr=-1
            )  # sp.PIPE: -1
            out, err = proc.communicate()
            # success = True
            return f"[{out}], [{err}]", None
        except Exception as e:
            out, err = "", str(e)
            # success = False
            # return f"[{out}]", f"[{err}]"
            return f"[{out}], [{err}]", None

    # quick test altair altair-save tooltip
    # from PIL import Image

    # import altair as alt
    # from altair_saver import save
    # alt.renderers.enable('altair_saver', fmts=['vega-lite', 'png'])

    df_ = pd.DataFrame(data={'x': [1, 2], 'y': [3, 4], "cos": [0.1, 0.5]})
    # chart_df = alt.Chart(df_).mark_circle(size=60).encode(
        # x='x',
        # y='y',
        # color='cos',
        # tooltip=['x', 'y', 'cos', ]
    # )
    # .interactive()

    # save(chart_df, "chart_df.html")
    # chart_df_html = Path("chart_df.html").read_text("utf")
    # save(chart_df, "chart_df.png")
    # chart_df_png = Path("chart_df.png").read_bytes()

    # chart_df_png = Image.open("chart_df.png")
    # chart_df_png = "chart_df.png"

    # scatter_plot.save('simple_scatter_plot_with_altairchart.html')
    # chart_df.save("chart_df.html")  # does not work, constains js
    # chart_df_html = Path("chart_df.html").read_text("utf")

    # chart_df.save("chart_df.png")  #
    # chart_df_png = "chart_df.png"

    # not is_command or not flag: text, do seg_text
    _ = "\n\n".join(seg_text(command.strip()))

    logger.debug(_)
    # logger.debug(chart_df_html)
    # print(_)
    # print(chart_df_html)

    # _ = seg_text(command.strip())
    _ = cleandoc(
        f"""seg_text output (segmented sents):
        {_}
        """
    ).strip()

    # return _, chart_df_html

    plt.figure()
    sns.scatterplot(data=df_, x='x', y='y')
    Path("img").mkdir(exist_ok=True)
    plt.savefig("img/df.png")
    plt.close()
    df_png = "img/df.png"

    # return _, chart_df_png
    return _, df_png


iface = gr.Interface(
    # fn=greet,
    # inputs="text",
    fn=process,
    # inputs="text",
    inputs=gr.inputs.Textbox(
    # inputs=gr.components.Textbox(
        lines=1,
        placeholder="Type or paste input here then click 'Submit'",
        default="python -V  # show version",
        label="command or multiline text",
    ),
    # outputs="text",
    # outputs=["text",],
    # outputs=["text", "html"],
    outputs=[
        "text",
        # gr.outputs.Image("auto"),
        # gr.outputs.Image('pil'),
    ],
    examples=[
        "python -m site",
        """python -c "import gradio; print(gradio.__version__")""",
        "python -V ",
        "cat /proc/version",
        "free  # show free memory",
        "uname -m",
        "df -h .",
        "cat /proc/cpuinfo",
        """python -c "from psutil import virtual_memory; print(virtual_memory())" """,
    ],
    title="probe the system",
    description="Talk to the system via subprocess.check_output ",
    # layout="vertical",
    # allow_flagging="manual",
    allow_flagging="never",
)

# iface.launch(share=True, debug=True)
# import platform
# logger.info("platform.node(): %s", platform.node())

# if 'amzn2' in platform.uname().__str__(): "huggingdace spaces"

iface.launch(share=False, debug=True)

# iface.launch()