mirxakamran893 commited on
Commit
03021b9
Β·
verified Β·
1 Parent(s): 587208b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -46
app.py CHANGED
@@ -1,62 +1,145 @@
1
- import torch
2
  from fastapi import FastAPI, Request
3
  from fastapi.responses import JSONResponse
 
4
  import gradio as gr
5
- from diffusers import StableDiffusionPipeline
6
- import base64
7
- from io import BytesIO
8
- from PIL import Image
9
  import nest_asyncio
10
  import uvicorn
 
 
 
 
 
11
 
12
- # βœ… Create FastAPI app
13
  app = FastAPI()
14
 
15
- # βœ… Load the Stable Diffusion v1.5 model (faster than SDXL)
16
- model_id = "runwayml/stable-diffusion-v1-5"
17
- pipe = StableDiffusionPipeline.from_pretrained(
18
- model_id,
19
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
20
- use_safetensors=True,
21
- ).to("cuda" if torch.cuda.is_available() else "cpu")
22
-
23
- # βœ… Image generation function
24
- def generate_image(prompt: str):
25
- result = pipe(prompt=prompt, guidance_scale=7.5, num_inference_steps=25)
26
- image = result.images[0]
27
-
28
- # Convert image to base64
29
- buffered = BytesIO()
30
- image.save(buffered, format="PNG")
31
- img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
32
- return img_str
33
-
34
- # βœ… Gradio UI function (optional visual test)
35
- def gradio_ui(prompt):
36
- img_str = generate_image(prompt)
37
- return Image.open(BytesIO(base64.b64decode(img_str)))
38
-
39
- # βœ… Gradio Interface
40
- gr_interface = gr.Interface(fn=gradio_ui, inputs="text", outputs="image", title="Fast SD v1.5 Generator")
41
-
42
- # βœ… API route for programmatic access
43
- @app.post("/generate-image")
44
- async def generate(request: Request):
45
- data = await request.json()
46
- prompt = data.get("prompt")
47
- if not prompt:
48
- return JSONResponse(status_code=400, content={"error": "Missing prompt"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
  try:
51
- img_base64 = generate_image(prompt)
52
- return {"image_base64": img_base64}
 
 
 
 
 
 
 
 
53
  except Exception as e:
54
- return JSONResponse(status_code=500, content={"error": str(e)})
 
 
 
 
 
 
 
 
 
55
 
56
- # βœ… Mount Gradio UI at / for Spaces or browser
57
- app = gr.mount_gradio_app(app, gr_interface, path="/")
58
 
59
- # βœ… Local run only (disabled on Hugging Face Spaces automatically)
60
  if __name__ == "__main__":
61
  nest_asyncio.apply()
62
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
1
  from fastapi import FastAPI, Request
2
  from fastapi.responses import JSONResponse
3
+ from pydantic import BaseModel
4
  import gradio as gr
5
+ import os
6
+ import requests
 
 
7
  import nest_asyncio
8
  import uvicorn
9
+ import re
10
+
11
+ # βœ… API config
12
+ API_KEY = os.environ.get("OPENROUTER_API_KEY")
13
+ MODEL = "deepseek/deepseek-chat-v3-0324:free"
14
 
 
15
  app = FastAPI()
16
 
17
+ # βœ… Chat Function
18
+ def chat_fn(message, history):
19
+ headers = {
20
+ "Authorization": f"Bearer {API_KEY}",
21
+ "Content-Type": "application/json"
22
+ }
23
+
24
+ messages = [
25
+ {
26
+ "role": "system",
27
+ "content": (
28
+ "You are a coding assistant with a focus on programming tasks. You should provide clear, friendly, "
29
+ "and concise responses to coding questions or tasks. If you're unsure, say: 'I’m not sure about that. Could you rephrase?'"
30
+ )
31
+ }
32
+ ]
33
+
34
+ for user, assistant in history:
35
+ messages.append({"role": "user", "content": user})
36
+ messages.append({"role": "assistant", "content": assistant})
37
+
38
+ messages.append({"role": "user", "content": message + "\n\nReply in a natural tone."})
39
+
40
+ payload = {
41
+ "model": MODEL,
42
+ "messages": messages,
43
+ "max_tokens": 16384,
44
+ "temperature": 0.7,
45
+ "top_p": 0.9
46
+ }
47
+
48
+ try:
49
+ response = requests.post(
50
+ "https://openrouter.ai/api/v1/chat/completions",
51
+ headers=headers,
52
+ json=payload,
53
+ timeout=300
54
+ )
55
+ response.raise_for_status()
56
+ reply = response.json()["choices"][0]["message"]["content"]
57
+ except Exception as e:
58
+ reply = f"⚠️ API error: {str(e)[:200]}"
59
+
60
+ return reply.strip()
61
+
62
+ # βœ… /chat API endpoint
63
+ @app.post("/chat")
64
+ async def chat_api(request: Request):
65
+ body = await request.json()
66
+ message = body.get("message", "").strip()
67
+ history = body.get("history", [])
68
+
69
+ if not message:
70
+ return JSONResponse(content={"response": "⚠️ Please enter a valid message."})
71
+
72
+ response = chat_fn(message, history)
73
+ return JSONResponse(content={"response": response})
74
+
75
+
76
+ # βœ… New: /code-check endpoint for Monaco Editor integration
77
+ class CodePayload(BaseModel):
78
+ code: str
79
+
80
+ @app.post("/code-check")
81
+ async def code_check(request: Request):
82
+ body = await request.json()
83
+ code = body.get("code", "")
84
+
85
+ if not code.strip():
86
+ return JSONResponse(content={"suggestions": []})
87
+
88
+ headers = {
89
+ "Authorization": f"Bearer {API_KEY}",
90
+ "Content-Type": "application/json"
91
+ }
92
+
93
+ prompt = (
94
+ "Analyze the following code. Identify syntax issues or improvements.\n"
95
+ "Return a JSON array of suggestions with these keys:\n"
96
+ "- message\n"
97
+ "- severity ('error' or 'hint')\n"
98
+ "- fix (string to replace)\n"
99
+ "- line (1-based)\n"
100
+ "- startColumn, endColumn\n\n"
101
+ f"Code:\n{code}\n\n"
102
+ "Respond ONLY with the JSON array."
103
+ )
104
+
105
+ payload = {
106
+ "model": MODEL,
107
+ "messages": [
108
+ {"role": "system", "content": "You are a code analysis tool."},
109
+ {"role": "user", "content": prompt}
110
+ ],
111
+ "temperature": 0.3,
112
+ "top_p": 0.9,
113
+ "max_tokens": 2048
114
+ }
115
 
116
  try:
117
+ response = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload)
118
+ response.raise_for_status()
119
+ raw = response.json()["choices"][0]["message"]["content"]
120
+
121
+ # Try to extract JSON array from output
122
+ match = re.search(r"\[\s*{.*?}\s*\]", raw, re.DOTALL)
123
+ suggestions = eval(match.group(0)) if match else []
124
+
125
+ return JSONResponse(content={"suggestions": suggestions})
126
+
127
  except Exception as e:
128
+ return JSONResponse(content={"suggestions": [], "error": str(e)}, status_code=500)
129
+
130
+
131
+ # βœ… Gradio interface
132
+ demo = gr.ChatInterface(
133
+ fn=chat_fn,
134
+ title="πŸ’¬ CODEX MIRXA KAMRAN",
135
+ description="Ask coding or general programming questions! Short, natural, and helpful responses.",
136
+ theme="soft"
137
+ )
138
 
139
+ # βœ… Mount Gradio on FastAPI
140
+ app = gr.mount_gradio_app(app, demo, path="/")
141
 
142
+ # βœ… Local debug (won't run on HF Spaces, but okay locally)
143
  if __name__ == "__main__":
144
  nest_asyncio.apply()
145
  uvicorn.run(app, host="0.0.0.0", port=7860)