File size: 22,133 Bytes
775d6d5
dd6de00
 
 
84b695c
9a9538f
 
775d6d5
dd6de00
b61ee91
ec837f7
fb1d503
 
 
dd6de00
 
 
fb1d503
84b695c
 
dd6de00
 
 
 
 
 
 
 
 
 
 
 
84b695c
 
c0e25af
84b695c
 
 
 
 
 
c0e25af
 
 
 
 
 
96244d2
dd6de00
c0e25af
84b695c
 
dd6de00
96244d2
 
 
 
 
 
 
 
84b695c
 
 
 
 
c0e25af
 
 
 
 
 
 
 
 
 
96244d2
dd6de00
c0e25af
84b695c
 
dd6de00
96244d2
 
 
 
 
 
 
 
 
 
 
 
84b695c
 
 
 
 
c0e25af
 
 
 
 
 
 
 
96244d2
dd6de00
c0e25af
84b695c
 
dd6de00
96244d2
 
 
 
 
 
 
 
 
 
84b695c
 
 
 
 
c0e25af
 
 
 
 
96244d2
dd6de00
c0e25af
84b695c
 
dd6de00
96244d2
 
 
 
 
 
 
84b695c
 
 
 
 
96244d2
84b695c
 
96244d2
c0e25af
84b695c
 
 
 
dd6de00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6162d3
 
 
ff7bae6
96244d2
e6162d3
dd6de00
e6162d3
96244d2
dd6de00
e6162d3
 
 
 
51355c0
dd6de00
 
51355c0
 
dd6de00
51355c0
 
 
 
dd6de00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a9538f
 
e344f2d
 
 
1ee12e5
e344f2d
 
 
9a9538f
96244d2
775d6d5
fb1d503
775d6d5
 
96244d2
775d6d5
 
 
 
 
 
 
 
 
 
9a9538f
 
 
 
96244d2
9a9538f
 
 
96244d2
775d6d5
9a9538f
 
 
 
 
 
 
 
 
 
4049eba
431deae
96244d2
 
9a9538f
 
 
 
 
96244d2
9a9538f
 
 
 
775d6d5
96244d2
775d6d5
 
ef27d85
4049eba
ef27d85
 
9a9538f
 
e6162d3
b61ee91
 
e344f2d
 
 
1ee12e5
e344f2d
 
 
b61ee91
e344f2d
b61ee91
e344f2d
b61ee91
e344f2d
b61ee91
 
 
 
 
 
 
 
 
 
 
 
 
e344f2d
b61ee91
 
 
 
e344f2d
 
 
b61ee91
 
 
 
 
e344f2d
b61ee91
 
 
 
 
 
 
 
 
e344f2d
b61ee91
 
 
 
 
 
 
 
 
 
 
 
 
 
df243be
 
70a0c4d
dd6de00
6df9775
70a0c4d
 
 
4049eba
6df9775
42fa09f
96244d2
df243be
70a0c4d
dd6de00
70a0c4d
df243be
96244d2
c369e1a
9235666
 
c369e1a
 
 
 
 
 
 
3fac53e
c369e1a
 
 
70a0c4d
 
dd6de00
07d6350
 
 
 
 
 
 
 
9235666
dd6de00
 
 
df243be
70a0c4d
42fa09f
70a0c4d
 
 
 
f008a24
ef27d85
96244d2
ef27d85
 
 
96244d2
 
ef27d85
 
 
 
 
 
96244d2
ef27d85
ff7bae6
ef27d85
 
 
 
 
 
 
 
fb1d503
f50a979
96244d2
f50a979
 
 
 
 
96244d2
 
f50a979
 
 
 
 
 
08caa7f
f50a979
 
96244d2
08caa7f
f50a979
 
 
 
 
 
 
 
6302d85
dd6de00
6302d85
 
 
dd6de00
6302d85
dd6de00
 
 
 
 
 
0e6e27c
dd6de00
6302d85
fb1d503
 
84b695c
c0e25af
 
 
96244d2
 
c0e25af
84b695c
 
96244d2
c0e25af
84b695c
 
 
 
5aceada
afb06d8
5aceada
afb06d8
dd6de00
 
 
 
e481665
afb06d8
5aceada
 
 
84b695c
c0e25af
f58d4b8
96244d2
 
c0e25af
84b695c
 
11deaaa
 
84b695c
 
 
fb1d503
9f408e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84b695c
 
 
dd6de00
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import JSONResponse, StreamingResponse
from webscout import WEBS, YTTranscriber, LLM
from typing import Optional, List, Dict
from fastapi.encoders import jsonable_encoder
from bs4 import BeautifulSoup
import requests
import aiohttp
import asyncio
import threading
import json
from huggingface_hub import InferenceClient
from PIL import Image
import io
from easygoogletranslate import EasyGoogleTranslate

from pydantic import BaseModel

app = FastAPI()

# Define Pydantic models for request payloads
class ChatRequest(BaseModel):
    q: str
    model: str = "gpt-4o-mini"
    history: List[Dict[str, str]] = []
    proxy: Optional[str] = None

class AIRequest(BaseModel):
    user: str
    model: str = "llama3-70b"
    system: str = "Answer as concisely as possible."

@app.get("/")
async def root():
    return {"message": "API documentation can be found at /docs"}

@app.get("/health")
async def health_check():
    return {"status": "OK"}

@app.get("/api/search")
async def search(
    q: str,
    max_results: int = 10,
    timelimit: Optional[str] = None,
    safesearch: str = "moderate",
    region: str = "wt-wt",
    backend: str = "api",
    proxy: Optional[str] = None
):
    """Perform a text search."""
    try:
        with WEBS(proxy=proxy) as webs:
            results = webs.text(
                keywords=q,
                region=region,
                safesearch=safesearch,
                timelimit=timelimit,
                backend=backend,
                max_results=max_results,
            )
            return JSONResponse(content=jsonable_encoder(results))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error during search: {e}")

@app.get("/api/images")
async def images(
    q: str,
    max_results: int = 10,
    safesearch: str = "moderate",
    region: str = "wt-wt",
    timelimit: Optional[str] = None,
    size: Optional[str] = None,
    color: Optional[str] = None,
    type_image: Optional[str] = None,
    layout: Optional[str] = None,
    license_image: Optional[str] = None,
    proxy: Optional[str] = None
):
    """Perform an image search."""
    try:
        with WEBS(proxy=proxy) as webs:
            results = webs.images(
                keywords=q,
                region=region,
                safesearch=safesearch,
                timelimit=timelimit,
                size=size,
                color=color,
                type_image=type_image,
                layout=layout,
                license_image=license_image,
                max_results=max_results,
            )
            return JSONResponse(content=jsonable_encoder(results))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error during image search: {e}")

@app.get("/api/videos")
async def videos(
    q: str,
    max_results: int = 10,
    safesearch: str = "moderate",
    region: str = "wt-wt",
    timelimit: Optional[str] = None,
    resolution: Optional[str] = None,
    duration: Optional[str] = None,
    license_videos: Optional[str] = None,
    proxy: Optional[str] = None
):
    """Perform a video search."""
    try:
        with WEBS(proxy=proxy) as webs:
            results = webs.videos(
                keywords=q,
                region=region,
                safesearch=safesearch,
                timelimit=timelimit,
                resolution=resolution,
                duration=duration,
                license_videos=license_videos,
                max_results=max_results,
            )
            return JSONResponse(content=jsonable_encoder(results))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error during video search: {e}")

@app.get("/api/news")
async def news(
    q: str,
    max_results: int = 10,
    safesearch: str = "moderate",
    region: str = "wt-wt",
    timelimit: Optional[str] = None,
    proxy: Optional[str] = None
):
    """Perform a news search."""
    try:
        with WEBS(proxy=proxy) as webs:
            results = webs.news(
                keywords=q,
                region=region,
                safesearch=safesearch,
                timelimit=timelimit,
                max_results=max_results
            )
            return JSONResponse(content=jsonable_encoder(results))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error during news search: {e}")

@app.get("/api/answers")
async def answers(q: str, proxy: Optional[str] = None):
    """Get instant answers for a query."""
    try:
        with WEBS(proxy=proxy) as webs:
            results = webs.answers(keywords=q)
            return JSONResponse(content=jsonable_encoder(results))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error getting instant answers: {e}")

@app.get("/api/maps")
async def maps(
    q: str,
    place: Optional[str] = None,
    street: Optional[str] = None,
    city: Optional[str] = None,
    county: Optional[str] = None,
    state: Optional[str] = None,
    country: Optional[str] = None,
    postalcode: Optional[str] = None,
    latitude: Optional[str] = None,
    longitude: Optional[str] = None,
    radius: int = 0,
    max_results: int = 10,
    proxy: Optional[str] = None
):
    """Perform a maps search."""
    try:
        with WEBS(proxy=proxy) as webs:
            results = webs.maps(keywords=q, place=place, street=street, city=city, county=county, state=state, country=country, postalcode=postalcode, latitude=latitude, longitude=longitude, radius=radius, max_results=max_results)
            return JSONResponse(content=jsonable_encoder(results))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error during maps search: {e}")

@app.get("/api/chat")
async def chat(
    q: str,
    model: str = "gpt-4o-mini",
    proxy: Optional[str] = None
):
    """Interact with a specified large language model."""
    try:
        with WEBS(proxy=proxy) as webs:
            results = webs.chat(keywords=q, model=model)
            return JSONResponse(content=jsonable_encoder(results))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error getting chat results: {e}")

@app.post("/api/chat-post")
async def chat_post(request: ChatRequest):
    """Interact with a specified large language model with chat history."""
    try:
        with WEBS(proxy=request.proxy) as webs:
            results = webs.chat(keywords=request.q, model=request.model, chat_messages=request.history)
            return JSONResponse(content=jsonable_encoder(results))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error getting chat results: {e}")

@app.get("/api/llm")
async def llm_chat(
    model: str,
    message: str,
    system_prompt: str = Query(None, description="Optional custom system prompt")
):
    """Interact with a specified large language model with an optional system prompt."""
    try:
        messages = [{"role": "user", "content": message}]
        if system_prompt:
            messages.insert(0, {"role": "system", "content": system_prompt}) 

        llm = LLM(model=model)
        response = llm.chat(messages=messages)
        return JSONResponse(content={"response": response})
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error during LLM chat: {e}")

@app.post("/api/ai-post") 
async def ai_post(request: AIRequest):
    """Interact with a specified large language model (using AIRequest model)."""
    try:
        llm = LLM(model=request.model)
        response = llm.chat(messages=[
            {"role": "system", "content": request.system},
            {"role": "user", "content": request.user}
        ])
        return JSONResponse(content={"response": response})
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error during AI request: {e}")

def extract_text_from_webpage(html_content):
    """Extracts visible text from HTML content using BeautifulSoup."""
    soup = BeautifulSoup(html_content, "html.parser")
    # Remove unwanted tags
    for tag in soup(["script", "style", "header", "footer", "nav"]):
        tag.extract()
    # Get the remaining visible text
    visible_text = soup.get_text(strip=True)
    return visible_text

async def fetch_and_extract(url, max_chars, proxy: Optional[str] = None):
    """Fetches a URL and extracts text asynchronously."""

    async with aiohttp.ClientSession() as session:
        try:
            async with session.get(url, headers={"User-Agent": "Mozilla/5.0"}, proxy=proxy) as response:
                response.raise_for_status()
                html_content = await response.text()
                visible_text = extract_text_from_webpage(html_content)
                if len(visible_text) > max_chars:
                    visible_text = visible_text[:max_chars] + "..."
                return {"link": url, "text": visible_text}
        except (aiohttp.ClientError, requests.exceptions.RequestException) as e:
            print(f"Error fetching or processing {url}: {e}")
            return {"link": url, "text": None}

@app.get("/api/web_extract")
async def web_extract(
    url: str,
    max_chars: int = 12000,  # Adjust based on token limit
    proxy: Optional[str] = None
):
    """Extracts text from a given URL."""
    try:
        result = await fetch_and_extract(url, max_chars, proxy)
        return {"url": url, "text": result["text"]}
    except requests.exceptions.RequestException as e:
        raise HTTPException(status_code=500, detail=f"Error fetching or processing URL: {e}")

@app.get("/api/search-and-extract")
async def web_search_and_extract(
    q: str,
    max_results: int = 3,
    timelimit: Optional[str] = None,
    safesearch: str = "moderate",
    region: str = "wt-wt",
    backend: str = "html",
    max_chars: int = 6000,
    extract_only: bool = True,
    proxy: Optional[str] = None
):
    """
    Searches using WEBS, extracts text from the top results, and returns both.
    """
    try:
        with WEBS(proxy=proxy) as webs:
            # Perform WEBS search
            search_results = webs.text(keywords=q, region=region, safesearch=safesearch,
                                     timelimit=timelimit, backend=backend, max_results=max_results)

            # Extract text from each result's link asynchronously
            tasks = [fetch_and_extract(result['href'], max_chars, proxy) for result in search_results if 'href' in result]
            extracted_results = await asyncio.gather(*tasks)

            if extract_only:
                return JSONResponse(content=jsonable_encoder(extracted_results))
            else:
                return JSONResponse(content=jsonable_encoder({"search_results": search_results, "extracted_results": extracted_results}))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error during search and extraction: {e}")

def extract_text_from_webpage2(html_content):
    """Extracts visible text from HTML content using BeautifulSoup."""
    soup = BeautifulSoup(html_content, "html.parser")
    # Remove unwanted tags
    for tag in soup(["script", "style", "header", "footer", "nav"]):
        tag.extract()
    # Get the remaining visible text
    visible_text = soup.get_text(strip=True)
    return visible_text

def fetch_and_extract2(url, max_chars, proxy: Optional[str] = None):
    """Fetches a URL and extracts text using threading."""
    proxies = {'http': proxy, 'https': proxy} if proxy else None
    try:
        response = requests.get(url, headers={"User-Agent": "Mozilla/5.0"}, proxies=proxies)
        response.raise_for_status()
        html_content = response.text
        visible_text = extract_text_from_webpage2(html_content)
        if len(visible_text) > max_chars:
            visible_text = visible_text[:max_chars] + "..."
        return {"link": url, "text": visible_text}
    except (requests.exceptions.RequestException) as e:
        print(f"Error fetching or processing {url}: {e}")
        return {"link": url, "text": None}

@app.get("/api/websearch-and-extract-threading")
def web_search_and_extract_threading(
    q: str,
    max_results: int = 3,
    timelimit: Optional[str] = None,
    safesearch: str = "moderate",
    region: str = "wt-wt",
    backend: str = "html",
    max_chars: int = 6000,
    extract_only: bool = True,
    proxy: Optional[str] = None
):
    """
    Searches using WEBS, extracts text from the top results using threading, and returns both.
    """
    try:
        with WEBS(proxy=proxy) as webs:
            # Perform WEBS search
            search_results = webs.text(keywords=q, region=region, safesearch=safesearch,
                                     timelimit=timelimit, backend=backend, max_results=max_results)

            # Extract text from each result's link using threading
            extracted_results = []
            threads = []
            for result in search_results:
                if 'href' in result:
                    thread = threading.Thread(target=lambda: extracted_results.append(fetch_and_extract2(result['href'], max_chars, proxy)))
                    threads.append(thread)
                    thread.start()

            # Wait for all threads to finish
            for thread in threads:
                thread.join()

            if extract_only:
                return JSONResponse(content=jsonable_encoder(extracted_results))
            else:
                return JSONResponse(content=jsonable_encoder({"search_results": search_results, "extracted_results": extracted_results}))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error during search and extraction: {e}")

@app.get("/api/adv_web_search")
async def adv_web_search(
    q: str,
    model: str = "gpt-4o-mini",  # Use webs.chat by default
    max_results: int = 5,
    timelimit: Optional[str] = None,
    safesearch: str = "moderate",
    region: str = "wt-wt",
    backend: str = "html",
    max_chars: int = 15000,
    system_prompt: str = "You are an advanced AI chatbot. Provide the best answer to the user based on Google search results.",
    proxy: Optional[str] = None
):
    """
    Combines web search, web extraction, and chat model for advanced search.
    """
    try:
        with WEBS(proxy=proxy) as webs:
            search_results = webs.text(keywords=q, region=region,
                                     safesearch=safesearch,
                                     timelimit=timelimit, backend=backend,
                                     max_results=max_results)

            # 2. Extract text from top search result URLs asynchronously
            extracted_text = ""
            tasks = [fetch_and_extract(result['href'], 6000, proxy) for result in search_results if 'href' in result]
            extracted_results = await asyncio.gather(*tasks)
            for result in extracted_results:
                if result['text'] and len(extracted_text) < max_chars:
                    extracted_text += f"## Content from: {result['link']}\n\n{result['text']}\n\n"

            extracted_text[:max_chars]


        # 3. Construct the prompt for the chat model
        ai_prompt = (
            f"User Query: {q}\n\n"
            f"Please provide a detailed and accurate answer to the user's query. Include relevant information extracted from the search results below. Ensure to cite sources by providing links to the original content where applicable. Format your response as follows:\n\n"
            f"1. **Answer:** Provide a clear and comprehensive answer to the user's query.\n"
            f"2. **Details:** Include any additional relevant details or explanations.\n"
            f"3. **Sources:** List the sources of the information with clickable links for further reading.\n\n"
            f"Search Results:\n{extracted_text}"
        )

        # 4. Get the chat model's response using webs.chat 
        with WEBS(proxy=proxy) as webs:
            response = webs.chat(keywords=ai_prompt, model=model)

        # 5. Return the results
        return JSONResponse(content={"response": response})

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error during advanced search: {e}")


@app.get("/api/website_summarizer")
async def website_summarizer(url: str, proxy: Optional[str] = None):
    """Summarizes the content of a given URL using a chat model."""
    try:
        # Extract text from the given URL
        proxies = {'http': proxy, 'https': proxy} if proxy else None
        response = requests.get(url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"}, proxies=proxies)
        response.raise_for_status()
        visible_text = extract_text_from_webpage(response.text)
        if len(visible_text) > 7500:  # Adjust max_chars based on your needs
            visible_text = visible_text[:7500] + "..."

        # Use chat model to summarize the extracted text
        with WEBS(proxy=proxy) as webs:
            summary_prompt = f"Summarize this in detail in Paragraph: {visible_text}"
            summary_result = webs.chat(keywords=summary_prompt, model="gpt-4o-mini")

        # Return the summary result
        return JSONResponse(content=jsonable_encoder({summary_result}))

    except requests.exceptions.RequestException as e:
        raise HTTPException(status_code=500, detail=f"Error fetching or processing URL: {e}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error during summarization: {e}")

@app.get("/api/ask_website")
async def ask_website(url: str, question: str, model: str = "llama-3-70b", proxy: Optional[str] = None):
    """
    Asks a question about the content of a given website.
    """
    try:
        # Extract text from the given URL
        proxies = {'http': proxy, 'https': proxy} if proxy else None
        response = requests.get(url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"}, proxies=proxies)
        response.raise_for_status()
        visible_text = extract_text_from_webpage(response.text)
        if len(visible_text) > 7500:  # Adjust max_chars based on your needs
            visible_text = visible_text[:7500] + "..."

        # Construct a prompt for the chat model
        prompt = f"Based on the following text, answer this question in Paragraph: [QUESTION] {question} [TEXT] {visible_text}"

        # Use chat model to get the answer
        with WEBS(proxy=proxy) as webs:
            answer_result = webs.chat(keywords=prompt, model=model)

        # Return the answer result
        return JSONResponse(content=jsonable_encoder({answer_result}))

    except requests.exceptions.RequestException as e:
        raise HTTPException(status_code=500, detail=f"Error fetching or processing URL: {e}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error during question answering: {e}")

# Stable Diffusion client
client_sd3 = InferenceClient("stabilityai/stable-diffusion-3-medium-diffusers")

@app.get("/api/sd3")
def sd3(prompt: str = "", steps: int = 20, width: int = 1000, height: int = 1000):
    try:
        image = client_sd3.text_to_image(
            prompt=f"{prompt}, hd, high quality, 4k, masterpiece",
            num_inference_steps=steps,
            width=width,
            height=height
        )
        image = Image.open(io.BytesIO(image))
        return image 
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error during image generation: {e}")

@app.get("/api/translate")
async def translate(
    q: str,
    from_: Optional[str] = None,
    to: str = "en",
    proxy: Optional[str] = None
):
    """Translate text."""
    try:
        with WEBS(proxy=proxy) as webs:
            results = webs.translate(keywords=q, from_=from_, to=to)
            return JSONResponse(content=jsonable_encoder(results))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error during translation: {e}")

@app.get("/api/google_translate")
def google_translate(q: str, from_: Optional[str] = 'auto', to: str = "en"):
    try:
        translator = EasyGoogleTranslate(
            source_language=from_,
            target_language=to,
            timeout=10
        )
        result = translator.translate(q)
        return JSONResponse(content=jsonable_encoder({"detected_language": from_ , "original": q , "translated": result}))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error during translation: {e}")

@app.get("/api/youtube/transcript")
async def youtube_transcript(
    video_url: str,
    preserve_formatting: bool = False,
    proxy: Optional[str] = None  # Add proxy parameter
):
    """Get the transcript of a YouTube video."""
    try:
        proxies = {"http": proxy, "https": proxy} if proxy else None
        transcript = YTTranscriber.get_transcript(video_url, languages=None, preserve_formatting=preserve_formatting, proxies=proxies)
        return JSONResponse(content=jsonable_encoder(transcript))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error getting YouTube transcript: {e}")

@app.get("/weather/json/{location}")
def get_weather_json(location: str):
    url = f"https://wttr.in/{location}?format=j1"
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()
    else:
        return {"error": f"Unable to fetch weather data. Status code: {response.status_code}"}

@app.get("/weather/ascii/{location}")
def get_ascii_weather(location: str):
    url = f"https://wttr.in/{location}"
    response = requests.get(url, headers={'User-Agent': 'curl'})
    if response.status_code == 200:
        return response.text
    else:
        return {"error": f"Unable to fetch weather data. Status code: {response.status_code}"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8083)