abdullahalioo commited on
Commit
e532099
·
verified ·
1 Parent(s): 85582c9

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +31 -53
main.py CHANGED
@@ -1,57 +1,35 @@
1
- from fastapi import FastAPI
2
- from fastapi.responses import HTMLResponse
3
- import logging
 
4
 
5
- # Set up logging
6
- logging.basicConfig(level=logging.INFO)
7
- logger = logging.getLogger(__name__)
8
-
9
- # Initialize FastAPI app
10
  app = FastAPI()
11
 
12
- # Serve HTML page
13
- @app.get("/", response_class=HTMLResponse)
14
- async def serve_html():
15
- logger.info("Serving HTML page")
16
- return """
17
- <html>
18
- <head>
19
- <title>AI Chemistry Chat</title>
20
- <style>
21
- body { font-family: Arial, sans-serif; margin: 20px; }
22
- #response { white-space: pre-wrap; border: 1px solid #ccc; padding: 10px; min-height: 100px; }
23
- input { width: 300px; padding: 5px; }
24
- button { padding: 5px 10px; }
25
- </style>
26
- </head>
27
- <body>
28
- <h1>AI Chemistry Chat</h1>
29
- <input type="text" id="prompt" placeholder="Ask about chemistry..." value="Tell me something I might not know about chemistry." />
30
- <button onclick="sendPrompt()">Send</button>
31
- <div id="response"></div>
32
- <script src="https://js.puter.com/v2/"></script>
33
- <script>
34
- async function sendPrompt() {
35
- const prompt = document.getElementById('prompt').value;
36
- const responseDiv = document.getElementById('response');
37
- responseDiv.innerHTML = 'Loading...';
38
- try {
39
- const resp = await puter.ai.chat(prompt, { model: 'grok-beta', stream: true });
40
- responseDiv.innerHTML = '';
41
- for await (const part of resp) {
42
- responseDiv.innerHTML += part?.text?.replaceAll('\\n', '<br>') || '';
43
- }
44
- } catch (error) {
45
- responseDiv.innerHTML = 'Error: ' + error.message;
46
- }
47
- }
48
- </script>
49
- </body>
50
- </html>
51
- """
52
 
53
- # Health check endpoint
54
- @app.get("/health")
55
- async def health():
56
- logger.info("Health check requested")
57
- return {"status": "healthy"}
 
 
1
+ from fastapi import FastAPI, UploadFile, File, HTTPException
2
+ import speech_recognition as sr
3
+ import os
4
+ import uuid
5
 
 
 
 
 
 
6
  app = FastAPI()
7
 
8
+ UPLOAD_DIR = "uploads"
9
+ os.makedirs(UPLOAD_DIR, exist_ok=True)
10
+
11
+ @app.post("/voice-to-text")
12
+ async def voice_to_text(file: UploadFile = File(...)):
13
+ # Check for .wav file
14
+ if not file.filename.endswith(".wav"):
15
+ raise HTTPException(status_code=400, detail="Only .wav files are supported")
16
+
17
+ # Save uploaded file
18
+ file_path = os.path.join(UPLOAD_DIR, f"{uuid.uuid4()}.wav")
19
+ with open(file_path, "wb") as f:
20
+ f.write(await file.read())
21
+
22
+ # Speech recognition
23
+ recognizer = sr.Recognizer()
24
+ try:
25
+ with sr.AudioFile(file_path) as source:
26
+ audio_data = recognizer.record(source)
27
+ recognized_text = recognizer.recognize_google(audio_data)
28
+ return {"recognized_text": recognized_text}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
+ except sr.UnknownValueError:
31
+ raise HTTPException(status_code=400, detail="Could not understand audio")
32
+ except sr.RequestError as e:
33
+ raise HTTPException(status_code=500, detail=f"Speech API error: {e}")
34
+ finally:
35
+ os.remove(file_path)