hasanalrobasi commited on
Commit
de3c63b
·
verified ·
1 Parent(s): 61943b8

Upload streamlit_app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. streamlit_app.py +216 -0
streamlit_app.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from daggr import GradioNode, InferenceNode, FnNode, Graph
3
+ import gradio as gr
4
+ from typing import Dict, Any
5
+ import requests
6
+ import os
7
+ import time
8
+ from datetime import datetime
9
+
10
+ # Set page config
11
+ st.set_page_config(
12
+ page_title="Global Integration Platform",
13
+ page_icon="🌐",
14
+ layout="wide"
15
+ )
16
+
17
+ # Add anycoder link
18
+ st.sidebar.markdown("[Built with anycoder](https://huggingface.co/spaces/akhaliq/anycoder)")
19
+
20
+ # Initialize session state
21
+ if 'workflow_results' not in st.session_state:
22
+ st.session_state.workflow_results = None
23
+
24
+ # Environment variables for API keys
25
+ API_KEYS = {
26
+ "OPENAI": os.getenv("OPENAI_API_KEY"),
27
+ "HUGGINGFACE": os.getenv("HF_API_KEY")
28
+ }
29
+
30
+ # ========== Nodes Definition ==========
31
+ def preprocess_inputs(user_input: str, metadata: Dict[str, Any]) -> Dict[str, Any]:
32
+ """Clean and validate inputs with metadata enrichment"""
33
+ if not user_input.strip():
34
+ raise ValueError("Input cannot be empty")
35
+ return {
36
+ "cleaned_input": user_input.strip(),
37
+ "timestamp": metadata.get("timestamp", datetime.now().isoformat()),
38
+ "source": metadata.get("source", "web")
39
+ }
40
+
41
+ input_processor = FnNode(
42
+ fn=preprocess_inputs,
43
+ inputs={
44
+ "user_input": gr.Textbox(label="User Input"),
45
+ "metadata": gr.JSON(label="Metadata", value={"source": "streamlit"})
46
+ },
47
+ outputs={
48
+ "processed_data": gr.JSON(label="Processed Input")
49
+ }
50
+ )
51
+
52
+ def llm_wrapper(prompt: str, temperature: float = 0.7) -> str:
53
+ """Wrapper for LLM processing with error handling"""
54
+ try:
55
+ # Simulate processing time
56
+ time.sleep(1)
57
+ return f"LLM Response to: {prompt}"
58
+ except Exception as e:
59
+ return f"Error in LLM processing: {str(e)}"
60
+
61
+ llm_processor = FnNode(
62
+ fn=llm_wrapper,
63
+ inputs={
64
+ "prompt": gr.Textbox(label="LLM Prompt"),
65
+ "temperature": gr.Slider(0, 1, value=0.7)
66
+ },
67
+ outputs={
68
+ "response": gr.Textbox(label="LLM Response")
69
+ }
70
+ )
71
+
72
+ def image_gen_wrapper(prompt: str, negative_prompt: str = "", steps: int = 30) -> Any:
73
+ """Wrapper for image generation"""
74
+ try:
75
+ # Placeholder for actual image generation
76
+ return "https://via.placeholder.com/512?text=Generated+Image"
77
+ except Exception as e:
78
+ return f"Error in image generation: {str(e)}"
79
+
80
+ image_generator = FnNode(
81
+ fn=image_gen_wrapper,
82
+ inputs={
83
+ "prompt": gr.Textbox(label="Image Prompt"),
84
+ "negative_prompt": gr.Textbox(label="Negative Prompt"),
85
+ "steps": gr.Slider(10, 50, value=30)
86
+ },
87
+ outputs={
88
+ "image": gr.Image(label="Generated Image")
89
+ }
90
+ )
91
+
92
+ def call_external_api(data: Dict[str, Any]) -> Dict[str, Any]:
93
+ """Generic API caller with error handling"""
94
+ try:
95
+ # Simulate API call
96
+ time.sleep(0.5)
97
+ return {
98
+ "status": "success",
99
+ "data": {
100
+ "input": data,
101
+ "processed": True,
102
+ "timestamp": datetime.now().isoformat()
103
+ }
104
+ }
105
+ except Exception as e:
106
+ return {"error": str(e)}
107
+
108
+ api_integrator = FnNode(
109
+ fn=call_external_api,
110
+ inputs={
111
+ "api_data": gr.JSON(label="API Payload")
112
+ },
113
+ outputs={
114
+ "api_response": gr.JSON(label="API Results")
115
+ }
116
+ )
117
+
118
+ def format_output(llm_response: str, image: Any, api_data: Dict) -> Dict[str, Any]:
119
+ """Create unified output format"""
120
+ return {
121
+ "text_response": llm_response,
122
+ "visual_response": image,
123
+ "api_data": api_data,
124
+ "status": "success",
125
+ "timestamp": datetime.now().isoformat()
126
+ }
127
+
128
+ output_formatter = FnNode(
129
+ fn=format_output,
130
+ inputs={
131
+ "llm_response": gr.Textbox(),
132
+ "image": gr.Image(),
133
+ "api_data": gr.JSON()
134
+ },
135
+ outputs={
136
+ "final_output": gr.JSON(label="Final Output")
137
+ }
138
+ )
139
+
140
+ # ========== Create Workflow ==========
141
+ workflow = Graph(
142
+ name="Global Integration Platform",
143
+ nodes=[
144
+ input_processor,
145
+ llm_processor,
146
+ image_generator,
147
+ api_integrator,
148
+ output_formatter
149
+ ],
150
+ connections=[
151
+ (input_processor.outputs["processed_data"], llm_processor.inputs["prompt"]),
152
+ (input_processor.outputs["processed_data"], image_generator.inputs["prompt"]),
153
+ (input_processor.outputs["processed_data"], api_integrator.inputs["api_data"]),
154
+ (llm_processor.outputs["response"], output_formatter.inputs["llm_response"]),
155
+ (image_generator.outputs["image"], output_formatter.inputs["image"]),
156
+ (api_integrator.outputs["api_response"], output_formatter.inputs["api_data"])
157
+ ]
158
+ )
159
+
160
+ # ========== Streamlit UI ==========
161
+ st.title("🌐 Global Integration Platform")
162
+ st.markdown("""
163
+ This application integrates multiple components into a cohesive workflow including:
164
+ - Input processing
165
+ - LLM processing
166
+ - Image generation
167
+ - External API integration
168
+ """)
169
+
170
+ with st.form("workflow_form"):
171
+ user_input = st.text_area("Enter your input:", height=150)
172
+ metadata = st.text_input("Additional metadata (JSON):", value='{"source": "streamlit"}')
173
+ temperature = st.slider("LLM Temperature:", 0.0, 1.0, 0.7)
174
+ steps = st.slider("Image Generation Steps:", 10, 50, 30)
175
+
176
+ submitted = st.form_submit_button("Run Workflow")
177
+
178
+ if submitted:
179
+ with st.spinner("Processing workflow..."):
180
+ try:
181
+ # Prepare inputs
182
+ inputs = {
183
+ "user_input": user_input,
184
+ "metadata": metadata,
185
+ "temperature": temperature,
186
+ "steps": steps
187
+ }
188
+
189
+ # Execute workflow
190
+ results = workflow.run(inputs)
191
+ st.session_state.workflow_results = results
192
+
193
+ st.success("Workflow completed successfully!")
194
+
195
+ except Exception as e:
196
+ st.error(f"Error in workflow execution: {str(e)}")
197
+
198
+ # Display results if available
199
+ if st.session_state.workflow_results:
200
+ st.subheader("Workflow Results")
201
+
202
+ col1, col2 = st.columns(2)
203
+
204
+ with col1:
205
+ st.markdown("### Text Response")
206
+ st.write(st.session_state.workflow_results['final_output']['text_response'])
207
+
208
+ st.markdown("### API Response")
209
+ st.json(st.session_state.workflow_results['final_output']['api_data'])
210
+
211
+ with col2:
212
+ st.markdown("### Generated Image")
213
+ st.image(st.session_state.workflow_results['final_output']['visual_response'])
214
+
215
+ st.markdown("### Full Output")
216
+ st.json(st.session_state.workflow_results['final_output'])