arshy commited on
Commit
9f012c2
1 Parent(s): b7000e1

initial commit

Browse files
Files changed (3) hide show
  1. .gitignore +165 -0
  2. app.py +144 -0
  3. requirements.txt +2 -0
.gitignore ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
163
+
164
+ /flagged
165
+ naptha_output
app.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import asyncio
3
+ import gradio as gr
4
+ from PIL import Image
5
+ from dotenv import load_dotenv, find_dotenv
6
+ from naptha_sdk.client.naptha import Naptha
7
+ from naptha_sdk.user import generate_user
8
+ from naptha_sdk.schemas import ModuleRun
9
+
10
+ load_dotenv(find_dotenv())
11
+
12
+ async def run_module(module_name, prompt, selected_node):
13
+ user, _ = generate_user(os.getenv("PRIVATE_KEY"))
14
+ hub_url = os.getenv("HUB_URL")
15
+ hub_username = os.getenv("HUB_USER")
16
+ hub_password = os.getenv("HUB_PASS")
17
+
18
+ # Use the selected node
19
+ if selected_node == "node":
20
+ node_url = 'http://node.naptha.ai:7001'
21
+ elif selected_node == "node1":
22
+ node_url = 'http://node1.naptha.ai:7001'
23
+ else:
24
+ return None, f"Error: Invalid node selection: {selected_node}"
25
+
26
+ routing_url = os.getenv("ROUTING_URL", None)
27
+ indirect_node_id = os.getenv("INDIRECT_NODE_ID", None)
28
+ output_dir = './naptha_output'
29
+
30
+ if module_name == 'generate_image':
31
+ os.makedirs(output_dir, exist_ok=True)
32
+ for f in os.listdir(output_dir):
33
+ os.remove(os.path.join(output_dir, f))
34
+
35
+ naptha = await Naptha(
36
+ user=user,
37
+ hub_username=hub_username,
38
+ hub_password=hub_password,
39
+ hub_url=hub_url,
40
+ node_url=node_url,
41
+ routing_url=routing_url,
42
+ indirect_node_id=indirect_node_id,
43
+ )
44
+
45
+ module_run_input = {
46
+ 'consumer_id': naptha.user["id"],
47
+ "module_name": module_name,
48
+ 'worker_nodes': None,
49
+ "module_params": {
50
+ "prompt": prompt
51
+ },
52
+ }
53
+
54
+ print(f"Running module {module_name} on {selected_node} with parameters: {module_run_input}")
55
+
56
+ print("Checking user...")
57
+ user = await naptha.node.check_user(user_input=naptha.user)
58
+
59
+ if user["is_registered"]:
60
+ print("Found user...", user)
61
+ else:
62
+ print("No user found. Registering user...")
63
+ user = await naptha.node.register_user(user_input=user)
64
+ print(f"User registered: {user}.")
65
+
66
+ print("Running...")
67
+ module_run = await naptha.node.run_task(module_run_input)
68
+
69
+ if isinstance(module_run, dict):
70
+ module_run = ModuleRun(**module_run)
71
+
72
+ print(f"Module Run ID: {module_run.id}")
73
+ current_results_len = 0
74
+ while True:
75
+ module_run = await naptha.node.check_task(module_run)
76
+
77
+ if isinstance(module_run, dict):
78
+ module_run = ModuleRun(**module_run)
79
+
80
+ output = f"{module_run.status} {module_run.module_type} {module_run.module_name}"
81
+ if len(module_run.child_runs) > 0:
82
+ output += f", task {len(module_run.child_runs)} {module_run.child_runs[-1].module_name} (node: {module_run.child_runs[-1].worker_nodes[0]})"
83
+ print(output)
84
+
85
+ if len(module_run.results) > current_results_len:
86
+ print("Output: ", module_run.results[-1])
87
+ current_results_len += 1
88
+
89
+ if module_run.status in ['completed', 'error']:
90
+ break
91
+
92
+ await asyncio.sleep(3)
93
+
94
+ if module_run.status == 'completed':
95
+ results = module_run.results
96
+ print(f"Results: {results}")
97
+
98
+ if module_name == 'generate_image':
99
+ folder_id = module_run.id.split(":")[1]
100
+ image_path = f"{output_dir}/output.png"
101
+ await naptha.node.read_storage(folder_id.strip(), output_dir, ipfs=None)
102
+
103
+ if os.path.exists(image_path):
104
+ return image_path, None
105
+ else:
106
+ return None, "Image generation failed or image not found."
107
+ else: # chat
108
+ return None, results[-1] if results else "No output generated."
109
+ else:
110
+ error_message = module_run.error_message
111
+ print(f"Error: {error_message}")
112
+ return None, f"Error: {error_message}"
113
+
114
+ def gradio_wrapper(module, prompt, node):
115
+ image_path, text = asyncio.run(run_module(module, prompt, node))
116
+ if image_path:
117
+ return image_path, gr.update(visible=False)
118
+ elif text:
119
+ return gr.update(visible=False), text
120
+ else:
121
+ return gr.update(visible=False), gr.update(visible=False)
122
+
123
+ with gr.Blocks() as iface:
124
+ gr.Markdown("# Naptha Module Runner")
125
+ gr.Markdown("Run either the 'generate_image' or 'chat' module using Naptha on selected node.")
126
+
127
+ with gr.Row():
128
+ module = gr.Dropdown(["generate_image", "chat"], label="Module")
129
+ node = gr.Dropdown(["node", "node1"], label="Node")
130
+ prompt = gr.Textbox(label="Prompt")
131
+
132
+ with gr.Row():
133
+ image_output = gr.Image(label="Generated Image")
134
+ text_output = gr.Textbox(label="Chat Output")
135
+
136
+ submit_btn = gr.Button("Run")
137
+
138
+ submit_btn.click(
139
+ fn=gradio_wrapper,
140
+ inputs=[module, prompt, node],
141
+ outputs=[image_output, text_output]
142
+ )
143
+
144
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ git+https://github.com/napthaai/naptha-sdk.git#egg=naptha_sdk
2
+ gradio