sanvrypt commited on
Commit
89fd841
·
verified ·
1 Parent(s): 0230a46

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -84
app.py CHANGED
@@ -1,125 +1,176 @@
1
  from flask import Flask, request, jsonify, Response
2
  import requests
 
3
 
4
  app = Flask(__name__)
 
 
 
 
5
  OLLAMA_URL = "http://localhost:11434"
 
6
 
7
- # Add CORS headers to all responses
 
 
8
  @app.after_request
9
  def after_request(response):
10
- response.headers.add('Access-Control-Allow-Origin', '*')
11
- response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
12
- response.headers.add('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
13
  return response
14
 
15
- @app.route('/')
 
 
 
 
16
  def home():
17
- print("HOME ROUTE ACCESSED")
18
- return '''<!DOCTYPE html>
19
- <html><head><title>Ollama API</title></head>
 
 
 
20
  <body style="font-family:Arial;padding:50px;text-align:center;">
21
- <h1>🦙 Ollama API Running!</h1>
22
- <p>Model: llama3.2:3b</p>
23
- <h3>Test with:</h3>
24
- <pre style="background:#f4f4f4;padding:20px;text-align:left;max-width:700px;margin:20px auto;">
25
- curl -X POST https://my-ollama.hf.space/api/generate \\
 
26
  -H "Content-Type: application/json" \\
27
- -d '{"model":"sweaterdog/andy-4:latest","prompt":"Hello!","stream":false}'
28
- </pre>
29
- <button onclick="testAPI()">Test API Now</button>
30
- <div id="result" style="margin-top:20px;padding:20px;background:#f4f4f4;text-align:left;"></div>
 
 
 
 
 
 
 
31
  <script>
32
- async function testAPI() {
33
- const result = document.getElementById('result');
34
- result.textContent = 'Testing...';
35
- try {
36
- const response = await fetch('/api/generate', {
37
- method: 'POST',
38
- headers: {'Content-Type': 'application/json'},
39
- body: JSON.stringify({model:'llama3.2:3b',prompt:'Hello!',stream:false})
40
- });
41
- const data = await response.json();
42
- result.textContent = JSON.stringify(data, null, 2);
43
- } catch(e) {
44
- result.textContent = 'Error: ' + e.message;
45
- }
46
- }
 
 
 
 
 
47
  </script>
48
- </body></html>'''
 
 
 
49
 
50
- @app.route('/api/generate', methods=['POST', 'OPTIONS'])
 
 
 
51
  def generate():
52
- print("=== /api/generate ROUTE HIT ===")
53
- if request.method == 'OPTIONS':
54
- return '', 204
55
-
56
  try:
57
- data = request.get_json()
58
- print(f"Request data: {data}")
59
-
 
 
60
  resp = requests.post(
61
- f"{OLLAMA_URL}/api/generate",
62
- json=data,
63
- stream=data.get('stream', False),
64
- timeout=120
65
  )
66
-
67
- print(f"Ollama response status: {resp.status_code}")
68
-
69
- if data.get('stream', False):
70
  def gen():
71
  for line in resp.iter_lines():
72
  if line:
73
- yield line + b'\n'
74
- return Response(gen(), content_type='application/x-ndjson')
75
- else:
76
- result = resp.json()
77
- print(f"Returning: {result}")
78
- return jsonify(result)
79
  except Exception as e:
80
- print(f"ERROR: {e}")
81
- import traceback
82
  traceback.print_exc()
83
  return jsonify({"error": str(e)}), 500
84
 
85
- @app.route('/api/chat', methods=['POST', 'OPTIONS'])
 
 
 
 
86
  def chat():
87
- print("=== /api/chat ROUTE HIT ===")
88
- if request.method == 'OPTIONS':
89
- return '', 204
90
-
91
  try:
92
- data = request.get_json()
 
 
 
 
93
  resp = requests.post(
94
- f"{OLLAMA_URL}/api/chat",
95
- json=data,
96
- stream=data.get('stream', False),
97
- timeout=120
98
  )
99
-
100
- if data.get('stream', False):
101
  def gen():
102
  for line in resp.iter_lines():
103
  if line:
104
- yield line + b'\n'
105
- return Response(gen(), content_type='application/x-ndjson')
106
- else:
107
- return jsonify(resp.json())
 
108
  except Exception as e:
109
- print(f"ERROR: {e}")
110
  return jsonify({"error": str(e)}), 500
111
 
112
- # Catch-all route for debugging
113
- @app.route('/<path:path>', methods=['GET', 'POST'])
 
 
 
114
  def catch_all(path):
115
- print(f"CATCH-ALL: {request.method} /{path}")
116
- return jsonify({"error": "Not found", "path": path}), 404
 
 
 
117
 
118
- if __name__ == '__main__':
 
 
 
119
  print("=" * 50)
120
- print("Starting Flask on port 7860...")
121
- print("Routes registered:")
122
- for rule in app.url_map.iter_rules():
123
- print(f" {rule}")
124
  print("=" * 50)
125
- app.run(host='0.0.0.0', port=7860, debug=False)
 
 
 
 
 
 
1
  from flask import Flask, request, jsonify, Response
2
  import requests
3
+ import traceback
4
 
5
  app = Flask(__name__)
6
+
7
+ # ==============================
8
+ # CONFIG
9
+ # ==============================
10
  OLLAMA_URL = "http://localhost:11434"
11
+ DEFAULT_MODEL = "sweaterdog/andy-4:latest"
12
 
13
+ # ==============================
14
+ # CORS
15
+ # ==============================
16
  @app.after_request
17
  def after_request(response):
18
+ response.headers["Access-Control-Allow-Origin"] = "*"
19
+ response.headers["Access-Control-Allow-Headers"] = "Content-Type"
20
+ response.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
21
  return response
22
 
23
+
24
+ # ==============================
25
+ # HOME
26
+ # ==============================
27
+ @app.route("/")
28
  def home():
29
+ return f"""
30
+ <!DOCTYPE html>
31
+ <html>
32
+ <head>
33
+ <title>Andy-4 API</title>
34
+ </head>
35
  <body style="font-family:Arial;padding:50px;text-align:center;">
36
+ <h1>🤖 Andy-4 API Running</h1>
37
+ <p><b>Model:</b> {DEFAULT_MODEL}</p>
38
+
39
+ <h3>Test CURL</h3>
40
+ <pre style="background:#f4f4f4;padding:20px;text-align:left;max-width:900px;margin:auto;">
41
+ curl -X POST https://sanvrypt-mindcraft-vllm.hf.space/api/generate \\
42
  -H "Content-Type: application/json" \\
43
+ -d '{{
44
+ "prompt": "Halo Andy-4!",
45
+ "stream": false
46
+ }}'
47
+ </pre>
48
+
49
+ <button onclick="testAPI()">Test API</button>
50
+
51
+ <pre id="result"
52
+ style="margin-top:20px;padding:20px;background:#f4f4f4;text-align:left;white-space:pre-wrap;"></pre>
53
+
54
  <script>
55
+ async function testAPI() {{
56
+ const el = document.getElementById("result");
57
+ el.textContent = "Testing...";
58
+
59
+ try {{
60
+ const res = await fetch("/api/generate", {{
61
+ method: "POST",
62
+ headers: {{ "Content-Type": "application/json" }},
63
+ body: JSON.stringify({{
64
+ prompt: "Hello from browser!",
65
+ stream: false
66
+ }})
67
+ }});
68
+
69
+ const data = await res.json();
70
+ el.textContent = JSON.stringify(data, null, 2);
71
+ }} catch (e) {{
72
+ el.textContent = "ERROR: " + e.message;
73
+ }}
74
+ }}
75
  </script>
76
+ </body>
77
+ </html>
78
+ """
79
+
80
 
81
+ # ==============================
82
+ # GENERATE
83
+ # ==============================
84
+ @app.route("/api/generate", methods=["POST", "OPTIONS"])
85
  def generate():
86
+ if request.method == "OPTIONS":
87
+ return "", 204
88
+
 
89
  try:
90
+ data = request.get_json(force=True)
91
+
92
+ # FORCE MODEL
93
+ data["model"] = DEFAULT_MODEL
94
+
95
  resp = requests.post(
96
+ f"{OLLAMA_URL}/api/generate",
97
+ json=data,
98
+ stream=data.get("stream", False),
99
+ timeout=300
100
  )
101
+
102
+ if data.get("stream", False):
 
 
103
  def gen():
104
  for line in resp.iter_lines():
105
  if line:
106
+ yield line + b"\n"
107
+ return Response(gen(), content_type="application/x-ndjson")
108
+
109
+ return jsonify(resp.json())
110
+
 
111
  except Exception as e:
 
 
112
  traceback.print_exc()
113
  return jsonify({"error": str(e)}), 500
114
 
115
+
116
+ # ==============================
117
+ # CHAT
118
+ # ==============================
119
+ @app.route("/api/chat", methods=["POST", "OPTIONS"])
120
  def chat():
121
+ if request.method == "OPTIONS":
122
+ return "", 204
123
+
 
124
  try:
125
+ data = request.get_json(force=True)
126
+
127
+ # FORCE MODEL
128
+ data["model"] = DEFAULT_MODEL
129
+
130
  resp = requests.post(
131
+ f"{OLLAMA_URL}/api/chat",
132
+ json=data,
133
+ stream=data.get("stream", False),
134
+ timeout=300
135
  )
136
+
137
+ if data.get("stream", False):
138
  def gen():
139
  for line in resp.iter_lines():
140
  if line:
141
+ yield line + b"\n"
142
+ return Response(gen(), content_type="application/x-ndjson")
143
+
144
+ return jsonify(resp.json())
145
+
146
  except Exception as e:
147
+ traceback.print_exc()
148
  return jsonify({"error": str(e)}), 500
149
 
150
+
151
+ # ==============================
152
+ # FALLBACK
153
+ # ==============================
154
+ @app.route("/<path:path>", methods=["GET", "POST"])
155
  def catch_all(path):
156
+ return jsonify({
157
+ "error": "Not Found",
158
+ "path": path
159
+ }), 404
160
+
161
 
162
+ # ==============================
163
+ # MAIN
164
+ # ==============================
165
+ if __name__ == "__main__":
166
  print("=" * 50)
167
+ print(" Andy-4 Flask API ")
168
+ print(f" Model : {DEFAULT_MODEL}")
169
+ print(" Port : 7860")
 
170
  print("=" * 50)
171
+
172
+ app.run(
173
+ host="0.0.0.0",
174
+ port=7860,
175
+ debug=False
176
+ )