chaos4455 commited on
Commit
89c7b66
·
verified ·
1 Parent(s): 3fbd71c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -131
app.py CHANGED
@@ -2,13 +2,13 @@ import streamlit as st
2
  import google.generativeai as genai
3
  import re
4
  import os
5
- import platform
6
 
7
  # Secret key and Google Gemini API configuration
8
  API_KEY = st.secrets["GOOGLE_API_KEY"]
9
 
10
  # Page configuration
11
- st.set_page_config(page_title="🐍✨ Gemini2 Pip Gen Pro", page_icon="🐍✨", layout="wide")
12
 
13
  # --- Helper Functions ---
14
  def send_message_to_model(message, model_name, temperature, top_p, top_k, max_tokens):
@@ -33,82 +33,64 @@ def send_message_to_model(message, model_name, temperature, top_p, top_k, max_to
33
  st.error(f"❌ Error communicating with the AI: {e}")
34
  return None
35
 
36
- def generate_pip_command(prompt_base, model_name, temperature, top_p, top_k, max_tokens, selected_libraries, selected_groups, custom_requirements, specific_details, pip_options, target_os):
37
- """Generates a pip command based on user settings."""
38
  prompt = f"""
39
- You are an expert Python development assistant. Your task is to generate a complete and efficient pip command based on the following description:
40
 
41
- **Goal:** Create the most complete, detailed, and efficient pip install command possible, considering all variables, edge cases, and potential scenarios.
42
-
43
- **Target Operating System:** {target_os}
44
 
45
- **Command Description:** {prompt_base}
46
 
47
- **Selected Libraries:** {selected_libraries if selected_libraries else "None"}
48
- **Selected Groups:** {selected_groups if selected_groups else "None"}
 
49
  **Custom Requirements:** {custom_requirements if custom_requirements else "None"}
50
  **Specific Details:** {specific_details if specific_details else "None"}
51
- **Pip Options:** {pip_options if pip_options else "None"}
52
 
53
  **Response Format:**
54
- - Respond in Markdown format, including a pip command code block, a bash code block and powershell code block with its original formatting, without line breaks.
55
- - The pip command code block must be delimited by ```pip and ```.
56
- - The bash code block must be delimited by ```bash and ```.
57
- - The powershell code block must be delimited by ```powershell and ```.
58
- - Do not include comments, explanations, or any other text outside the code block.
59
  - The code must maintain its full vertical formatting, respecting indentation and line breaks.
 
60
  - Explore different approaches, techniques, and advanced practices, always prioritizing security and efficiency.
61
- - Use advanced pip resources such as version constraints, index options, and requirements files when necessary.
62
- - If a specific version of a library is specified, use it.
63
- - Unless the user specifies otherwise, use the most current versions of the libraries and pip, using and following best practices.
 
64
  - Use incremental reasoning to add improvements, expansions, and considerations to your code.
65
  - Use the history of the conversations so that the response is incremental.
66
- - If the target OS is Windows, use pip commands compatible with Windows, and if the target OS is Linux, use pip commands compatible with Linux
67
 
68
  **Important:**
69
- - Generate only one command at a time.
70
- - Create the longest, most complete, and detailed command possible to cover a wide range of possibilities and scenarios.
71
- - Consider all the details of the request, expanding the response and improving the command.
72
- - If the prompt asks to install a library that is not in a given group, install it in the command, but include in the prompt that library is not in the selected groups.
73
- - If a version of a library is specified, install it using a version constraint.
74
- - Consider if the user needs a requirements.txt file or not and if needed use it in your command.
75
- """
76
-
77
  response = send_message_to_model(prompt, model_name, temperature, top_p, top_k, max_tokens)
78
  return response
79
 
80
- def parse_and_save_code(ai_code, short_title):
81
- """Parses the markdown and saves the code."""
82
- pip_match = re.search(r'```pip\s*(.*?)\s*```', ai_code, re.DOTALL | re.IGNORECASE)
83
- bash_match = re.search(r'```bash\s*(.*?)\s*```', ai_code, re.DOTALL | re.IGNORECASE)
84
- ps1_match = re.search(r'```powershell\s*(.*?)\s*```', ai_code, re.DOTALL | re.IGNORECASE)
85
-
86
- pip_code = pip_match.group(1).strip() if pip_match else ai_code.strip()
87
- bash_code = bash_match.group(1).strip() if bash_match else None
88
- ps1_code = ps1_match.group(1).strip() if ps1_match else None
89
-
90
- base_file_name = f"pip_command_{short_title}"
91
-
92
- files = {}
93
-
94
- files["pip"]= {"name":f"{base_file_name}.txt", "code":pip_code}
95
-
96
- if bash_code:
97
- files["bash"]= {"name":f"{base_file_name}.sh", "code":bash_code}
98
-
99
- if ps1_code:
100
- files["powershell"]= {"name":f"{base_file_name}.ps1", "code":ps1_code}
101
-
102
- for key, value in files.items():
103
- with open(value["name"], "w") as f:
104
- f.write(value["code"])
105
-
106
- return files
107
 
 
 
 
 
108
 
109
  def main():
110
- st.title("🐍✨ Gemini2 Pip Gen Pro by [Elias Andrade](https://github.com/chaos4455)")
111
- st.markdown("Generate advanced pip install commands with ease! 🚀")
112
  st.markdown("---")
113
 
114
  # Layout in columns (sidebar and main area)
@@ -123,95 +105,65 @@ def main():
123
  top_p = st.slider("Top P", min_value=0.1, max_value=1.0, value=0.8, step=0.1, help="Adjust the AI's sampling.")
124
  top_k = st.slider("Top K", min_value=1, max_value=100, value=40, step=1, help="Adjust the AI's number of candidate tokens.")
125
  max_tokens = st.number_input("📏 Max Tokens", min_value=128, max_value=8192, value=8192, step=128, help="Adjust the maximum size of the response.")
126
-
127
- with st.expander("📝 Libraries & Groups"):
128
- available_libraries = {
129
- "📊 Data Analysis": ["pandas", "numpy", "scipy", "matplotlib", "seaborn", "plotly", "bokeh", "statsmodels", "scikit-image", "geopandas", "altair", "holoviews", "datashader", "missingno", "vaex", "dask", "xarray", "polars", "arrow", "numba", "cudf", "cupy", "streamz", "panel", "hvplot"],
130
- "🧠 Machine Learning": ["scikit-learn", "tensorflow", "torch", "keras", "xgboost", "lightgbm", "catboost", "pytorch-lightning", "transformers", "optuna", "mlflow", "gradio", "huggingface-hub", "sentence-transformers", "fastai", "librosa", "gensim", "spacy", "nltk", "opencv-python", "imbalanced-learn", "sktime", "umap-learn", "fairlearn", "shap", "eli5", "snorkel", "thinc"],
131
- "����️ Web Development": ["flask", "fastapi", "django", "requests", "beautifulsoup4", "aiohttp", "uvicorn", "gunicorn", "jinja2", "starlette", "websockets", "flask-restful", "django-rest-framework", "scrapy", "selenium", "playwright", "httpx", "rich", "pyramid", "bottle", "tornado", "dash", "plotly-dash", "streamlit", "gradio"],
132
- "🗄️ Database": ["sqlalchemy", "psycopg2", "pymongo", "mysql-connector-python", "sqlite3", "redis", "cassandra-driver", "pyodbc", "aiosqlite", "kafka-python", "motor", "neo4j", "influxdb", "elasticsearch", "pyarrow", "clickhouse-driver", "arangodb", "couchbase", "dgraph-python", "tinydb", "dataset"],
133
- "☁️ Cloud": ["boto3", "google-cloud-storage", "azure-storage-blob", "kubernetes", "docker", "apache-libcloud", "pulumi", "awscli", "google-cloud-sdk", "azure-cli", "terraform", "openstack", "ansible", "salt", "chef", "cdktf", "serverless", "aws-cdk", "google-cloud-build", "azure-pipelines", "docker-compose", "moto", "localstack"],
134
- "🤖 IA & LLM": ["langchain", "openai", "diffusers", "sentence-transformers", "stable-diffusion", "huggingface-hub", "pyannote-audio", "whisper", "nltk", "spacy", "transformers", "accelerate", "datasets", "einops", "faiss-cpu", "bitsandbytes", "peft", "trl", "haystack", "llama-index", "deepsparse", "nanogpt", "autogpt", "babyagi","ml-agents", "tensorboardx"],
135
- "🛠️ Dev Tools": ["pytest", "flake8", "mypy", "black", "isort", "pylint", "tox", "pre-commit", "bandit", "coverage", "virtualenv", "pipenv", "poetry", "invoke", "nox", "twine", "wheel", "setuptools", "build", "debugpy", "pyinstrument", "memory-profiler", "cProfile", "pdbpp", "ipython"],
136
- "⚙️ Data Engineering": ["apache-airflow", "dask", "luigi", "pyspark", "ray", "prefect", "dbt-core", "pandas-gbq", "petl", "sqlalchemy-redshift", "fugue", "ibis-framework", "mindsdb", "koalas", "vaex-core", "feast", "flink", "beam", "kafka-python", "clickhouse-driver", "superset", "metabase", "trino"],
137
- "🌐 Networking": ["requests", "httpx", "socketio", "paramiko", "netmiko", "scapy", "dnspython", "asyncssh", "tqdm", "gevent", "websocket-client", "pyserial", "grpcio", "aiozmq", "uvloop", "aiofiles", "urllib3", "fastsocket", "twisted", "aiohttp-socks", "aioredis", "websockets"],
138
- "🔒 Security": ["cryptography", "pyjwt", "requests-oauthlib", "paramiko", "pyOpenSSL", "passlib", "hashlib", "bcrypt", "python-nmap", "sqlmap", "scapy", "yara-python", "pwn", "mitmproxy", "themis", "pycryptodome", "tpm2-py", "pyspy", "volatility3", "pefile", "dpkt"],
139
- "🎨 GUI": ["tkinter", "pyqt5", "kivy", "wxpython", "pygame", "dearpygui", "pyglet", "flet", "toga", "eel", "qt-material", "pyside6", "pywebview", "guizero", "remif", "taipy"],
140
- "🧪 Testing": ["unittest", "pytest-cov", "hypothesis", "behave", "locust", "nose", "selenium", "playwright", "mock", "freezegun", "ddt", "tox", "robotframework", "hypothesis", "vcrpy", "responses", "faker", "factory-boy", "coveragepy", "parameterized"],
141
- "🧰 Utilities": ["click", "typer", "argparse", "rich", "tqdm", "colorama", "schedule", "python-dotenv", "shutil", "pathlib", "arrow", "toml", "json5", "xmltodict", "humanize", "pendulum", "inflect", "unidecode", "boltons", "delegator.py"],
142
- "📚 Documentation": ["sphinx", "mkdocs", "pdoc", "readthedocs-sphinx-search", "numpydoc", "docutils", "recommonmark", "sphinx-rtd-theme", "furo", "m2r2", "autoapi", "plantuml", "pycco", "doc8", "griffe", "mistletoe", "marko"],
143
- "🎮 Game Dev": ["pygame", "pyglet", "arcade", "panda3d", "ursina", "cocos2d", "renpy", "pyopengl", "cymunk", "pytmx", "pybox2d", "pymunk", "moderngl", "glumpy", "glfw", "sdl2"],
144
- "💹 Finance": ["numpy-financial", "pandas-datareader", "scikit-portfolio", "yfinance", "finmarketpy", "quantstats", "TA-Lib", "riskfolio-optimization", "alphalens", "pyfolio", "zipline", "backtrader", "quantlib-python", "pyfin", "quandl", "vnpy"],
145
- "🤖 Robotics": ["rospy", "pybullet", "mujoco-py", "open3d", "numpy-stl", "pyserial", "opencv-python", "pymavlink", "robotframework", "webots", "vpython", "transforms3d", "trimesh", "pyrealsense2", "aiortc", "gymnasium", "stable-baselines3"],
146
- "🧬 Bioinformatics": ["biopython", "scikit-bio", "pysam", "pandas-genomics", "statsmodels", "pybedtools", "matplotlib", "seaborn", "pyteomics", "networkx", "pyfaidx", "lifelines", "ngslib", "bcbio-nextgen", "scanpy", "anndata", "gseapy", "deepchem", "methylpy"],
147
- "🔭 Astronomy": ["astropy", "astroquery", "scikit-image", "photutils", "pyephem", "poliastro", "pyvista", "vtk", "healpy", "astroplan", "specutils", "sunpy", "gwpy", "lhorizon", "dustmaps", "reproject", "pymc3", "celerite"],
148
- "🗺️ Geospatial": ["geopandas", "rasterio", "shapely", "pyproj", "fiona", "cartopy", "folium", "geopy", "earthpy", "descartes", "osmnx", "geohash", "momepy", "pyvista", "whitebox", "earthengine-api", "gisalchemist", "mapclassify", "spatialpandas"],
149
- "💡 IoT": ["pyserial", "paho-mqtt", "RPi.GPIO", "smbus2", "pysnmp", "can-utils", "zeroconf", "asyncio", "bluepy", "adafruit-circuitpython", "iotconnect", "thinger-io", "micropython", "homeassistant", "openhab", "tasmota", "esphome", "nodemcu"],
150
- "💻 System": ["psutil", "subprocess32", "watchdog", "inotify", "pywin32", "sh", "delegator.py", "appdirs", "click", "typer", "pathlib", "colorama", "fire", "daemonize", "lsof", "ruamel.yaml", "py-cpuinfo", "platformdirs"]
151
- }
152
-
153
- selected_libraries = {}
154
- for group, libraries in available_libraries.items():
155
- selected_libraries[group] = st.multiselect(f"{group} ", libraries, default=[],key=f"lib_{group}")
156
-
157
- selected_groups = st.multiselect("🗂️ Groups", list(available_libraries.keys()), default=[], help="Choose groups to include libraries.")
158
-
159
-
160
- with st.expander("⚙️ Pip Settings"):
161
- custom_requirements = st.text_input("➕ Custom Libraries:", placeholder="Specific libraries or versions (e.g., requests==2.28.1, numpy>=1.23.0)", help="List specific libraries and versions.")
162
- specific_details = st.text_input("ℹ️ Specific Details", placeholder="Special pip install options, edge cases", help="Add specific details for the pip command generation.")
163
- pip_options = st.text_input("⚙️ Pip Options", placeholder="Add custom pip options like --index-url or --no-cache", help="Add custom options to your pip command")
164
- target_os = st.selectbox("🎯 Target OS", ["Linux 🐧", "Windows 🪟"], index=0, help="Choose the target Operating System.")
165
-
166
-
167
 
168
  with col2:
169
- # User's base prompt
170
- prompt_base = st.text_input("📝 Describe the Pip Command:", placeholder="Ex: Install all libraries for web development and data analysis", key="prompt_base")
171
-
172
- if st.button("✨ Generate Pip Command"):
173
- if not prompt_base and not selected_libraries and not selected_groups and not custom_requirements:
174
- st.error("⚠️ Please enter a command description or select libraries/groups")
 
 
 
 
 
 
 
 
 
 
175
  return
176
 
177
- selected_libs = []
178
- for group in selected_groups:
179
- selected_libs.extend(selected_libraries[group])
180
-
181
- with st.spinner("⏳ Generating command..."):
182
- ai_code = generate_pip_command(
183
  prompt_base,
184
  model_name,
185
  temperature,
186
  top_p,
187
  top_k,
188
  max_tokens,
189
- selected_libs,
190
- selected_groups,
191
  custom_requirements,
192
  specific_details,
193
- pip_options,
194
- target_os
195
  )
196
 
197
  if ai_code:
198
- st.markdown("### ✅ Generated Command:")
199
- st.code(ai_code, language="text") #to output all codes
200
-
201
- short_title = prompt_base[:30].strip().replace(" ", "_").lower()
202
- files = parse_and_save_code(ai_code, short_title)
203
-
204
- for key, value in files.items():
205
- st.download_button(
206
- label=f"⬇️ Download Command (.{(key)})",
207
- data=value["code"],
208
- file_name=value["name"],
209
- mime="text/plain",
210
- )
211
-
212
  else:
213
- st.error("❌ Error generating the command. Check the connection with the AI and try again.")
214
-
215
 
216
  if __name__ == "__main__":
217
  main()
 
2
  import google.generativeai as genai
3
  import re
4
  import os
5
+ import textwrap
6
 
7
  # Secret key and Google Gemini API configuration
8
  API_KEY = st.secrets["GOOGLE_API_KEY"]
9
 
10
  # Page configuration
11
+ st.set_page_config(page_title="🔄✨ Gemini2 Script Mig Gen Pro", page_icon="🔄✨", layout="wide")
12
 
13
  # --- Helper Functions ---
14
  def send_message_to_model(message, model_name, temperature, top_p, top_k, max_tokens):
 
33
  st.error(f"❌ Error communicating with the AI: {e}")
34
  return None
35
 
36
+ def generate_migration_script(prompt_base, model_name, temperature, top_p, top_k, max_tokens, source_type, target_type, custom_requirements, specific_details, transformation_details):
37
+ """Generates a migration script based on user settings."""
38
  prompt = f"""
39
+ You are an expert automation engineer specializing in migration scripts. Your task is to generate a complete, secure, and efficient migration script based on the following description:
40
 
41
+ **Goal:** Create the most complete, detailed, and efficient migration script possible, considering all variables, edge cases, and potential scenarios.
 
 
42
 
43
+ **Migration Description:** {prompt_base}
44
 
45
+ **Source Type:** {source_type if source_type else "None"}
46
+ **Target Type:** {target_type if target_type else "None"}
47
+ **Transformation Details:** {transformation_details if transformation_details else "None"}
48
  **Custom Requirements:** {custom_requirements if custom_requirements else "None"}
49
  **Specific Details:** {specific_details if specific_details else "None"}
 
50
 
51
  **Response Format:**
52
+ - Respond in Markdown format, including a python code block with its original formatting, without line breaks.
53
+ - The python code block must be delimited by ```python and ```.
54
+ - Do not include comments, explanations, or any other text outside the code block, unless the prompt requires.
 
 
55
  - The code must maintain its full vertical formatting, respecting indentation and line breaks.
56
+ - The code must be realistic, using real-world examples, data, and situations.
57
  - Explore different approaches, techniques, and advanced practices, always prioritizing security and efficiency.
58
+ - The code must use best practices for accessing resources, connecting to databases, handling errors and logging data.
59
+ - Unless the user specifies otherwise, use the most current and secure versions of libraries and resources, using python and following best practices.
60
+ - The code must use a valid logging system with timestamps and log levels.
61
+ - The code must be well structured according to PEP8 guidelines, with docstrings and clear naming conventions.
62
  - Use incremental reasoning to add improvements, expansions, and considerations to your code.
63
  - Use the history of the conversations so that the response is incremental.
64
+ - If the user requests for a transformation, generate it using python code and libraries, and document every step in the code.
65
 
66
  **Important:**
67
+ - Generate only one script at a time.
68
+ - Create the longest, most complete, and detailed code possible to cover a wide range of possibilities and scenarios.
69
+ - Consider all the details of the request, expanding the response and improving the script.
70
+ - If the user does not provide details on connection parameters, create placeholders in the code with comments like 'PLEASE FILL THIS' indicating where the user should fill in.
71
+ - If the user does not provide the details about source and target, use MySQL as source and SQLite as target, and include comments on what the user should change, use the comments '# SOURCE DATABASE' and '# TARGET DATABASE'.
72
+ - Provide in your code all necessary comments for the user to understand the process of migration and where he should add his parameters.
73
+ - Use `try/except` blocks for error handling, and document what could cause the errors.
74
+ """
75
  response = send_message_to_model(prompt, model_name, temperature, top_p, top_k, max_tokens)
76
  return response
77
 
78
+ def parse_and_save_py(ai_code, short_title):
79
+ """Parses the markdown and saves the python code as .py."""
80
+ match = re.search(r'```python\s*(.*?)\s*```', ai_code, re.DOTALL | re.IGNORECASE)
81
+ if match:
82
+ py_code = match.group(1).strip()
83
+ else:
84
+ py_code = ai_code.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
+ file_name = f"migration_script_{short_title}.py"
87
+ with open(file_name, "w", encoding="utf-8") as f:
88
+ f.write(py_code)
89
+ return file_name, py_code
90
 
91
  def main():
92
+ st.title("🔄✨ Gemini2 Script Mig Gen Pro by [Elias Andrade](https://github.com/chaos4455)")
93
+ st.markdown("Generate advanced migration scripts with ease! 🚀")
94
  st.markdown("---")
95
 
96
  # Layout in columns (sidebar and main area)
 
105
  top_p = st.slider("Top P", min_value=0.1, max_value=1.0, value=0.8, step=0.1, help="Adjust the AI's sampling.")
106
  top_k = st.slider("Top K", min_value=1, max_value=100, value=40, step=1, help="Adjust the AI's number of candidate tokens.")
107
  max_tokens = st.number_input("📏 Max Tokens", min_value=128, max_value=8192, value=8192, step=128, help="Adjust the maximum size of the response.")
108
+
109
+ with st.expander("🧰 Migration Settings"):
110
+ source_type = st.selectbox("📦 Source Type", ["MySQL", "PostgreSQL", "SQLite", "MongoDB", "CSV", "JSON", "Parquet", "Excel", "BigQuery", "Snowflake", "Redis", "Kafka", "Other"], index=0, help="Select the type of the data source.")
111
+ target_type = st.selectbox("🎯 Target Type", ["SQLite", "MySQL", "PostgreSQL", "MongoDB", "CSV", "JSON", "Parquet", "Excel", "BigQuery", "Snowflake", "Redis", "Kafka", "Other"], index=0, help="Select the type of the data target.")
112
+ transformation_details = st.text_area("🔄 Transformation Details", placeholder="Specify any transformations or filtering needed (e.g., convert date formats, filter rows, etc).",
113
+ help="Provide details of any transformations you need during the migration, using Python or SQL, if it can be done with SQL.",
114
+ )
115
+ custom_requirements = st.text_input(" Custom Requirements:", placeholder="Specific libraries or parameters (e.g., version, parameters)", help="List specific libraries and versions, parameters, etc.")
116
+ specific_details = st.text_input("ℹ️ Specific Details", placeholder="Special options, edge cases", help="Add specific details for the script generation.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
  with col2:
119
+ # User's base prompt
120
+ prompt_base = st.text_area("📝 Describe the Migration:",
121
+ placeholder=textwrap.dedent("""
122
+ Describe your migration process in detail.
123
+ Include:
124
+ - Source and target system details (e.g., database IPs, ports, logins, passwords).
125
+ - Specific tables to migrate.
126
+ - Any filtering, transformations, or data cleansing needed.
127
+ - Important notes about the systems (e.g., if there is an external system involved)
128
+ If connection details or source and target are not included, the script will be generated using defaults, and you must fill in the parameters.
129
+ """), key="prompt_base",
130
+ help="Provide a detailed description of your migration, including source and target systems, tables, transformations, and any specific parameters.")
131
+
132
+ if st.button("✨ Generate Migration Script"):
133
+ if not prompt_base:
134
+ st.error("⚠️ Please enter a migration description.")
135
  return
136
 
137
+ with st.spinner("⏳ Generating script..."):
138
+ ai_code = generate_migration_script(
 
 
 
 
139
  prompt_base,
140
  model_name,
141
  temperature,
142
  top_p,
143
  top_k,
144
  max_tokens,
145
+ source_type,
146
+ target_type,
147
  custom_requirements,
148
  specific_details,
149
+ transformation_details
 
150
  )
151
 
152
  if ai_code:
153
+ st.markdown("### ✅ Generated Migration Script:")
154
+ st.code(ai_code, language="python")
155
+
156
+ short_title = prompt_base[:30].strip().replace(" ", "_").lower()
157
+ file_name_py, py_code = parse_and_save_py(ai_code, short_title)
158
+
159
+ st.download_button(
160
+ label="⬇️ Download Script (.py)",
161
+ data=py_code,
162
+ file_name=file_name_py,
163
+ mime="application/x-python",
164
+ )
 
 
165
  else:
166
+ st.error("❌ Error generating the script. Check the connection with the AI and try again.")
 
167
 
168
  if __name__ == "__main__":
169
  main()