Update app.py
#498
by
						
johnpraise
	
							
						- opened
							
					
    	
        app.py
    CHANGED
    
    | @@ -1,61 +1,123 @@ | |
| 1 | 
            -
            from smolagents import CodeAgent,DuckDuckGoSearchTool,  | 
| 2 | 
            -
            import datetime
         | 
| 3 | 
             
            import requests
         | 
| 4 | 
            -
            import  | 
|  | |
| 5 | 
             
            import yaml
         | 
| 6 | 
            -
             | 
| 7 | 
            -
             | 
| 8 | 
            -
            from  | 
|  | |
| 9 |  | 
| 10 | 
            -
             | 
| 11 | 
             
            @tool
         | 
| 12 | 
            -
            def  | 
| 13 | 
            -
                 | 
| 14 | 
            -
                """A tool that does nothing yet 
         | 
| 15 | 
             
                Args:
         | 
| 16 | 
            -
                     | 
| 17 | 
            -
             | 
|  | |
| 18 | 
             
                """
         | 
| 19 | 
            -
                 | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 20 |  | 
|  | |
| 21 | 
             
            @tool
         | 
| 22 | 
            -
            def  | 
| 23 | 
            -
                """ | 
| 24 | 
             
                Args:
         | 
| 25 | 
            -
                     | 
|  | |
|  | |
| 26 | 
             
                """
         | 
| 27 | 
            -
                 | 
| 28 | 
            -
             | 
| 29 | 
            -
             | 
| 30 | 
            -
                    # Get current time in that timezone
         | 
| 31 | 
            -
                    local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
         | 
| 32 | 
            -
                    return f"The current local time in {timezone} is: {local_time}"
         | 
| 33 | 
            -
                except Exception as e:
         | 
| 34 | 
            -
                    return f"Error fetching time for timezone '{timezone}': {str(e)}"
         | 
| 35 |  | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 36 |  | 
| 37 | 
            -
             | 
| 38 | 
            -
             | 
| 39 | 
            -
             | 
| 40 | 
            -
             | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 41 |  | 
| 42 | 
            -
             | 
| 43 | 
            -
             | 
| 44 | 
            -
             | 
| 45 | 
            -
             | 
| 46 | 
            -
             | 
| 47 | 
            -
             | 
|  | |
| 48 |  | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 49 |  | 
| 50 | 
            -
             | 
| 51 | 
            -
             | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 52 |  | 
|  | |
| 53 | 
             
            with open("prompts.yaml", 'r') as stream:
         | 
| 54 | 
             
                prompt_templates = yaml.safe_load(stream)
         | 
| 55 | 
            -
             | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 56 | 
             
            agent = CodeAgent(
         | 
| 57 | 
             
                model=model,
         | 
| 58 | 
            -
                tools=[ | 
| 59 | 
             
                max_steps=6,
         | 
| 60 | 
             
                verbosity_level=1,
         | 
| 61 | 
             
                grammar=None,
         | 
| @@ -65,5 +127,4 @@ agent = CodeAgent( | |
| 65 | 
             
                prompt_templates=prompt_templates
         | 
| 66 | 
             
            )
         | 
| 67 |  | 
| 68 | 
            -
             | 
| 69 | 
            -
            GradioUI(agent).launch()
         | 
|  | |
| 1 | 
            +
            from smolagents import CodeAgent, DuckDuckGoSearchTool, tool, load_tool, HfApiModel
         | 
|  | |
| 2 | 
             
            import requests
         | 
| 3 | 
            +
            from bs4 import BeautifulSoup
         | 
| 4 | 
            +
            import pandas as pd
         | 
| 5 | 
             
            import yaml
         | 
| 6 | 
            +
            import datetime
         | 
| 7 | 
            +
            import pytz
         | 
| 8 | 
            +
            from textblob import TextBlob  # Simple sentiment analysis
         | 
| 9 | 
            +
            from Gradio_UI import GradioUI  # For building Gradio UI
         | 
| 10 |  | 
| 11 | 
            +
            #### TOOL 1: Scrape GSMArena Reviews & Specs ####
         | 
| 12 | 
             
            @tool
         | 
| 13 | 
            +
            def scrape_gsmarena_reviews(phone_name: str) -> dict:
         | 
| 14 | 
            +
                """Scrapes GSMArena for reviews and specs of a given smartphone.
         | 
|  | |
| 15 | 
             
                Args:
         | 
| 16 | 
            +
                    phone_name: The model name (exact/substantial match).
         | 
| 17 | 
            +
                Returns:
         | 
| 18 | 
            +
                    Dictionary with keys: 'reviews', 'price', 'specs'
         | 
| 19 | 
             
                """
         | 
| 20 | 
            +
                # You’ll need accurate GSMArena URL fetching logic per phone_name.
         | 
| 21 | 
            +
                search_url = f"https://www.gsmarena.com/res.php3?sSearch={phone_name.replace(' ', '+')}"
         | 
| 22 | 
            +
                res = requests.get(search_url)
         | 
| 23 | 
            +
                soup = BeautifulSoup(res.text, "html.parser")
         | 
| 24 | 
            +
                # Find first matching phone page link
         | 
| 25 | 
            +
                link = soup.find("div", class_="makers").find("a")["href"]
         | 
| 26 | 
            +
                phone_url = f"https://www.gsmarena.com/{link}"
         | 
| 27 | 
            +
                phone_page = requests.get(phone_url)
         | 
| 28 | 
            +
                phone_soup = BeautifulSoup(phone_page.text, "html.parser")
         | 
| 29 | 
            +
                # Parse reviews and price
         | 
| 30 | 
            +
                reviews = []
         | 
| 31 | 
            +
                for rev in phone_soup.find_all("div", class_="user-review"):
         | 
| 32 | 
            +
                    reviews.append(rev.text)
         | 
| 33 | 
            +
                # Fallback if structure changes
         | 
| 34 | 
            +
                price = "Unknown"
         | 
| 35 | 
            +
                for spec in phone_soup.find_all("td", string="Price"):
         | 
| 36 | 
            +
                    price = spec.find_next_sibling("td").text
         | 
| 37 | 
            +
                specs = {li.find('span').text: li.text for li in phone_soup.find_all("li")}
         | 
| 38 | 
            +
                return {"reviews": reviews, "price": price, "specs": specs}
         | 
| 39 |  | 
| 40 | 
            +
            #### TOOL 2: Churn/Sentiment Scoring ####
         | 
| 41 | 
             
            @tool
         | 
| 42 | 
            +
            def score_churn(reviews: list) -> float:
         | 
| 43 | 
            +
                """Calculates aggregate churn score from reviews using sentiment analysis.
         | 
| 44 | 
             
                Args:
         | 
| 45 | 
            +
                    reviews: List of review texts.
         | 
| 46 | 
            +
                Returns:
         | 
| 47 | 
            +
                    float churn score (avg polarity; lower = less churn)
         | 
| 48 | 
             
                """
         | 
| 49 | 
            +
                scores = [TextBlob(r).sentiment.polarity for r in reviews]
         | 
| 50 | 
            +
                churn_score = 1 - (sum(scores) / len(scores)) if scores else 1  # Lower is better
         | 
| 51 | 
            +
                return churn_score
         | 
|  | |
|  | |
|  | |
|  | |
|  | |
| 52 |  | 
| 53 | 
            +
            #### TOOL 3: Find Competing Phones ####
         | 
| 54 | 
            +
            @tool
         | 
| 55 | 
            +
            def find_competitors(price: str) -> list:
         | 
| 56 | 
            +
                """Scrapes or queries GSM Arena for phones in the same price bracket.
         | 
| 57 | 
            +
                Args:
         | 
| 58 | 
            +
                    price: The reference price.
         | 
| 59 | 
            +
                Returns:
         | 
| 60 | 
            +
                    List of phone names.
         | 
| 61 | 
            +
                """
         | 
| 62 | 
            +
                price_value = ''.join(filter(str.isdigit, price))
         | 
| 63 | 
            +
                # For demo: just pick other search results in same price bracket
         | 
| 64 | 
            +
                # Expand with real price logic as needed
         | 
| 65 | 
            +
                return ["Phone1", "Phone2", "Phone3"]
         | 
| 66 |  | 
| 67 | 
            +
            #### FINAL TOOL: Recommend Phone ####
         | 
| 68 | 
            +
            @tool
         | 
| 69 | 
            +
            def recommend_smartphone(user_phone: str):
         | 
| 70 | 
            +
                """Main logic for recommendation."""
         | 
| 71 | 
            +
                user_data = scrape_gsmarena_reviews(user_phone)
         | 
| 72 | 
            +
                user_reviews = user_data['reviews']
         | 
| 73 | 
            +
                user_score = score_churn(user_reviews)
         | 
| 74 | 
            +
                user_price = user_data['price']
         | 
| 75 | 
            +
                competitors = find_competitors(user_price)
         | 
| 76 | 
            +
                best_score = user_score
         | 
| 77 | 
            +
                best_phone = user_phone
         | 
| 78 |  | 
| 79 | 
            +
                for c in competitors:
         | 
| 80 | 
            +
                    c_data = scrape_gsmarena_reviews(c)
         | 
| 81 | 
            +
                    c_reviews = c_data['reviews']
         | 
| 82 | 
            +
                    c_score = score_churn(c_reviews)
         | 
| 83 | 
            +
                    if c_score < best_score:
         | 
| 84 | 
            +
                        best_score = c_score
         | 
| 85 | 
            +
                        best_phone = c
         | 
| 86 |  | 
| 87 | 
            +
                # If best_phone is not user's, recommend; else try next bracket
         | 
| 88 | 
            +
                result = {
         | 
| 89 | 
            +
                    "Your phone": user_phone,
         | 
| 90 | 
            +
                    "Your phone score": user_score,
         | 
| 91 | 
            +
                    "Best competitor": best_phone,
         | 
| 92 | 
            +
                    "Best score": best_score,
         | 
| 93 | 
            +
                    "Recommended": "Yes" if best_phone != user_phone else "No better phone in range",
         | 
| 94 | 
            +
                }
         | 
| 95 | 
            +
                return result
         | 
| 96 |  | 
| 97 | 
            +
            #### Gradio UI ####
         | 
| 98 | 
            +
            def agent_ui(user_phone_name):
         | 
| 99 | 
            +
                """Gradio UI interface handler."""
         | 
| 100 | 
            +
                result = recommend_smartphone(user_phone_name)
         | 
| 101 | 
            +
                return f"""
         | 
| 102 | 
            +
                **Your phone:** {result['Your phone']}
         | 
| 103 | 
            +
                **Churn score:** {result['Your phone score']}
         | 
| 104 | 
            +
                **Best alternative:** {result['Best competitor']} (score: {result['Best score']})
         | 
| 105 | 
            +
                **Recommended:** {result['Recommended']}
         | 
| 106 | 
            +
                """
         | 
| 107 |  | 
| 108 | 
            +
            # Connect everything for Hugging Face Space
         | 
| 109 | 
             
            with open("prompts.yaml", 'r') as stream:
         | 
| 110 | 
             
                prompt_templates = yaml.safe_load(stream)
         | 
| 111 | 
            +
             | 
| 112 | 
            +
            model = HfApiModel(
         | 
| 113 | 
            +
                max_tokens=2096,
         | 
| 114 | 
            +
                temperature=0.5,
         | 
| 115 | 
            +
                model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
         | 
| 116 | 
            +
            )
         | 
| 117 | 
            +
             | 
| 118 | 
             
            agent = CodeAgent(
         | 
| 119 | 
             
                model=model,
         | 
| 120 | 
            +
                tools=[recommend_smartphone],  # add your main tool, you can add others as desired
         | 
| 121 | 
             
                max_steps=6,
         | 
| 122 | 
             
                verbosity_level=1,
         | 
| 123 | 
             
                grammar=None,
         | 
|  | |
| 127 | 
             
                prompt_templates=prompt_templates
         | 
| 128 | 
             
            )
         | 
| 129 |  | 
| 130 | 
            +
            GradioUI(agent_ui).launch()
         | 
|  | 
